[Lens] Visualization UI package refactoring (#156185)

## Summary

Fix #156181

This PR attempts to reduce the bundle size of the visualization UI
package by moving out all color manipulation functions into the
`@kbn/coloring` package, including the `chroma-js` dependency.
After a bundle size analysis the `chroma-js` package was found to be the
most offending in terms of size as its pre-2.0 version was not
treeshakable: other dependencies like EUI and Elastic Charts were
already using version `^2.1.0` therefore an upgrade was triggered at
kibana level.

Removed more kb from the package and Lens via replacing the `color`
dependency with the new `chroma-js` package.

### 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—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—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>
This commit is contained in:
Marco Liberati 2023-05-04 14:12:10 +02:00 committed by GitHub
parent 6a85012951
commit 5207e52895
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 67 additions and 93 deletions

View file

@ -761,7 +761,7 @@
"cbor-x": "^1.3.3",
"chalk": "^4.1.0",
"cheerio": "^1.0.0-rc.10",
"chroma-js": "^1.4.1",
"chroma-js": "^2.1.0",
"classnames": "2.2.6",
"color": "^4.2.3",
"commander": "^4.1.1",
@ -1179,7 +1179,7 @@
"@types/base64-js": "^1.2.5",
"@types/byte-size": "^8.1.0",
"@types/chance": "^1.0.0",
"@types/chroma-js": "^1.4.2",
"@types/chroma-js": "^2.1.0",
"@types/chromedriver": "^81.0.1",
"@types/classnames": "^2.2.9",
"@types/color": "^3.0.3",

View file

@ -8,3 +8,4 @@
export * from './src/palettes';
export * from './src/shared_components';
export * from './src/color_manipulation';

View file

@ -0,0 +1,30 @@
/*
* 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 chroma from 'chroma-js';
import { isColorDark } from '@elastic/eui';
export const enforceColorContrast = (color: string, backgroundColor: string) => {
const finalColor =
chroma(color).alpha() < 1 ? chroma.blend(backgroundColor, color, 'overlay') : chroma(color);
return isColorDark(...finalColor.rgb());
};
export function isValidColor(colorString?: string) {
// chroma can handle also hex values with alpha channel/transparency
// chroma accepts also hex without #, so test for it
return (
colorString != null && colorString !== '' && /^#/.test(colorString) && chroma.valid(colorString)
);
}
export const getColorAlpha = (color?: string | null) =>
(color && isValidColor(color) && chroma(color)?.alpha()) || 1;
export const makeColorWithAlpha = (color: string, newAlpha: number) =>
chroma(color).alpha(newAlpha);

View file

@ -23,6 +23,7 @@ import {
useEuiTheme,
} from '@elastic/eui';
import { isValidColor } from '../../../color_manipulation';
import {
PaletteContinuity,
checkIsMaxContinuity,
@ -32,7 +33,6 @@ import {
import { RelatedIcon } from '../assets/related';
import { getAutoBoundInformation, isLastItem } from './utils';
import { isValidColor } from '../utils';
import {
ColorRangeDeleteButton,
ColorRangeAutoDetectButton,

View file

@ -7,7 +7,7 @@
*/
import { i18n } from '@kbn/i18n';
import { isValidColor } from '../utils';
import { isValidColor } from '../../../color_manipulation';
import type { ColorRange, ColorRangeAccessor } from './types';

View file

@ -6,15 +6,10 @@
* Side Public License, v 1.
*/
import {
getColorStops,
isValidColor,
mergePaletteParams,
updateRangeType,
changeColorPalette,
} from './utils';
import { getColorStops, mergePaletteParams, updateRangeType, changeColorPalette } from './utils';
import { getPaletteRegistry } from './mocks/palettes_registry';
import { isValidColor } from '../../color_manipulation';
describe('getColorStops', () => {
const paletteRegistry = getPaletteRegistry();
@ -103,6 +98,7 @@ describe('isValidColor', () => {
expect(isValidColor('#fff')).toBe(true);
expect(isValidColor('#ffffff')).toBe(true);
expect(isValidColor('#ffffffaa')).toBe(true);
expect(isValidColor('#fffa')).toBe(true);
});
it('should return false for non valid strings', () => {
@ -114,8 +110,6 @@ describe('isValidColor', () => {
expect(isValidColor('rgba(1, 1, 1, 0)')).toBe(false);
expect(isValidColor('#ffffffgg')).toBe(false);
expect(isValidColor('#fff00')).toBe(false);
// this version of chroma does not support hex4 format
expect(isValidColor('#fffa')).toBe(false);
});
});

View file

@ -6,8 +6,6 @@
* Side Public License, v 1.
*/
import chroma from 'chroma-js';
import {
DataBounds,
PaletteOutput,
@ -245,22 +243,6 @@ export function mergePaletteParams(
};
}
function isValidPonyfill(colorString: string) {
// we're using an old version of chroma without the valid function
try {
chroma(colorString);
return true;
} catch (e) {
return false;
}
}
export function isValidColor(colorString: string) {
// chroma can handle also hex values with alpha channel/transparency
// chroma accepts also hex without #, so test for it
return colorString !== '' && /^#/.test(colorString) && isValidPonyfill(colorString);
}
function getSwitchToCustomParams(
palettes: PaletteRegistry,
activePalette: PaletteOutput<CustomPaletteParams>,

View file

@ -7,7 +7,6 @@
*/
import React, { useEffect, useRef, useState } from 'react';
import chroma from 'chroma-js';
import { i18n } from '@kbn/i18n';
import {
EuiFormRow,
@ -17,6 +16,7 @@ import {
EuiIcon,
euiPaletteColorBlind,
} from '@elastic/eui';
import { getColorAlpha, makeColorWithAlpha } from '@kbn/coloring';
import { TooltipWrapper } from './tooltip_wrapper';
const tooltipContent = {
@ -32,28 +32,6 @@ const tooltipContent = {
}),
};
// copied from coloring package
function isValidPonyfill(colorString: string) {
// we're using an old version of chroma without the valid function
try {
chroma(colorString);
return true;
} catch (e) {
return false;
}
}
function isValidColor(colorString?: string) {
// chroma can handle also hex values with alpha channel/transparency
// chroma accepts also hex without #, so test for it
return (
colorString && colorString !== '' && /^#/.test(colorString) && isValidPonyfill(colorString)
);
}
const getColorAlpha = (color?: string | null) =>
(color && isValidColor(color) && chroma(color)?.alpha()) || 1;
export const ColorPicker = ({
label,
disableHelpTooltip,
@ -132,7 +110,7 @@ export const ColorPicker = ({
swatches={
currentColorAlpha === 1
? euiPaletteColorBlind()
: euiPaletteColorBlind().map((c) => chroma(c).alpha(currentColorAlpha).hex())
: euiPaletteColorBlind().map((c) => makeColorWithAlpha(c, currentColorAlpha).hex())
}
/>
);

View file

@ -13,7 +13,7 @@ import { css } from '@emotion/react';
import { euiThemeVars } from '@kbn/ui-theme';
import { DimensionButtonIcon } from './dimension_button_icon';
import { PaletteIndicator } from './palette_indicator';
import { AccessorConfig, Message } from './types';
import type { AccessorConfig, Message } from './types';
const triggerLinkA11yText = (label: string) =>
i18n.translate('visualizationUiComponents.dimensionButton.editConfig', {

View file

@ -8,7 +8,7 @@
import React from 'react';
import { EuiColorPaletteDisplay } from '@elastic/eui';
import { AccessorConfig } from './types';
import type { AccessorConfig } from './types';
export function PaletteIndicator({ accessorConfig }: { accessorConfig: AccessorConfig }) {
if (accessorConfig.triggerIconType !== 'colorBy' || !accessorConfig.palette) return null;

View file

@ -13,7 +13,7 @@ import useEffectOnce from 'react-use/lib/useEffectOnce';
import { EuiComboBox, EuiComboBoxProps, EuiFlexGroup, EuiFlexItem } from '@elastic/eui';
import { FieldIcon } from '@kbn/unified-field-list-plugin/public';
import classNames from 'classnames';
import { DataType } from './types';
import type { DataType } from './types';
import { TruncatedLabel } from './truncated_label';
import type { FieldOptionValue, FieldOption } from './types';

View file

@ -7,8 +7,7 @@
*/
import React, { useMemo } from 'react';
import { EuiMark } from '@elastic/eui';
import { EuiHighlight } from '@elastic/eui';
import { EuiMark, EuiHighlight } from '@elastic/eui';
const createContext = () =>
document.createElement('canvas').getContext('2d') as CanvasRenderingContext2D;

View file

@ -6,11 +6,8 @@
* Side Public License, v 1.
*/
import chroma from 'chroma-js';
import { VisualizationUiComponentsPlugin } from './plugin';
export { chroma };
export {
FieldPicker,
TruncatedLabel,

View file

@ -23,7 +23,8 @@
"@kbn/core-notifications-browser",
"@kbn/core-doc-links-browser",
"@kbn/core",
"@kbn/ui-theme"
"@kbn/ui-theme",
"@kbn/coloring"
],
"exclude": [
"target/**/*",

View file

@ -5,9 +5,7 @@
* 2.0.
*/
import { chroma } from '@kbn/visualization-ui-components/public';
import { euiLightVars, euiDarkVars } from '@kbn/ui-theme';
import { isColorDark } from '@elastic/eui';
import {
DataBounds,
@ -18,6 +16,7 @@ import {
reversePalette,
getPaletteStops,
CUSTOM_PALETTE,
enforceColorContrast,
} from '@kbn/coloring';
import { Datatable } from '@kbn/expressions-plugin/common';
@ -35,9 +34,7 @@ export function getContrastColor(
const backgroundColor = isDarkTheme
? euiDarkVars.euiPageBackgroundColor
: euiLightVars.euiPageBackgroundColor;
const finalColor =
chroma(color).alpha() < 1 ? chroma.blend(backgroundColor, color, 'overlay') : chroma(color);
return isColorDark(...finalColor.rgb()) ? lightColor : darkColor;
return enforceColorContrast(color, backgroundColor) ? lightColor : darkColor;
}
export function getNumericValue(rowValue: number | number[] | undefined) {

View file

@ -13,7 +13,7 @@ import {
RequiredPaletteParamTypes,
} from '@kbn/coloring';
import Color from 'color';
import chroma from 'chroma-js';
import { defaultPaletteParams as sharedDefaultParams } from '../../shared_components';
export const DEFAULT_PALETTE_NAME = 'gray';
@ -31,7 +31,7 @@ export const defaultPaletteParams: RequiredPaletteParamTypes = {
};
export const transparentizePalettes = (palettes: PaletteRegistry) => {
const addAlpha = (c: string | null) => (c ? new Color(c).hex() + `80` : `000000`);
const addAlpha = (c: string | null) => (c ? chroma(c).hex() + `80` : `000000`).toUpperCase();
const transparentizePalette = (palette: PaletteDefinition<unknown>) => ({
...palette,
getCategoricalColor: (

View file

@ -20,18 +20,18 @@ import {
isQueryAnnotationConfig,
isRangeAnnotationConfig,
} from '@kbn/event-annotation-plugin/public';
import Color from 'color';
import chroma from 'chroma-js';
import { pick } from 'lodash';
import moment from 'moment';
import type { FramePublicAPI } from '../../../../types';
import type { XYDataLayerConfig } from '../../types';
export const toRangeAnnotationColor = (color = defaultAnnotationColor) => {
return new Color(transparentize(color, 0.1)).hexa();
return chroma(transparentize(color, 0.1)).hex().toUpperCase();
};
export const toLineAnnotationColor = (color = defaultAnnotationRangeColor) => {
return new Color(transparentize(color, 1)).hex();
return chroma(transparentize(color, 1)).hex().toUpperCase();
};
export const getEndTimestamp = (

View file

@ -5025,7 +5025,7 @@
"@kbn/server-route-repository@link:packages/kbn-server-route-repository":
version "0.0.0"
uid ""
"@kbn/serverless-observability@link:x-pack/plugins/serverless_observability":
version "0.0.0"
uid ""
@ -5034,14 +5034,6 @@
version "0.0.0"
uid ""
"@kbn/serverless-storybook-config@link:packages/serverless/storybook/config":
version "0.0.0"
uid ""
"@kbn/serverless-types@link:packages/serverless/types":
version "0.0.0"
uid ""
"@kbn/serverless-search@link:x-pack/plugins/serverless_search":
version "0.0.0"
uid ""
@ -5050,6 +5042,14 @@
version "0.0.0"
uid ""
"@kbn/serverless-storybook-config@link:packages/serverless/storybook/config":
version "0.0.0"
uid ""
"@kbn/serverless-types@link:packages/serverless/types":
version "0.0.0"
uid ""
"@kbn/serverless@link:x-pack/plugins/serverless":
version "0.0.0"
uid ""
@ -7959,16 +7959,16 @@
dependencies:
"@types/node" "*"
"@types/chroma-js@^1.4.2":
version "1.4.2"
resolved "https://registry.yarnpkg.com/@types/chroma-js/-/chroma-js-1.4.2.tgz#3152c8dedfa8621f1ccaaabb40722a8aca808bcf"
integrity sha512-Ni8yCN1vF0yfnfKf5bNrBm+92EdZIX2sUk+A4t4QvO1x/9G04rGyC0nik4i5UcNfx8Q7MhX4XUDcy2nrkKQLFg==
"@types/chroma-js@^2.0.0":
version "2.0.0"
resolved "https://registry.yarnpkg.com/@types/chroma-js/-/chroma-js-2.0.0.tgz#b0fc98c8625d963f14e8138e0a7961103303ab22"
integrity sha512-iomunXsXjDxhm2y1OeJt8NwmgC7RyNkPAOddlYVGsbGoX8+1jYt84SG4/tf6RWcwzROLx1kPXPE95by1s+ebIg==
"@types/chroma-js@^2.1.0":
version "2.1.3"
resolved "https://registry.yarnpkg.com/@types/chroma-js/-/chroma-js-2.1.3.tgz#0b03d737ff28fad10eb884e0c6cedd5ffdc4ba0a"
integrity sha512-1xGPhoSGY1CPmXLCBcjVZSQinFjL26vlR8ZqprsBWiFyED4JacJJ9zHhh5aaUXqbY9B37mKQ73nlydVAXmr1+g==
"@types/chromedriver@^81.0.1":
version "81.0.1"
resolved "https://registry.yarnpkg.com/@types/chromedriver/-/chromedriver-81.0.1.tgz#bff3e4cdc7830dc0f115a9c0404f6979771064d4"
@ -11966,11 +11966,6 @@ chownr@^2.0.0:
resolved "https://registry.yarnpkg.com/chownr/-/chownr-2.0.0.tgz#15bfbe53d2eab4cf70f18a8cd68ebe5b3cb1dece"
integrity sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==
chroma-js@^1.4.1:
version "1.4.1"
resolved "https://registry.yarnpkg.com/chroma-js/-/chroma-js-1.4.1.tgz#eb2d9c4d1ff24616be84b35119f4d26f8205f134"
integrity sha512-jTwQiT859RTFN/vIf7s+Vl/Z2LcMrvMv3WUFmd/4u76AdlFC0NTNgqEEFPcRiHmAswPsMiQEDZLM8vX8qXpZNQ==
chroma-js@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/chroma-js/-/chroma-js-2.1.0.tgz#c0be48a21fe797ef8965608c1c4f911ef2da49d5"