Skip to content

Commit

Permalink
[Lens] Improve Metric formatter to support bit format (#153389)
Browse files Browse the repository at this point in the history
## Summary

Fixes #152014 

This PR switches the formatter in the Metric visualization type from the
`Intl.NumberFormat` back to the `numeral.js` one which supports more
units for the `bytes` and `bit` format types.

While fixing the referenced issue, this PR also introduced some changes
in how the `bytes` number format is displayed to the user, mainly:

* below the `1024` threshold, the `B` format is used instead of the full
word `bytes` -- see the ⚠️ below
* The `k` for kilo is **not capitalized** when using `bytes` as
[documented for binary values for the entire Kibana
project](https://www.elastic.co/guide/en/kibana/current/numeral.html#_bytes_and_bits)
-- see the ⚠️ below
* The `K` for kilo is **capitalized** when using `bytes` as documented
[documented for binary values for the entire Kibana
project](https://www.elastic.co/guide/en/kibana/current/numeral.html#_bytes_and_bits)

Comparison table

| Raw value  | 8.6 | PR | Changes |
| ------------- | ------------- | ------------- | ------------- |
| 1023 bytes | <img width="320" alt="Screenshot 2023-03-21 at 16 29 09"
src="https://user-images.githubusercontent.com/924948/226687094-eac5b9a3-fc3f-4be5-b400-9e40ab15c92f.png">
| <img width="303" alt="Screenshot 2023-03-21 at 16 27 17"
src="https://user-images.githubusercontent.com/924948/226686883-77c7f79d-6346-4fc3-a401-c25761532598.png">
| ⚠️ |
| 1024 bytes | <img width="322" alt="Screenshot 2023-03-21 at 16 29 17"
src="https://user-images.githubusercontent.com/924948/226687220-38fa6d18-c3d2-4230-ac78-e15e1964d1e0.png">
| <img width="304" alt="Screenshot 2023-03-21 at 16 27 27"
src="https://user-images.githubusercontent.com/924948/226687269-ac250346-d6f7-415c-8d2a-19f057401e4d.png">
| ⚠️ |
| 1024 ^ 2 bytes | <img width="343" alt="Screenshot 2023-03-21 at 16 29
28"
src="https://user-images.githubusercontent.com/924948/226687439-da4fe335-d69e-4115-b728-bcee76f9ba1e.png">
| <img width="308" alt="Screenshot 2023-03-21 at 16 27 39"
src="https://user-images.githubusercontent.com/924948/226687509-29d81baa-25ab-445d-9375-c1c2414f3472.png">
| = |
| 1024 ^ 6 bytes | <img width="323" alt="Screenshot 2023-03-21 at 16 29
36"
src="https://user-images.githubusercontent.com/924948/226687645-8dc4c65f-5eeb-4049-ac94-afbf35bf6d3a.png">
| <img width="304" alt="Screenshot 2023-03-21 at 16 27 47"
src="https://user-images.githubusercontent.com/924948/226687673-2be028f6-ef54-45be-850a-b48d16d8b661.png">
| ✅ |
| 1024 ^ 9 bytes | <img width="324" alt="Screenshot 2023-03-21 at 16 29
45"
src="https://user-images.githubusercontent.com/924948/226687780-88cba5ed-baa6-4c94-9e5b-24efd8970ab5.png">
| <img width="307" alt="Screenshot 2023-03-21 at 16 28 08"
src="https://user-images.githubusercontent.com/924948/226687816-92ff4a72-bfcc-4a0c-92a8-48b0d7a68c5f.png">
| ✅ |
| 999 bits | <img width="327" alt="Screenshot 2023-03-21 at 17 55 12"
src="https://user-images.githubusercontent.com/924948/226687945-6b66ef65-a7e1-4bb1-92e3-038bfe2b40ba.png">
| <img width="308" alt="Screenshot 2023-03-21 at 16 27 00"
src="https://user-images.githubusercontent.com/924948/226688011-cebef661-f2e9-475c-840f-c808fc367965.png">
| ✅ |
| 1000 bits | <img width="333" alt="Screenshot 2023-03-21 at 17 55 04"
src="https://user-images.githubusercontent.com/924948/226688119-e783c243-9269-41ba-a695-a93e0f63afdf.png">
| <img width="302" alt="Screenshot 2023-03-21 at 16 26 52"
src="https://user-images.githubusercontent.com/924948/226688182-08a67dc4-c8e6-4416-83ab-3a4a13eb7904.png">
| ✅ |
| 1000 ^ 2 bits | <img width="329" alt="Screenshot 2023-03-21 at 17 54
54"
src="https://user-images.githubusercontent.com/924948/226688267-f310246d-61bb-4e88-9b14-42a9e49d5b5b.png">
| <img width="317" alt="Screenshot 2023-03-21 at 16 26 40"
src="https://user-images.githubusercontent.com/924948/226688312-fc51bec2-78a1-4f02-89dc-e8d3dcaa8971.png">
| ✅ |
| 1000 ^ 6 bits | <img width="322" alt="Screenshot 2023-03-21 at 16 30
06"
src="https://user-images.githubusercontent.com/924948/226688489-596ec3ee-1d64-407a-a9cc-6d559d312e87.png">
| <img width="295" alt="Screenshot 2023-03-21 at 16 26 25"
src="https://user-images.githubusercontent.com/924948/226688635-0290bc74-f66d-460f-ade8-dbc57b6f7263.png">
| ✅ |
| 1000 ^ 9 bits | <img width="329" alt="Screenshot 2023-03-21 at 16 29
59"
src="https://user-images.githubusercontent.com/924948/226688779-e127440d-bb1a-495e-b3e3-2c3572781517.png">
| <img width="301" alt="Screenshot 2023-03-21 at 16 28 25"
src="https://user-images.githubusercontent.com/924948/226688834-7716e433-6290-4719-b3ec-fef0bd776958.png">
| ✅ |



### 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)
  • Loading branch information
dej611 authored Mar 27, 2023
1 parent 676aec7 commit bac8aac
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 44 deletions.
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';

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

0 comments on commit bac8aac

Please sign in to comment.