[Lens] Introduce new duration formatter (#162246)

## Summary

Fixes #153378 

This PR introduces a new Duration formatter, similar to the TSVB one and
more complete like the Field Formatter one.

Few keys features of the new formatter:
* supports from and to unit selection
* supports Humanize (approximate) and Humanize (precise) outputs
* supports units below milliseconds
* supports decimals precision (with the exception of the `humanize
approximate` output)
* supports suffix
* supports the compact version (with the exception of the `humanize
approximate` output)

Input and Output options are now exported directly from the Field
Formatter to have a shared list of options.

A first look at the new formatter in action: when enabled it the first
time it will lands on `Seconds => Humanize (Approximate)` configuration
(this emulates the current Field Formatter behaviour)

<img width="1217" alt="Screenshot 2023-07-19 at 15 28 52"
src="8ddcb945-3cd7-4af1-bdfb-2ae1795ab06c">

In this example the input was in Minutes so it is possible to change it
from the default `Seconds` entry:

<img width="1223" alt="Screenshot 2023-07-19 at 14 17 11"
src="b547b3ed-475e-421c-b196-a76b07235bd3">

Switching output type to something else than `Humanize (approximate)`
will make available both decimals and compact controls as well.
Custom suffix is supported as well.

<img width="1220" alt="Screenshot 2023-07-19 at 14 18 34"
src="f5efe1f7-5f0d-4de1-bb3e-80ff00857bc6">
<img width="1228" alt="Screenshot 2023-07-19 at 14 18 19"
src="fef7fa2d-ecd3-48ae-a833-16dbeaeaade2">

When Decimals and Compact controls are disabled a helpful tooltip is
shown to the user to explain why:

<img width="341" alt="Screenshot 2023-07-19 at 14 17 30"
src="78ca1df5-808d-4e2d-8598-90e3f3ec5a85">
<img width="337" alt="Screenshot 2023-07-19 at 14 17 23"
src="4ca0028d-3344-464c-8b36-1f74f53bd34e">
 
I've also prepared an alternate UI version which is more compact, using
the `DelimitedControls` UI, but it does not looks that great. Maybe some
design iteration could help make it better? cc @MichaelMarcialis

<img width="1226" alt="Screenshot 2023-07-19 at 14 20 02"
src="fb8f69f2-5182-480d-9cb2-7a7149a54320">

### 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: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
Co-authored-by: Stratoula Kalafateli <efstratia.kalafateli@elastic.co>
This commit is contained in:
Marco Liberati 2023-07-24 09:55:55 +02:00 committed by GitHub
parent 0af4e7e113
commit ad493e1a25
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 648 additions and 223 deletions

View file

@ -1417,6 +1417,18 @@ describe('MetricVisComponent', function () {
});
});
it('does not override duration configuration at visualization level when set', () => {
getFormattedMetrics(394.2393, 983123.984, {
id: 'duration',
params: { formatOverride: true, outputFormat: 'asSeconds' },
});
expect(mockDeserialize).toHaveBeenCalledTimes(2);
expect(mockDeserialize).toHaveBeenCalledWith({
id: 'duration',
params: { formatOverride: true, outputFormat: 'asSeconds' },
});
});
it('does not tweak bytes format when passed', () => {
getFormattedMetrics(394.2393, 983123.984, {
id: 'bytes',

View file

@ -49,7 +49,7 @@ export const defaultColor = euiThemeVars.euiColorLightestShade;
function enhanceFieldFormat(serializedFieldFormat: SerializedFieldFormat | undefined) {
const formatId = serializedFieldFormat?.id || 'number';
if (formatId === 'duration') {
if (formatId === 'duration' && !serializedFieldFormat?.params?.formatOverride) {
return {
...serializedFieldFormat,
params: {

View file

@ -0,0 +1,171 @@
/*
* 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';
const DEFAULT_INPUT_FORMAT = {
text: i18n.translate('fieldFormats.duration.inputFormats.seconds', {
defaultMessage: 'Seconds',
}),
kind: 'seconds',
};
const inputFormats = [
{
text: i18n.translate('fieldFormats.duration.inputFormats.picoseconds', {
defaultMessage: 'Picoseconds',
}),
kind: 'picoseconds',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.nanoseconds', {
defaultMessage: 'Nanoseconds',
}),
kind: 'nanoseconds',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.microseconds', {
defaultMessage: 'Microseconds',
}),
kind: 'microseconds',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.milliseconds', {
defaultMessage: 'Milliseconds',
}),
kind: 'milliseconds',
},
{ ...DEFAULT_INPUT_FORMAT },
{
text: i18n.translate('fieldFormats.duration.inputFormats.minutes', {
defaultMessage: 'Minutes',
}),
kind: 'minutes',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.hours', {
defaultMessage: 'Hours',
}),
kind: 'hours',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.days', {
defaultMessage: 'Days',
}),
kind: 'days',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.weeks', {
defaultMessage: 'Weeks',
}),
kind: 'weeks',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.months', {
defaultMessage: 'Months',
}),
kind: 'months',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.years', {
defaultMessage: 'Years',
}),
kind: 'years',
},
];
const DEFAULT_OUTPUT_FORMAT = {
text: i18n.translate('fieldFormats.duration.outputFormats.humanize.approximate', {
defaultMessage: 'Human-readable (approximate)',
}),
method: 'humanize',
};
const outputFormats = [
{ ...DEFAULT_OUTPUT_FORMAT },
{
text: i18n.translate('fieldFormats.duration.outputFormats.humanize.precise', {
defaultMessage: 'Human-readable (precise)',
}),
method: 'humanizePrecise',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asMilliseconds', {
defaultMessage: 'Milliseconds',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asMilliseconds.short', {
defaultMessage: 'ms',
}),
method: 'asMilliseconds',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asSeconds', {
defaultMessage: 'Seconds',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asSeconds.short', {
defaultMessage: 's',
}),
method: 'asSeconds',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asMinutes', {
defaultMessage: 'Minutes',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asMinutes.short', {
defaultMessage: 'min',
}),
method: 'asMinutes',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asHours', {
defaultMessage: 'Hours',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asHours.short', {
defaultMessage: 'h',
}),
method: 'asHours',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asDays', {
defaultMessage: 'Days',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asDays.short', {
defaultMessage: 'd',
}),
method: 'asDays',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asWeeks', {
defaultMessage: 'Weeks',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asWeeks.short', {
defaultMessage: 'w',
}),
method: 'asWeeks',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asMonths', {
defaultMessage: 'Months',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asMonths.short', {
defaultMessage: 'mon',
}),
method: 'asMonths',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asYears', {
defaultMessage: 'Years',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asYears.short', {
defaultMessage: 'y',
}),
method: 'asYears',
},
];
export const DEFAULT_DURATION_INPUT_FORMAT = DEFAULT_INPUT_FORMAT;
export const DEFAULT_DURATION_OUTPUT_FORMAT = DEFAULT_OUTPUT_FORMAT;
export const DURATION_INPUT_FORMATS = inputFormats;
export const DURATION_OUTPUT_FORMATS = outputFormats;

View file

@ -11,171 +11,22 @@ import moment, { unitOfTime, Duration } from 'moment';
import { KBN_FIELD_TYPES } from '@kbn/field-types';
import { FieldFormat } from '../field_format';
import { TextContextTypeConvert, FIELD_FORMAT_IDS } from '../types';
import {
DEFAULT_DURATION_INPUT_FORMAT,
DEFAULT_DURATION_OUTPUT_FORMAT,
DURATION_INPUT_FORMATS,
DURATION_OUTPUT_FORMATS,
} from '../constants/duration_formats';
const ratioToSeconds: Record<string, number> = {
picoseconds: 0.000000000001,
nanoseconds: 0.000000001,
microseconds: 0.000001,
};
const HUMAN_FRIENDLY = 'humanize';
const HUMAN_FRIENDLY_PRECISE = 'humanizePrecise';
const DEFAULT_OUTPUT_PRECISION = 2;
const DEFAULT_INPUT_FORMAT = {
text: i18n.translate('fieldFormats.duration.inputFormats.seconds', {
defaultMessage: 'Seconds',
}),
kind: 'seconds',
};
const inputFormats = [
{
text: i18n.translate('fieldFormats.duration.inputFormats.picoseconds', {
defaultMessage: 'Picoseconds',
}),
kind: 'picoseconds',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.nanoseconds', {
defaultMessage: 'Nanoseconds',
}),
kind: 'nanoseconds',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.microseconds', {
defaultMessage: 'Microseconds',
}),
kind: 'microseconds',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.milliseconds', {
defaultMessage: 'Milliseconds',
}),
kind: 'milliseconds',
},
{ ...DEFAULT_INPUT_FORMAT },
{
text: i18n.translate('fieldFormats.duration.inputFormats.minutes', {
defaultMessage: 'Minutes',
}),
kind: 'minutes',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.hours', {
defaultMessage: 'Hours',
}),
kind: 'hours',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.days', {
defaultMessage: 'Days',
}),
kind: 'days',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.weeks', {
defaultMessage: 'Weeks',
}),
kind: 'weeks',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.months', {
defaultMessage: 'Months',
}),
kind: 'months',
},
{
text: i18n.translate('fieldFormats.duration.inputFormats.years', {
defaultMessage: 'Years',
}),
kind: 'years',
},
];
const DEFAULT_OUTPUT_FORMAT = {
text: i18n.translate('fieldFormats.duration.outputFormats.humanize.approximate', {
defaultMessage: 'Human-readable (approximate)',
}),
method: 'humanize',
};
const outputFormats = [
{ ...DEFAULT_OUTPUT_FORMAT },
{
text: i18n.translate('fieldFormats.duration.outputFormats.humanize.precise', {
defaultMessage: 'Human-readable (precise)',
}),
method: 'humanizePrecise',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asMilliseconds', {
defaultMessage: 'Milliseconds',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asMilliseconds.short', {
defaultMessage: 'ms',
}),
method: 'asMilliseconds',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asSeconds', {
defaultMessage: 'Seconds',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asSeconds.short', {
defaultMessage: 's',
}),
method: 'asSeconds',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asMinutes', {
defaultMessage: 'Minutes',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asMinutes.short', {
defaultMessage: 'min',
}),
method: 'asMinutes',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asHours', {
defaultMessage: 'Hours',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asHours.short', {
defaultMessage: 'h',
}),
method: 'asHours',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asDays', {
defaultMessage: 'Days',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asDays.short', {
defaultMessage: 'd',
}),
method: 'asDays',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asWeeks', {
defaultMessage: 'Weeks',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asWeeks.short', {
defaultMessage: 'w',
}),
method: 'asWeeks',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asMonths', {
defaultMessage: 'Months',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asMonths.short', {
defaultMessage: 'mon',
}),
method: 'asMonths',
},
{
text: i18n.translate('fieldFormats.duration.outputFormats.asYears', {
defaultMessage: 'Years',
}),
shortText: i18n.translate('fieldFormats.duration.outputFormats.asYears.short', {
defaultMessage: 'y',
}),
method: 'asYears',
},
];
function parseInputAsDuration(val: number, inputFormat: string) {
const ratio = ratioToSeconds[inputFormat] || 1;
@ -214,8 +65,8 @@ export class DurationFormat extends FieldFormat {
defaultMessage: 'Duration',
});
static fieldType = KBN_FIELD_TYPES.NUMBER;
static inputFormats = inputFormats;
static outputFormats = outputFormats;
static inputFormats = DURATION_INPUT_FORMATS;
static outputFormats = DURATION_OUTPUT_FORMATS;
allowsNumericalAggregations = true;
isHuman() {
@ -228,8 +79,8 @@ export class DurationFormat extends FieldFormat {
getParamDefaults() {
return {
inputFormat: DEFAULT_INPUT_FORMAT.kind,
outputFormat: DEFAULT_OUTPUT_FORMAT.method,
inputFormat: DEFAULT_DURATION_INPUT_FORMAT.kind,
outputFormat: DEFAULT_DURATION_OUTPUT_FORMAT.method,
outputPrecision: DEFAULT_OUTPUT_PRECISION,
includeSpaceWithSuffix: true,
};
@ -261,7 +112,7 @@ export class DurationFormat extends FieldFormat {
: duration[outputFormat]();
const precise = human || humanPrecise ? formatted : formatted.toFixed(outputPrecision);
const type = outputFormats.find(({ method }) => method === outputFormat);
const type = DURATION_OUTPUT_FORMATS.find(({ method }) => method === outputFormat);
const unitText = useShortSuffix ? type?.shortText : type?.text.toLowerCase();
@ -293,7 +144,7 @@ function formatDuration(
];
const getUnitText = (method: string) => {
const type = outputFormats.find(({ method: methodT }) => method === methodT);
const type = DURATION_OUTPUT_FORMATS.find(({ method: methodT }) => method === methodT);
return useShortSuffix ? type?.shortText : type?.text.toLowerCase();
};

View file

@ -37,6 +37,12 @@ export { getHighlightRequest, geoUtils } from './utils';
export { DEFAULT_CONVERTER_COLOR } from './constants/color_default';
export { FORMATS_UI_SETTINGS } from './constants/ui_settings';
export {
DEFAULT_DURATION_INPUT_FORMAT,
DEFAULT_DURATION_OUTPUT_FORMAT,
DURATION_INPUT_FORMATS,
DURATION_OUTPUT_FORMATS,
} from './constants/duration_formats';
export { FIELD_FORMAT_IDS } from './types';
export { HTML_CONTEXT_TYPE, TEXT_CONTEXT_TYPE } from './content_types';

View file

@ -326,4 +326,65 @@ describe('format_column', () => {
},
});
});
it('does translate the duration params into native parameters', async () => {
const result = await fn(datatable, {
columnId: 'test',
format: 'duration',
fromUnit: 'seconds',
toUnit: 'asHours',
compact: true,
decimals: 2,
});
expect(result.columns[0].meta).toEqual({
type: 'number',
params: {
id: 'duration',
params: {
pattern: '',
formatOverride: true,
inputFormat: 'seconds',
outputFormat: 'asHours',
outputPrecision: 2,
useShortSuffix: true,
showSuffix: true,
includeSpaceWithSuffix: true,
},
},
});
});
it('should apply custom suffix to duration format when configured', async () => {
const result = await fn(datatable, {
columnId: 'test',
format: 'duration',
fromUnit: 'seconds',
toUnit: 'asHours',
compact: true,
decimals: 2,
suffix: ' on Earth',
});
expect(result.columns[0].meta).toEqual({
type: 'number',
params: {
id: 'suffix',
params: {
suffixString: ' on Earth',
id: 'duration',
formatOverride: true,
params: {
pattern: '',
formatOverride: true,
inputFormat: 'seconds',
outputFormat: 'asHours',
outputPrecision: 2,
useShortSuffix: true,
showSuffix: true,
includeSpaceWithSuffix: true,
},
},
},
});
});
});

View file

@ -42,7 +42,16 @@ function getPatternFromFormat(
export const formatColumnFn: FormatColumnExpressionFunction['fn'] = (
input,
{ format, columnId, decimals, compact, suffix, pattern, parentFormat }: FormatColumnArgs
{
format,
columnId,
decimals,
compact,
suffix,
pattern,
parentFormat,
...otherArgs
}: FormatColumnArgs
) => ({
...input,
columns: input.columns
@ -56,6 +65,12 @@ export const formatColumnFn: FormatColumnExpressionFunction['fn'] = (
params: {
pattern: getPatternFromFormat(format, decimals, compact, pattern),
formatOverride: true,
...supportedFormats[format].translateToFormatParams?.({
decimals,
compact,
suffix,
...otherArgs,
}),
},
};
return withParams(col, serializedFormat as Record<string, unknown>);
@ -80,6 +95,12 @@ export const formatColumnFn: FormatColumnExpressionFunction['fn'] = (
const customParams = {
pattern: getPatternFromFormat(format, decimals, compact, pattern),
formatOverride: true,
...supportedFormats[format].translateToFormatParams?.({
decimals,
compact,
suffix,
...otherArgs,
}),
};
// 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

View file

@ -15,6 +15,8 @@ export interface FormatColumnArgs {
compact?: boolean;
pattern?: string;
parentFormat?: string;
fromUnit?: string;
toUnit?: string;
}
export const formatColumn: FormatColumnExpressionFunction = {
@ -52,6 +54,14 @@ export const formatColumn: FormatColumnExpressionFunction = {
types: ['string'],
help: '',
},
fromUnit: {
types: ['string'],
help: '',
},
toUnit: {
types: ['string'],
help: '',
},
},
inputTypes: ['datatable'],
async fn(...args) {

View file

@ -5,9 +5,21 @@
* 2.0.
*/
import {
DEFAULT_DURATION_INPUT_FORMAT,
DEFAULT_DURATION_OUTPUT_FORMAT,
} from '@kbn/field-formats-plugin/common';
import type { FormatColumnArgs } from '.';
export const supportedFormats: Record<
string,
{ decimalsToPattern: (decimals?: number, compact?: boolean) => string; formatId: string }
{
formatId: string;
decimalsToPattern: (decimals?: number, compact?: boolean) => string;
translateToFormatParams?: (
params: Omit<FormatColumnArgs, 'format' | 'columnId' | 'parentFormat'>
) => Record<string, unknown>;
}
> = {
number: {
formatId: 'number',
@ -45,6 +57,20 @@ export const supportedFormats: Record<
return `0,0.${'0'.repeat(decimals)}bitd`;
},
},
duration: {
formatId: 'duration',
decimalsToPattern: () => '',
translateToFormatParams: (params) => {
return {
inputFormat: params.fromUnit || DEFAULT_DURATION_INPUT_FORMAT.kind,
outputFormat: params.toUnit || DEFAULT_DURATION_OUTPUT_FORMAT.method,
outputPrecision: params.decimals,
useShortSuffix: Boolean(params.compact),
showSuffix: true,
includeSpaceWithSuffix: true,
};
},
},
custom: {
formatId: 'custom',
decimalsToPattern: () => '',

View file

@ -14,7 +14,7 @@ import { LensAppServices } from '../../../app_plugin/types';
import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public';
import { I18nProvider } from '@kbn/i18n-react';
import { coreMock } from '@kbn/core/public/mocks';
import { EuiFieldNumber } from '@elastic/eui';
import { EuiComboBox, EuiFieldNumber } from '@elastic/eui';
jest.mock('lodash', () => {
const original = jest.requireActual('lodash');
@ -106,10 +106,10 @@ describe('FormatSelector', () => {
});
expect(props.onChange).toBeCalledWith({ id: 'bytes', params: { decimals: 0 } });
});
it('updates the suffix', async () => {
it('updates the suffix', () => {
const props = getDefaultProps();
const component = mountWithServices(<FormatSelector {...props} />);
await act(async () => {
act(() => {
component
.find('[data-test-subj="indexPattern-dimension-formatSuffix"]')
.last()
@ -120,4 +120,55 @@ describe('FormatSelector', () => {
component.update();
expect(props.onChange).toBeCalledWith({ id: 'bytes', params: { suffix: 'GB' } });
});
describe('Duration', () => {
it('disables the decimals and compact controls for humanize approximate output', () => {
const originalProps = getDefaultProps();
let component = mountWithServices(
<FormatSelector
{...{
...originalProps,
selectedColumn: {
...originalProps.selectedColumn,
params: { format: { id: 'duration' } },
},
}}
/>
);
expect(
component
.find('[data-test-subj="indexPattern-dimension-formatDecimals"]')
.last()
.prop('disabled')
).toBe(true);
expect(
component
.find('[data-test-subj="lns-indexpattern-dimension-formatCompact"]')
.first()
.prop('disabled')
).toBe(true);
act(() => {
component
.find('[data-test-subj="indexPattern-dimension-duration-end"]')
.find(EuiComboBox)
.prop('onChange')!([{ label: 'Hours', value: 'asHours' }]);
});
component = component.update();
expect(
component
.find('[data-test-subj="indexPattern-dimension-formatDecimals"]')
.last()
.prop('disabled')
).toBe(false);
expect(
component
.find('[data-test-subj="lns-indexpattern-dimension-formatCompact"]')
.first()
.prop('disabled')
).toBe(false);
});
});
});

View file

@ -16,35 +16,52 @@ import {
EuiSwitch,
EuiCode,
} from '@elastic/eui';
import { useDebouncedValue } from '@kbn/visualization-ui-components';
import { useDebouncedValue, TooltipWrapper } from '@kbn/visualization-ui-components';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { FORMATS_UI_SETTINGS } from '@kbn/field-formats-plugin/common';
import {
DEFAULT_DURATION_INPUT_FORMAT,
DEFAULT_DURATION_OUTPUT_FORMAT,
FORMATS_UI_SETTINGS,
} from '@kbn/field-formats-plugin/common';
import { FormattedMessage } from '@kbn/i18n-react';
import { LensAppServices } from '../../../app_plugin/types';
import { GenericIndexPatternColumn } from '../form_based';
import { isColumnFormatted } from '../operations/definitions/helpers';
import { ValueFormatConfig } from '../operations/definitions/column_types';
import { DurationRowInputs } from './formatting/duration_input';
const supportedFormats: Record<
string,
{ title: string; defaultDecimals?: number; supportsCompact: boolean }
{
title: string;
defaultDecimals?: number;
supportsCompact: boolean;
supportsDecimals: boolean;
supportsSuffix: boolean;
}
> = {
number: {
title: i18n.translate('xpack.lens.indexPattern.numberFormatLabel', {
defaultMessage: 'Number',
}),
supportsDecimals: true,
supportsSuffix: true,
supportsCompact: true,
},
percent: {
title: i18n.translate('xpack.lens.indexPattern.percentFormatLabel', {
defaultMessage: 'Percent',
}),
supportsDecimals: true,
supportsSuffix: true,
supportsCompact: true,
},
bytes: {
title: i18n.translate('xpack.lens.indexPattern.bytesFormatLabel', {
defaultMessage: 'Bytes (1024)',
}),
supportsDecimals: true,
supportsSuffix: true,
supportsCompact: false,
},
bits: {
@ -52,13 +69,26 @@ const supportedFormats: Record<
defaultMessage: 'Bits (1000)',
}),
defaultDecimals: 0,
supportsDecimals: true,
supportsSuffix: true,
supportsCompact: false,
},
duration: {
title: i18n.translate('xpack.lens.indexPattern.durationLabel', {
defaultMessage: 'Duration',
}),
defaultDecimals: 0,
supportsDecimals: true,
supportsSuffix: true,
supportsCompact: true,
},
custom: {
title: i18n.translate('xpack.lens.indexPattern.customFormatLabel', {
defaultMessage: 'Custom format',
}),
defaultDecimals: 0,
supportsDecimals: false,
supportsSuffix: false,
supportsCompact: false,
},
};
@ -164,6 +194,20 @@ export function FormatSelector(props: FormatSelectorProps) {
onChange
);
const { setter: setDurationFrom, value: durationFrom } = useDebouncedInputforParam(
'fromUnit' as const,
DEFAULT_DURATION_INPUT_FORMAT.kind,
currentFormat,
onChange
);
const { setter: setDurationTo, value: durationTo } = useDebouncedInputforParam(
'toUnit' as const,
DEFAULT_DURATION_OUTPUT_FORMAT.method,
currentFormat,
onChange
);
const selectedFormat = currentFormat?.id ? supportedFormats[currentFormat.id] : undefined;
const stableOptions = useMemo(
() => [
@ -210,6 +254,8 @@ export function FormatSelector(props: FormatSelectorProps) {
[currentFormat, selectedFormat?.title]
);
const approximatedFormat = currentFormat?.id === 'duration' && durationTo === 'humanize';
return (
<>
<EuiFormRow
@ -240,57 +286,102 @@ export function FormatSelector(props: FormatSelectorProps) {
selectedOptions={currentOption}
onChange={onChangeWrapped}
/>
{currentFormat && currentFormat.id !== 'custom' ? (
{currentFormat && selectedFormat ? (
<>
<EuiSpacer size="s" />
<EuiRange
showInput="inputWithPopover"
value={decimals}
min={RANGE_MIN}
max={RANGE_MAX}
onChange={(e) => {
const value = Number(e.currentTarget.value);
setDecimals(value);
const validatedValue = Math.min(RANGE_MAX, Math.max(RANGE_MIN, value));
onChange({
id: currentFormat.id,
params: {
...currentFormat.params,
decimals: validatedValue,
},
});
}}
data-test-subj="indexPattern-dimension-formatDecimals"
compressed
fullWidth
prepend={decimalsLabel}
aria-label={decimalsLabel}
/>
<EuiSpacer size="s" />
<EuiFieldText
value={suffix}
onChange={(e) => {
setSuffix(e.currentTarget.value);
}}
data-test-subj="indexPattern-dimension-formatSuffix"
compressed
fullWidth
prepend={suffixLabel}
aria-label={suffixLabel}
/>
</>
) : null}
{selectedFormat?.supportsCompact ? (
<>
<EuiSpacer size="s" />
<EuiSwitch
compressed
label={compactLabel}
checked={Boolean(compact)}
onChange={() => setCompact(!compact)}
data-test-subj="lns-indexpattern-dimension-formatCompact"
/>
{currentFormat?.id === 'duration' ? (
<>
<EuiSpacer size="s" />
<DurationRowInputs
onStartChange={setDurationFrom}
onEndChange={setDurationTo}
startValue={durationFrom}
endValue={durationTo}
testSubjEnd="indexPattern-dimension-duration-end"
testSubjStart="indexPattern-dimension-duration-start"
/>
</>
) : null}
{selectedFormat.supportsDecimals ? (
<>
<EuiSpacer size="s" />
<TooltipWrapper
tooltipContent={i18n.translate(
'xpack.lens.indexPattern.format.decimalsDisabled',
{
defaultMessage: 'Use a precise duration output format to use decimals.',
}
)}
condition={approximatedFormat}
display="block"
>
<EuiRange
showInput="inputWithPopover"
value={decimals}
min={RANGE_MIN}
max={RANGE_MAX}
onChange={(e) => {
const value = Number(e.currentTarget.value);
setDecimals(value);
const validatedValue = Math.min(RANGE_MAX, Math.max(RANGE_MIN, value));
onChange({
id: currentFormat.id,
params: {
...currentFormat.params,
decimals: validatedValue,
},
});
}}
data-test-subj="indexPattern-dimension-formatDecimals"
compressed
fullWidth
prepend={decimalsLabel}
aria-label={decimalsLabel}
disabled={approximatedFormat}
/>
</TooltipWrapper>
</>
) : null}
{selectedFormat.supportsSuffix ? (
<>
<EuiSpacer size="s" />
<EuiFieldText
value={suffix}
onChange={(e) => {
setSuffix(e.currentTarget.value);
}}
data-test-subj="indexPattern-dimension-formatSuffix"
compressed
fullWidth
prepend={suffixLabel}
aria-label={suffixLabel}
/>
</>
) : null}
{selectedFormat.supportsCompact ? (
<>
<EuiSpacer size="s" />
<TooltipWrapper
tooltipContent={i18n.translate(
'xpack.lens.indexPattern.format.compactDisabled',
{
defaultMessage:
'Use a precise duration output format to use a compact format.',
}
)}
condition={approximatedFormat}
display="block"
>
<EuiSwitch
compressed
label={compactLabel}
checked={Boolean(compact)}
onChange={() => setCompact(!compact)}
data-test-subj="lns-indexpattern-dimension-formatCompact"
disabled={approximatedFormat}
/>
</TooltipWrapper>
</>
) : null}
</>
) : null}
</div>

View file

@ -0,0 +1,78 @@
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { EuiComboBox, EuiSpacer } from '@elastic/eui';
import { DURATION_INPUT_FORMATS, DURATION_OUTPUT_FORMATS } from '@kbn/field-formats-plugin/common';
import { i18n } from '@kbn/i18n';
import React from 'react';
export const durationOutputOptions = DURATION_OUTPUT_FORMATS.map(({ text, method }) => ({
label: text,
value: method,
}));
export const durationInputOptions = DURATION_INPUT_FORMATS.map(({ text, kind }) => ({
label: text,
value: kind,
}));
interface DurationInputProps {
testSubjLayout?: string;
testSubjStart?: string;
testSubjEnd?: string;
onStartChange: (newStartValue: string) => void;
onEndChange: (newEndValue: string) => void;
startValue: string | undefined;
endValue: string | undefined;
}
function getSelectedOption(
inputValue: string,
list: Array<{ label: string; value: string }>
): Array<{ label: string; value: string }> {
const option = list.find(({ value }) => inputValue === value);
return option ? [option] : [];
}
export const DurationRowInputs = ({
testSubjLayout,
testSubjStart,
testSubjEnd,
startValue = 'milliseconds',
endValue = 'seconds',
onStartChange,
onEndChange,
}: DurationInputProps) => {
return (
<>
<EuiComboBox
prepend={i18n.translate('xpack.lens.indexPattern.duration.fromLabel', {
defaultMessage: 'From',
})}
isClearable={false}
options={durationInputOptions}
selectedOptions={getSelectedOption(startValue, durationInputOptions)}
onChange={([newStartValue]) => onStartChange(newStartValue.value!)}
singleSelection={{ asPlainText: true }}
data-test-subj={testSubjStart}
compressed
/>
<EuiSpacer size="s" />
<EuiComboBox
prepend={i18n.translate('xpack.lens.indexPattern.custom.toLabel', {
defaultMessage: 'To',
})}
isClearable={false}
options={durationOutputOptions}
selectedOptions={getSelectedOption(endValue, durationOutputOptions)}
onChange={([newEndChange]) => onEndChange(newEndChange.value!)}
singleSelection={{ asPlainText: true }}
data-test-subj={testSubjEnd}
compressed
/>
</>
);
};

View file

@ -27,6 +27,8 @@ export interface ValueFormatConfig {
suffix?: string;
compact?: boolean;
pattern?: string;
fromUnit?: string;
toUnit?: string;
};
}

View file

@ -27,7 +27,7 @@ import { GenericIndexPatternColumn } from './form_based';
import { operationDefinitionMap } from './operations';
import { FormBasedPrivateState, FormBasedLayer } from './types';
import { DateHistogramIndexPatternColumn, RangeIndexPatternColumn } from './operations/definitions';
import { FormattedIndexPatternColumn } from './operations/definitions/column_types';
import type { FormattedIndexPatternColumn } from './operations/definitions/column_types';
import { isColumnFormatted, isColumnOfType } from './operations/definitions/helpers';
import type { IndexPattern, IndexPatternMap } from '../../types';
import { dedupeAggs } from './dedupe_aggs';
@ -352,6 +352,14 @@ function getExpressionForLayer(
format?.params && 'pattern' in format.params && format.params.pattern
? [format.params.pattern]
: [],
fromUnit:
format?.params && 'fromUnit' in format.params && format.params.fromUnit
? [format.params.fromUnit]
: [],
toUnit:
format?.params && 'toUnit' in format.params && format.params.toUnit
? [format.params.toUnit]
: [],
parentFormat: parentFormat ? [JSON.stringify(parentFormat)] : [],
},
};

View file

@ -36,7 +36,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
await fieldEditor.confirmDelete();
await PageObjects.lens.waitForFieldMissing('runtimefield');
});
it('should display url formatter correctly', async () => {
await retry.try(async () => {
await PageObjects.lens.clickAddField();
@ -196,5 +195,43 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
expect(await PageObjects.lens.getDatatableCellText(0, 0)).to.eql('572,732.21%');
});
});
describe('formatter order', () => {
before(async () => {
await PageObjects.visualize.navigateToNewVisualization();
await PageObjects.visualize.clickVisType('lens');
await PageObjects.lens.goToTimeRange();
await PageObjects.lens.switchToVisualization('lnsDatatable');
});
after(async () => {
await PageObjects.lens.clickField('runtimefield');
await PageObjects.lens.removeField('runtimefield');
await fieldEditor.confirmDelete();
await PageObjects.lens.waitForFieldMissing('runtimefield');
});
it('should be overridden by Lens formatter', async () => {
await retry.try(async () => {
await PageObjects.lens.clickAddField();
await fieldEditor.setName('runtimefield');
await fieldEditor.setFieldType('long');
await fieldEditor.enableValue();
await fieldEditor.typeScript("emit(doc['bytes'].value)");
await fieldEditor.setFormat(FIELD_FORMAT_IDS.BYTES);
await fieldEditor.save();
await fieldEditor.waitUntilClosed();
await PageObjects.header.waitUntilLoadingHasFinished();
});
await PageObjects.lens.configureDimension({
dimension: 'lnsDatatable_metrics > lns-empty-dimension',
operation: 'average',
field: 'runtimefield',
keepOpen: true,
});
await PageObjects.lens.editDimensionFormat('Bits (1000)', { decimals: 3, prefix: 'blah' });
await PageObjects.lens.closeDimensionEditor();
await PageObjects.lens.waitForVisualization();
expect(await PageObjects.lens.getDatatableCellText(0, 0)).to.eql('5.727kbitblah');
});
});
});
}