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] Improve Metric formatter to support bit format #153389

Merged
merged 5 commits into from
Mar 27, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,16 @@ jest.mock('@kbn/field-formats-plugin/common', () => ({
},
}));

jest.mock('@elastic/numeral', () => ({
language: jest.fn(() => 'en'),
languageData: jest.fn(() => ({
jest.mock('@elastic/numeral', () => {
const actualNumeral = jest.requireActual('@elastic/numeral');
actualNumeral.language = jest.fn(() => 'en');
actualNumeral.languageData = jest.fn(() => ({
currency: {
symbol: '$',
},
})),
}));
}));
return actualNumeral;
});

type Props = MetricVisComponentProps;

Expand Down Expand Up @@ -1381,12 +1383,12 @@ describe('MetricVisComponent', function () {
const base = 1024;

const { primary: bytesValue } = getFormattedMetrics(base - 1, 0, { id: 'bytes' });
expect(bytesValue).toBe('1,023 byte');
expect(bytesValue).toBe('1,023 B');

const { primary: kiloBytesValue } = getFormattedMetrics(Math.pow(base, 1), 0, {
id: 'bytes',
});
expect(kiloBytesValue).toBe('1 kB');
expect(kiloBytesValue).toBe('1 KB');

const { primary: megaBytesValue } = getFormattedMetrics(Math.pow(base, 2), 0, {
id: 'bytes',
Expand All @@ -1396,7 +1398,27 @@ describe('MetricVisComponent', function () {
const { primary: moreThanPetaValue } = getFormattedMetrics(Math.pow(base, 6), 0, {
id: 'bytes',
});
expect(moreThanPetaValue).toBe('1,024 PB');
expect(moreThanPetaValue).toBe('1 EB');
});

it('correctly formats bits (decimal)', () => {
const base = 1000;
const bitFormat = {
id: 'number',
params: { pattern: '0.0bitd' },
};

const { primary: bytesValue } = getFormattedMetrics(base - 1, 0, bitFormat);
expect(bytesValue).toBe('999 bit');

const { primary: kiloBytesValue } = getFormattedMetrics(Math.pow(base, 1), 0, bitFormat);
expect(kiloBytesValue).toBe('1 kbit');

const { primary: megaBytesValue } = getFormattedMetrics(Math.pow(base, 2), 0, bitFormat);
expect(megaBytesValue).toBe('1 Mbit');

const { primary: moreThanPetaValue } = getFormattedMetrics(Math.pow(base, 6), 0, bitFormat);
expect(moreThanPetaValue).toBe('1 Ebit');
});

it('correctly formats durations', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import type {
RenderMode,
} from '@kbn/expressions-plugin/common';
import { CustomPaletteState } from '@kbn/charts-plugin/public';
import { FORMATS_UI_SETTINGS } from '@kbn/field-formats-plugin/common';
import { FORMATS_UI_SETTINGS, type SerializedFieldFormat } from '@kbn/field-formats-plugin/common';
import type { FieldFormatConvertFunction } from '@kbn/field-formats-plugin/common';
import { CUSTOM_PALETTE } from '@kbn/coloring';
import { css } from '@emotion/react';
Expand All @@ -48,47 +48,28 @@ import { getCurrencyCode } from './currency_codes';
import { getDataBoundsForPalette } from '../utils';

export const defaultColor = euiThemeVars.euiColorLightestShade;
const getBytesUnit = (value: number) => {
const units = ['byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte', 'petabyte'];
const abs = Math.abs(value);

const base = 1024;
let unit = units[0];
let matched = abs < base;
let power;

if (!matched) {
for (power = 1; power < units.length; power++) {
const [min, max] = [Math.pow(base, power), Math.pow(base, power + 1)];
if (abs >= min && abs < max) {
unit = units[power];
matched = true;
value = value / min;
break;
}
}
}

if (!matched) {
value = value / Math.pow(base, units.length - 1);
unit = units[units.length - 1];
function getFormatId(serializedFieldFormat: SerializedFieldFormat | undefined): string | undefined {
if (serializedFieldFormat?.id === 'suffix') {
return `${serializedFieldFormat.params?.id || ''}`;
}

return { value, unit };
};
if (/bitd/.test(`${serializedFieldFormat?.params?.pattern || ''}`)) {
return 'bit';
}
return serializedFieldFormat?.id;
}

const getMetricFormatter = (
accessor: ExpressionValueVisDimension | string,
columns: Datatable['columns']
) => {
const serializedFieldFormat = getFormatByAccessor(accessor, columns);
const formatId =
(serializedFieldFormat?.id === 'suffix'
? serializedFieldFormat.params?.id
: serializedFieldFormat?.id) ?? 'number';
const formatId = getFormatId(serializedFieldFormat) || 'number';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I'd probably move the number default into getFormatId.


if (
!['number', 'currency', 'percent', 'bytes', 'duration', 'string', 'null'].includes(formatId)
!['number', 'currency', 'percent', 'bytes', 'bit', 'duration', 'string', 'null'].includes(
formatId
)
) {
throw new Error(
i18n.translate('expressionMetricVis.errors.unsupportedColumnFormat', {
Expand Down Expand Up @@ -150,10 +131,9 @@ const getMetricFormatter = (
intlOptions.style = 'percent';
}

return formatId === 'bytes'
return ['bit', 'bytes'].includes(formatId)
? (rawValue: number) => {
const { value, unit } = getBytesUnit(rawValue);
return new Intl.NumberFormat(locale, { ...intlOptions, style: 'unit', unit }).format(value);
return numeral(rawValue).format(`0,0[.]00 ${formatId === 'bytes' ? 'b' : 'bitd'}`);
}
: new Intl.NumberFormat(locale, intlOptions).format;
};
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/visualizations/common/utils/accessors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export function getFormatByAccessor(
dimension: string | ExpressionValueVisDimension,
columns: DatatableColumn[],
defaultColumnFormat?: SerializedFieldFormat
) {
): SerializedFieldFormat | undefined {
return typeof dimension === 'string'
? getColumnByAccessor(dimension, columns)?.meta.params || defaultColumnFormat
: dimension.format || defaultColumnFormat;
Expand Down