Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Lens] Metric trend PoC - toggle switch #138804

Closed
wants to merge 22 commits into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

export const EXPRESSION_METRIC_NAME = 'metricVis';
export const EXPRESSION_METRIC_TRENDLINE_NAME = 'metricTrendline';

export const LabelPosition = {
BOTTOM: 'bottom',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/*
* 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 { i18n } from '@kbn/i18n';

import {
validateAccessor,
getColumnByAccessor,
prepareLogTable,
Dimension,
} from '@kbn/visualizations-plugin/common/utils';
import { DatatableRow } from '@kbn/expressions-plugin/common';
import { MetricWTrend } from '@elastic/charts';
import type { TrendlineExpressionFunctionDefinition } from '../types';
import { EXPRESSION_METRIC_TRENDLINE_NAME } from '../constants';

export const metricTrendlineFunction = (): TrendlineExpressionFunctionDefinition => ({
name: EXPRESSION_METRIC_TRENDLINE_NAME,
inputTypes: ['datatable'],
type: EXPRESSION_METRIC_TRENDLINE_NAME,
help: i18n.translate('expressionMetricTrendline.function.help', {
defaultMessage: 'Metric visualization',
}),
args: {
metric: {
types: ['vis_dimension', 'string'],
help: i18n.translate('expressionMetricTrendline.function.metric.help', {
defaultMessage: 'The primary metric.',
}),
required: true,
},
timeField: {
types: ['vis_dimension', 'string'],
help: i18n.translate('expressionMetricTrendline.function.metric.help', {
defaultMessage: 'The time field for the trend line',
}),
required: true,
},
breakdownBy: {
types: ['vis_dimension', 'string'],
help: i18n.translate('expressionMetricTrendline.function.breakdownBy.help', {
defaultMessage: 'The dimension containing the labels for sub-categories.',
}),
},
table: {
types: ['datatable'],
help: i18n.translate('expressionMetricTrendline.function.table.help', {
defaultMessage: 'A data table',
}),
multi: false,
},
inspectorTableId: {
types: ['string'],
help: i18n.translate('expressionMetricTrendline.function.inspectorTableId.help', {
defaultMessage: 'An ID for the inspector table',
}),
multi: false,
default: 'trendline',
},
},
fn(input, args, handlers) {
const table = args.table;
validateAccessor(args.metric, table.columns);
validateAccessor(args.timeField, table.columns);
validateAccessor(args.breakdownBy, table.columns);

const argsTable: Dimension[] = [
[
[args.metric],
i18n.translate('expressionMetricVis.function.dimension.metric', {
defaultMessage: 'Metric',
}),
],
[
[args.timeField],
i18n.translate('expressionMetricVis.function.dimension.timeField', {
defaultMessage: 'Time field',
}),
],
];

if (args.breakdownBy) {
argsTable.push([
[args.breakdownBy],
i18n.translate('expressionMetricVis.function.dimension.splitGroup', {
defaultMessage: 'Split group',
}),
]);
}

const inspectorTable = prepareLogTable(table, argsTable, true);

const metricColId = getColumnByAccessor(args.metric, table.columns)?.id;
const timeColId = getColumnByAccessor(args.timeField, table.columns)?.id;

if (!metricColId || !timeColId) {
throw new Error("Metric trendline - couldn't find metric or time column!");
}

const trends: Record<string, MetricWTrend['trend']> = {};

if (!args.breakdownBy) {
trends.default = table.rows.map((row) => ({
x: row[timeColId],
y: row[metricColId],
})); // TODO is the table ordered correctly?
} else {
const breakdownByColId = getColumnByAccessor(args.breakdownBy, table.columns)?.id;

if (!breakdownByColId) {
throw new Error("Metric trendline - couldn't find breakdown column!");
}

const rowsByBreakdown: Record<string, DatatableRow[]> = {};
table.rows.forEach((row) => {
const breakdownTerm = row[breakdownByColId];
if (!(breakdownTerm in rowsByBreakdown)) {
rowsByBreakdown[breakdownTerm] = [];
}
rowsByBreakdown[breakdownTerm].push(row);
});

for (const breakdownTerm in rowsByBreakdown) {
if (!rowsByBreakdown.hasOwnProperty(breakdownTerm)) continue;
trends[breakdownTerm] = rowsByBreakdown[breakdownTerm].map((row) => ({
x: row[timeColId],
y: row[metricColId],
}));
}
}

return {
type: EXPRESSION_METRIC_TRENDLINE_NAME,
trends,
inspectorTable,
inspectorTableId: args.inspectorTableId,
};
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
import { LayoutDirection } from '@elastic/charts';
import { visType } from '../types';
import { MetricVisExpressionFunctionDefinition } from '../types';
import { EXPRESSION_METRIC_NAME } from '../constants';
import { EXPRESSION_METRIC_NAME, EXPRESSION_METRIC_TRENDLINE_NAME } from '../constants';

export const metricVisFunction = (): MetricVisExpressionFunctionDefinition => ({
name: EXPRESSION_METRIC_NAME,
Expand Down Expand Up @@ -51,6 +51,12 @@ export const metricVisFunction = (): MetricVisExpressionFunctionDefinition => ({
defaultMessage: 'The dimension containing the labels for sub-categories.',
}),
},
trendline: {
types: [EXPRESSION_METRIC_TRENDLINE_NAME],
help: i18n.translate('expressionMetricVis.function.trendline.help', {
defaultMessage: 'An optional trendline configuration',
}),
},
subtitle: {
types: ['string'],
help: i18n.translate('expressionMetricVis.function.subtitle.help', {
Expand Down Expand Up @@ -98,14 +104,22 @@ export const metricVisFunction = (): MetricVisExpressionFunctionDefinition => ({
'Specifies the minimum number of tiles in the metric grid regardless of the input data.',
}),
},
inspectorTableId: {
types: ['string'],
help: i18n.translate('expressionMetricVis.function.inspectorTableId.help', {
defaultMessage: 'An ID for the inspector table',
}),
multi: false,
default: 'default',
},
},
fn(input, args, handlers) {
validateAccessor(args.metric, input.columns);
validateAccessor(args.secondaryMetric, input.columns);
validateAccessor(args.breakdownBy, input.columns);

if (handlers?.inspectorAdapters?.tables) {
handlers.inspectorAdapters.tables.reset();
// handlers.inspectorAdapters.tables.reset();
handlers.inspectorAdapters.tables.allowCsvExport = true;

const argsTable: Dimension[] = [
Expand Down Expand Up @@ -145,7 +159,13 @@ export const metricVisFunction = (): MetricVisExpressionFunctionDefinition => ({
}

const logTable = prepareLogTable(input, argsTable, true);
handlers.inspectorAdapters.tables.logDatatable('default', logTable);
handlers.inspectorAdapters.tables.logDatatable(args.inspectorTableId, logTable);
if (args.trendline) {
handlers.inspectorAdapters.tables.logDatatable(
args.trendline.inspectorTableId,
args.trendline.inspectorTable
);
}
}

return {
Expand All @@ -163,6 +183,7 @@ export const metricVisFunction = (): MetricVisExpressionFunctionDefinition => ({
progressDirection: args.progressDirection,
maxCols: args.maxCols,
minTiles: args.minTiles,
trends: args.trendline?.trends,
},
dimensions: {
metric: args.metric,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ export type {

export { metricVisFunction } from './expression_functions';

export { EXPRESSION_METRIC_NAME } from './constants';
export { EXPRESSION_METRIC_NAME, EXPRESSION_METRIC_TRENDLINE_NAME } from './constants';
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,31 @@
*/

import type { PaletteOutput } from '@kbn/coloring';
import { LayoutDirection } from '@elastic/charts';
import { LayoutDirection, MetricWTrend } from '@elastic/charts';
import {
Datatable,
ExpressionFunctionDefinition,
ExpressionValueRender,
} from '@kbn/expressions-plugin/common';
import { ExpressionValueVisDimension } from '@kbn/visualizations-plugin/common';
import { ExpressionValueVisDimension, prepareLogTable } from '@kbn/visualizations-plugin/common';
import { CustomPaletteState } from '@kbn/charts-plugin/common';
import { VisParams, visType } from './expression_renderers';
import { EXPRESSION_METRIC_NAME } from '../constants';
import { EXPRESSION_METRIC_NAME, EXPRESSION_METRIC_TRENDLINE_NAME } from '../constants';

export interface MetricArguments {
metric: ExpressionValueVisDimension | string;
secondaryMetric?: ExpressionValueVisDimension | string;
max?: ExpressionValueVisDimension | string;
breakdownBy?: ExpressionValueVisDimension | string;
trendline?: TrendlineResult;
subtitle?: string;
secondaryPrefix?: string;
progressDirection: LayoutDirection;
color?: string;
palette?: PaletteOutput<CustomPaletteState>;
maxCols: number;
minTiles?: number;
inspectorTableId: string;
}

export type MetricInput = Datatable;
Expand All @@ -46,3 +48,25 @@ export type MetricVisExpressionFunctionDefinition = ExpressionFunctionDefinition
MetricArguments,
ExpressionValueRender<MetricVisRenderConfig>
>;

export interface TrendlineArguments {
metric: ExpressionValueVisDimension | string;
timeField: ExpressionValueVisDimension | string;
breakdownBy?: ExpressionValueVisDimension | string;
table: Datatable;
inspectorTableId: string;
}

export interface TrendlineResult {
type: typeof EXPRESSION_METRIC_TRENDLINE_NAME;
trends: Record<string, MetricWTrend['trend']>;
inspectorTable: ReturnType<typeof prepareLogTable>;
inspectorTableId: string;
}

export type TrendlineExpressionFunctionDefinition = ExpressionFunctionDefinition<
typeof EXPRESSION_METRIC_TRENDLINE_NAME,
Datatable,
TrendlineArguments,
TrendlineResult
>;
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import { ExpressionValueVisDimension } from '@kbn/visualizations-plugin/common';
import { CustomPaletteState } from '@kbn/charts-plugin/common';
import { LayoutDirection } from '@elastic/charts';
import { TrendlineResult } from './expression_functions';

export const visType = 'metric';

Expand All @@ -27,6 +28,7 @@ export interface MetricVisParam {
progressDirection: LayoutDirection;
maxCols: number;
minTiles?: number;
trends?: TrendlineResult['trends'];
}

export interface VisParams {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ import {
isMetricElementEvent,
RenderChangeListener,
Settings,
MetricBase,
MetricWTrend,
} 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 @@ -223,17 +224,9 @@ export const MetricVis = ({
.getConverterFor('text');
}

let getProgressBarConfig = (_row: DatatableRow): Partial<MetricWProgress> => ({});

const maxColId = config.dimensions.max
? getColumnByAccessor(config.dimensions.max, data.columns)?.id
: undefined;
if (maxColId) {
getProgressBarConfig = (_row: DatatableRow): Partial<MetricWProgress> => ({
domainMax: _row[maxColId],
progressBarDirection: config.metric.progressDirection,
});
}

const metricConfigs: MetricSpec['data'][number] = (
breakdownByColumn ? data.rows : data.rows.slice(0, 1)
Expand All @@ -243,7 +236,7 @@ export const MetricVis = ({
? formatBreakdownValue(row[breakdownByColumn.id])
: primaryMetricColumn.name;
const subtitle = breakdownByColumn ? primaryMetricColumn.name : config.metric.subtitle;
return {
const baseMetric: MetricBase = {
value,
valueFormatter: formatPrimaryMetric,
title,
Expand Down Expand Up @@ -272,8 +265,29 @@ export const MetricVis = ({
rowIdx
) ?? defaultColor
: config.metric.color ?? defaultColor,
...getProgressBarConfig(row),
};

const trendId = breakdownByColumn ? row[breakdownByColumn.id] : 'default';
if (config.metric.trends && config.metric.trends[trendId]) {
const metricWTrend: MetricWTrend = {
...baseMetric,
trend: config.metric.trends[trendId],
};

return metricWTrend;
}

if (maxColId && config.metric.progressDirection) {
const metricWProgress: MetricWProgress = {
...baseMetric,
domainMax: row[maxColId],
progressBarDirection: config.metric.progressDirection,
};

return metricWProgress;
}

return baseMetric;
});

if (config.metric.minTiles) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export function plugin() {
}

export { getDataBoundsForPalette } from './utils';
export { EXPRESSION_METRIC_NAME, EXPRESSION_METRIC_TRENDLINE_NAME } from '../common';
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { setFormatService, setPaletteService } from './services';
import { getMetricVisRenderer } from './expression_renderers';
import { setThemeService } from './services/theme_service';
import { setUiSettingsService } from './services/ui_settings';
import { metricTrendlineFunction } from '../common/expression_functions/metric_trendline_function';

/** @internal */
export interface ExpressionMetricPluginSetup {
Expand Down Expand Up @@ -45,6 +46,7 @@ export class ExpressionMetricPlugin implements Plugin {
});

expressions.registerFunction(metricVisFunction);
expressions.registerFunction(metricTrendlineFunction);
expressions.registerRenderer(getMetricVisRenderer({ getStartDeps }));

setUiSettingsService(core.uiSettings);
Expand Down
Loading