Skip to content

Commit

Permalink
Control round and decimal places in Gauge Visualization when using ag…
Browse files Browse the repository at this point in the history
…gregate functions like average (elastic#91293) (elastic#93014)

* Add field for providing format in percentage mode

* Fix CI

* Add tests

* Fix ci

* Fix some remarks

* Fix ci

* Fix some remarks

* Fix ci

* Fix width

* Fix some remarks

* Fix text

* Fix i18n

* Remove unneeded import

* Remove unneeded code

Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>

Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
  • Loading branch information
VladLasitsa and kibanamachine authored Mar 1, 2021
1 parent 9a97394 commit 0772e20
Show file tree
Hide file tree
Showing 27 changed files with 280 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ export { NumberInputOption } from './number_input';
export { RangeOption } from './range';
export { RequiredNumberInputOption } from './required_number_input';
export { TextInputOption } from './text_input';
export { PercentageModeOption } from './percentage_mode';
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* 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 React from 'react';
import { mountWithIntl } from '@kbn/test/jest';
import { PercentageModeOption, PercentageModeOptionProps } from './percentage_mode';
import { EuiFieldText } from '@elastic/eui';

describe('PercentageModeOption', () => {
let props: PercentageModeOptionProps;
let component;
beforeAll(() => {
props = {
percentageMode: true,
setValue: jest.fn(),
};
});

it('renders the EuiFieldText', () => {
component = mountWithIntl(<PercentageModeOption {...props} />);
expect(component.find(EuiFieldText).length).toBe(1);
});

it('should call setValue when value was putted in fieldText', () => {
component = mountWithIntl(<PercentageModeOption {...props} />);
const fieldText = component.find(EuiFieldText);
fieldText.props().onChange!({
target: {
value: '0.0%',
},
} as React.ChangeEvent<HTMLInputElement>);

expect(props.setValue).toHaveBeenCalledWith('percentageFormatPattern', '0.0%');
});

it('fieldText should be disabled when percentageMode is false', () => {
props.percentageMode = false;
component = mountWithIntl(<PercentageModeOption {...props} />);
const fieldText = component.find(EuiFieldText);

expect(fieldText.props().disabled).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* 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 React from 'react';
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n/react';
import { EuiFieldText, EuiFormRow, EuiLink } from '@elastic/eui';
import { SwitchOption } from './switch';
import { useKibana } from '../../../../kibana_react/public';
import { UI_SETTINGS } from '../../../../data/public';

export interface PercentageModeOptionProps {
setValue: (
paramName: 'percentageMode' | 'percentageFormatPattern',
value: boolean | string | undefined
) => void;
percentageMode: boolean;
formatPattern?: string;
'data-test-subj'?: string;
}

function PercentageModeOption({
'data-test-subj': dataTestSubj,
setValue,
percentageMode,
formatPattern,
}: PercentageModeOptionProps) {
const { services } = useKibana();
const defaultPattern = services.uiSettings?.get(UI_SETTINGS.FORMAT_PERCENT_DEFAULT_PATTERN);

return (
<>
<SwitchOption
data-test-subj={dataTestSubj}
label={i18n.translate('visDefaultEditor.options.percentageMode.percentageModeLabel', {
defaultMessage: 'Percentage mode',
})}
paramName="percentageMode"
value={percentageMode}
setValue={setValue}
/>
<EuiFormRow
fullWidth
label={
<FormattedMessage
id="visDefaultEditor.options.percentageMode.numeralLabel"
defaultMessage="Format pattern"
/>
}
helpText={
<EuiLink target="_blank" href="https://adamwdraper.github.io/Numeral-js/">
<FormattedMessage
id="visDefaultEditor.options.percentageMode.documentationLabel"
defaultMessage="Numeral.js documentation"
/>
</EuiLink>
}
>
<EuiFieldText
fullWidth
compressed
data-test-subj={`${dataTestSubj}FormatPattern`}
value={formatPattern || ''}
placeholder={defaultPattern}
onChange={(e) => {
setValue('percentageFormatPattern', e.target.value ? e.target.value : undefined);
}}
disabled={!percentageMode}
/>
</EuiFormRow>
</>
);
}

export { PercentageModeOption };
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
SetColorSchemaOptionsValue,
ColorSchemaOptions,
RangeOption,
PercentageModeOption,
} from '../../../vis_default_editor/public';
import { ColorMode, colorSchemas } from '../../../charts/public';
import { MetricVisParam, VisParams } from '../types';
Expand Down Expand Up @@ -113,12 +114,10 @@ function MetricVisOptions({
</EuiTitle>
<EuiSpacer size="s" />

<SwitchOption
label={i18n.translate('visTypeMetric.params.percentageModeLabel', {
defaultMessage: 'Percentage mode',
})}
paramName="percentageMode"
value={stateParams.metric.percentageMode}
<PercentageModeOption
data-test-subj="metricPercentageMode"
percentageMode={stateParams.metric.percentageMode}
formatPattern={stateParams.metric.percentageFormatPattern}
setValue={setMetricValue}
/>

Expand Down
6 changes: 5 additions & 1 deletion src/plugins/vis_type_metric/public/to_ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export const toExpressionAst: VisToExpressionAst<VisParams> = (vis, params) => {

const {
percentageMode,
percentageFormatPattern,
useRanges,
colorSchema,
metricColorMode,
Expand All @@ -55,7 +56,10 @@ export const toExpressionAst: VisToExpressionAst<VisParams> = (vis, params) => {
// fix formatter for percentage mode
if (get(vis.params, 'metric.percentageMode') === true) {
schemas.metric.forEach((metric: SchemaConfig) => {
metric.format = { id: 'percent' };
metric.format = {
id: 'percent',
params: { pattern: percentageFormatPattern },
};
});
}

Expand Down
1 change: 1 addition & 0 deletions src/plugins/vis_type_metric/public/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface DimensionsVisParam {

export interface MetricVisParam {
percentageMode: boolean;
percentageFormatPattern?: string;
useRanges: boolean;
colorSchema: ColorSchemas;
metricColorMode: ColorMode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
SetColorRangeValue,
SwitchOption,
ColorSchemaOptions,
PercentageModeOption,
} from '../../../../../vis_default_editor/public';
import { ColorSchemaParams, ColorSchemas, colorSchemas } from '../../../../../charts/public';
import { GaugeOptionsInternalProps } from '../gauge';
Expand Down Expand Up @@ -77,13 +78,10 @@ function RangesPanel({
setValue={setGaugeValue}
/>

<SwitchOption
<PercentageModeOption
data-test-subj="gaugePercentageMode"
label={i18n.translate('visTypeVislib.controls.gaugeOptions.percentageModeLabel', {
defaultMessage: 'Percentage mode',
})}
paramName="percentageMode"
value={stateParams.gauge.percentageMode}
percentageMode={stateParams.gauge.percentageMode}
formatPattern={stateParams.gauge.percentageFormatPattern}
setValue={setGaugeValue}
/>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
SetColorSchemaOptionsValue,
ColorSchemaOptions,
NumberInputOption,
PercentageModeOption,
} from '../../../../../vis_default_editor/public';

import { HeatmapVisParams } from '../../../heatmap';
Expand Down Expand Up @@ -125,13 +126,10 @@ function HeatmapOptions(props: VisEditorOptionsProps<HeatmapVisParams>) {
setValue={setValueAxisScale}
/>

<SwitchOption
disabled={stateParams.setColorRange}
label={i18n.translate('visTypeVislib.controls.heatmapOptions.percentageModeLabel', {
defaultMessage: 'Percentage mode',
})}
paramName="percentageMode"
value={stateParams.setColorRange ? false : stateParams.percentageMode}
<PercentageModeOption
data-test-subj="metricPercentageMode"
percentageMode={stateParams.setColorRange ? false : stateParams.percentageMode}
formatPattern={stateParams.percentageFormatPattern}
setValue={setValue}
/>
<EuiSpacer size="s" />
Expand Down
3 changes: 3 additions & 0 deletions src/plugins/vis_type_vislib/public/fixtures/mocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ setFormatService({
deserialize: () => ({
convert: (v) => v,
}),
getInstance: () => ({
convert: (v) => v,
}),
});

export const getMockUiState = () => {
Expand Down
1 change: 1 addition & 0 deletions src/plugins/vis_type_vislib/public/gauge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export interface Gauge extends ColorSchemaParams {
gaugeType: GaugeType;
labels: Labels;
percentageMode: boolean;
percentageFormatPattern?: string;
outline?: boolean;
scale: {
show: boolean;
Expand Down
1 change: 1 addition & 0 deletions src/plugins/vis_type_vislib/public/heatmap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export interface HeatmapVisParams extends CommonVislibParams, ColorSchemaParams
valueAxes: ValueAxis[];
setColorRange: boolean;
percentageMode: boolean;
percentageFormatPattern?: string;
times: TimeMarker[];
}

Expand Down
5 changes: 4 additions & 1 deletion src/plugins/vis_type_vislib/public/to_ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ export const toExpressionAst = async <TVisParams extends VisParams>(
}
}
if (visConfig?.gauge?.percentageMode === true) {
yDimension.format = { id: 'percent' };
yDimension.format = {
id: 'percent',
params: { pattern: visConfig?.gauge?.percentageFormatPattern },
};
}
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,33 @@
* Side Public License, v 1.
*/

import { last } from 'lodash';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { UI_SETTINGS } from '../../../../../../plugins/data/public';
import { getValueForPercentageMode } from '../../percentage_mode_transform';

function getMax(handler, config, isGauge) {
let max;
if (handler.pointSeries) {
const series = handler.pointSeries.getSeries();
const scale = series.getValueAxis().getScale();
max = scale.domain()[1];
} else {
max = last(config.get(isGauge ? 'gauge.colorsRange' : 'colorsRange', [{}])).to;
}

return max;
}

export function pointSeriesTooltipFormatter() {
return function tooltipFormatter({ datum, data }) {
return function tooltipFormatter({ datum, data, config, handler }, uiSettings) {
if (!datum) return '';

const details = [];
const isGauge = config.get('gauge', false);
const isPercentageMode = config.get(isGauge ? 'gauge.percentageMode' : 'percentageMode', false);
const isSetColorRange = config.get('setColorRange', false);

const currentSeries =
data.series && data.series.find((serie) => serie.rawId === datum.seriesId);
Expand All @@ -30,8 +49,20 @@ export function pointSeriesTooltipFormatter() {
}

if (datum.y !== null && datum.y !== undefined) {
const value = datum.yScale ? datum.yScale * datum.y : datum.y;
addDetail(currentSeries.label, currentSeries.yAxisFormatter(value));
let value = datum.yScale ? datum.yScale * datum.y : datum.y;
if (isPercentageMode && !isSetColorRange) {
const percentageFormatPattern = config.get(
isGauge ? 'gauge.percentageFormatPattern' : 'percentageFormatPattern',
uiSettings.get(UI_SETTINGS.FORMAT_PERCENT_DEFAULT_PATTERN)
);
value = getValueForPercentageMode(
value / getMax(handler, config, isGauge),
percentageFormatPattern
);
addDetail(currentSeries.label, value);
} else {
addDetail(currentSeries.label, currentSeries.yAxisFormatter(value));
}
}

if (datum.z !== null && datum.z !== undefined) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,36 @@ describe('tooltipFormatter', function () {
extraMetrics: [],
seriesId: '1',
},
config: {
get: (name) => {
const config = {
setColorRange: false,
gauge: false,
percentageMode: false,
};
return config[name];
},
},
handler: {
pointSeries: {
getSeries: () => ({
getValueAxis: () => ({
getScale: () => ({
domain: () => [0, 10],
}),
}),
}),
},
},
};

const uiSettings = {
get: () => '',
};

it('returns html based on the mouse event', function () {
const event = _.cloneDeep(baseEvent);
const $el = $(tooltipFormatter(event));
const $el = $(tooltipFormatter(event, uiSettings));
const $rows = $el.find('tr');
expect($rows.length).toBe(3);

Expand All @@ -67,7 +92,7 @@ describe('tooltipFormatter', function () {
it('renders correctly on missing extraMetrics in datum', function () {
const event = _.cloneDeep(baseEvent);
delete event.datum.extraMetrics;
const $el = $(tooltipFormatter(event));
const $el = $(tooltipFormatter(event, uiSettings));
const $rows = $el.find('tr');
expect($rows.length).toBe(3);
});
Expand Down
Loading

0 comments on commit 0772e20

Please sign in to comment.