Skip to content

Commit

Permalink
[Lens] New random sampling shared plugin (#155068)
Browse files Browse the repository at this point in the history
## Summary

A new plugin to share the Random sampling logic across Kibana apps.
As starting point it contains the Random Sampling Icon + the setting
slider.

<img width="788" alt="Screenshot 2023-04-18 at 11 03 36"
src="https://user-images.githubusercontent.com/924948/232743718-9fad0308-9c21-4bd7-901f-9634ac3486ad.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)

---------

Co-authored-by: kibanamachine <[email protected]>
Co-authored-by: Stratoula Kalafateli <[email protected]>
  • Loading branch information
3 people authored May 2, 2023
1 parent df71c65 commit ca780c5
Show file tree
Hide file tree
Showing 32 changed files with 488 additions and 169 deletions.
1 change: 1 addition & 0 deletions .buildkite/scripts/steps/storybooks/build_and_upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ const STORYBOOKS = [
'ui_actions_enhanced',
'language_documentation_popover',
'unified_search',
'random_sampling',
];

const GITHUB_CONTEXT = 'Build and Publish Storybooks';
Expand Down
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,7 @@ examples/portable_dashboards_example @elastic/kibana-presentation
examples/preboot_example @elastic/kibana-security @elastic/kibana-core
src/plugins/presentation_util @elastic/kibana-presentation
x-pack/plugins/profiling @elastic/profiling-ui
x-pack/packages/kbn-random-sampling @elastic/kibana-visualizations
packages/kbn-react-field @elastic/kibana-data-discovery
x-pack/plugins/remote_clusters @elastic/platform-deployment-management
test/plugin_functional/plugins/rendering_plugin @elastic/kibana-core
Expand Down
1 change: 1 addition & 0 deletions .i18nrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
"navigation": "src/plugins/navigation",
"newsfeed": "src/plugins/newsfeed",
"presentationUtil": "src/plugins/presentation_util",
"randomSampling": "x-pack/packages/kbn-random-sampling",
"reporting": "packages/kbn-reporting/common",
"savedObjects": "src/plugins/saved_objects",
"savedObjectsFinder": "src/plugins/saved_objects_finder",
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,7 @@
"@kbn/preboot-example-plugin": "link:examples/preboot_example",
"@kbn/presentation-util-plugin": "link:src/plugins/presentation_util",
"@kbn/profiling-plugin": "link:x-pack/plugins/profiling",
"@kbn/random-sampling": "link:x-pack/packages/kbn-random-sampling",
"@kbn/react-field": "link:packages/kbn-react-field",
"@kbn/remote-clusters-plugin": "link:x-pack/plugins/remote_clusters",
"@kbn/rendering-plugin": "link:test/plugin_functional/plugins/rendering_plugin",
Expand Down
1 change: 1 addition & 0 deletions src/dev/storybook/aliases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export const storybookAliases = {
lists: 'x-pack/plugins/lists/.storybook',
observability: 'x-pack/plugins/observability/.storybook',
presentation: 'src/plugins/presentation_util/storybook',
random_sampling: 'x-pack/packages/kbn-random-sampling/.storybook',
security_solution: 'x-pack/plugins/security_solution/.storybook',
security_solution_packages: 'x-pack/packages/security-solution/storybook/config',
serverless: 'packages/serverless/storybook/config',
Expand Down
2 changes: 2 additions & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -1002,6 +1002,8 @@
"@kbn/presentation-util-plugin/*": ["src/plugins/presentation_util/*"],
"@kbn/profiling-plugin": ["x-pack/plugins/profiling"],
"@kbn/profiling-plugin/*": ["x-pack/plugins/profiling/*"],
"@kbn/random-sampling": ["x-pack/packages/kbn-random-sampling"],
"@kbn/random-sampling/*": ["x-pack/packages/kbn-random-sampling/*"],
"@kbn/react-field": ["packages/kbn-react-field"],
"@kbn/react-field/*": ["packages/kbn-react-field/*"],
"@kbn/remote-clusters-plugin": ["x-pack/plugins/remote_clusters"],
Expand Down
16 changes: 16 additions & 0 deletions x-pack/packages/kbn-random-sampling/.storybook/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* 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.
*/

const baseConfig = require('@kbn/storybook').defaultConfig;

module.exports = {
...baseConfig,
stories: ['../**/*.stories.mdx', ...baseConfig.stories],
typescript: {
reactDocgen: 'react-docgen-typescript',
},
};
13 changes: 13 additions & 0 deletions x-pack/packages/kbn-random-sampling/.storybook/preview.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
* 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.
*/

export const parameters = {
viewMode: 'docs',
previewTabs: {
canvas: { hidden: true },
},
};
10 changes: 10 additions & 0 deletions x-pack/packages/kbn-random-sampling/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# @kbn/random-sampling

Contains all the components of Kibana's random sampling experience. Specifically:
- UI components for rendering the random sampling configuration;

---

## Development

See the [kibana contributing guide](https://github.com/elastic/kibana/blob/main/CONTRIBUTING.md) for instructions setting up your development environment.
9 changes: 9 additions & 0 deletions x-pack/packages/kbn-random-sampling/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* 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.
*/

export { RandomSamplingSlider, RandomSamplingIcon } from './src';
export type { RandomSamplingSliderProps, RandomSamplingIconProps } from './src';
15 changes: 15 additions & 0 deletions x-pack/packages/kbn-random-sampling/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*
* 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.
*/

module.exports = {
preset: '@kbn/test',
rootDir: '../../..',
roots: ['<rootDir>/x-pack/packages/kbn-random-sampling'],
coverageDirectory: '<rootDir>/target/kibana-coverage/jest/x-pack/packages/kbn-random-sampling',
coverageReporters: ['text', 'html'],
collectCoverageFrom: ['<rootDir>/x-pack/packages/kbn-random-sampling/public/**/*.{ts,tsx}'],
};
5 changes: 5 additions & 0 deletions x-pack/packages/kbn-random-sampling/kibana.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"type": "shared-browser",
"id": "@kbn/random-sampling",
"owner": "@elastic/kibana-visualizations",
}
6 changes: 6 additions & 0 deletions x-pack/packages/kbn-random-sampling/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "@kbn/random-sampling",
"private": true,
"version": "1.0.0",
"license": "Elastic License 2.0"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { Canvas, Meta, Story, ArgsTable } from '@storybook/addon-docs/blocks';
import { I18nProvider } from '@kbn/i18n-react';
import { ControlSlider } from '../ui/slider_control'


export const Template = (args) => <I18nProvider><ControlSlider {...args} /></I18nProvider>;

<Meta
title="Random Sampling/Control Slider"
component={ControlSlider}
/>


# Overview

The following control slider component has been designed to work as a shared component in Kibana:

<Canvas>
<Story
name='basic'
args={
{
values:[0.00001, 0.0001, 0.001, 0.01, 0.1, 1],
currentValue:0.001,
'data-test-subj':'test-id'
}
}
argTypes={
{ onChange: { action: 'changed' } }
}
>
{Template.bind({})}
</Story>
</Canvas>

When the control slider is disabled an explanation tooltip is shown to the user:

<Canvas>
<Story
name='disabled'
args={
{
values:[0.00001, 0.0001, 0.001, 0.01, 0.1, 1],
currentValue:0.001,
disabled:true,
disabledReason:'Control was disabled due to X and Y',
'data-test-subj':'test-id'
}
}
argTypes={
{ onChange: { action: 'changed' } }
}
>
{Template.bind({})}
</Story>
</Canvas>

## Component props

The component exposes the following properties:

<ArgsTable story="basic"/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Canvas, Meta, Story, ArgsTable } from '@storybook/addon-docs/blocks';
import { RandomSamplingIcon } from '../ui/icon/sampling_icon'

<Meta title="Random Sampling/Icon" />

# Overview
The shared Random Sampling icon is the following

<Canvas>
<Story name='Basic Icon'>
<RandomSamplingIcon />
</Story>
</Canvas>

## Component table props

On top of common SVGElement props also the following props are supported by the component:

<ArgsTable of={RandomSamplingIcon}/>
12 changes: 12 additions & 0 deletions x-pack/packages/kbn-random-sampling/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* 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.
*/

export { RandomSamplingIcon, type RandomSamplingIconProps } from './ui/icon/sampling_icon';
export {
ControlSlider as RandomSamplingSlider,
type ControlSliderProps as RandomSamplingSliderProps,
} from './ui/slider_control';
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,17 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React from 'react';

interface CustomProps {
title?: string;
titleId?: string;
}

export function RandomSamplingIcon({
title,
titleId,
...props
}: React.SVGProps<SVGSVGElement> & CustomProps) {
export type RandomSamplingIconProps = React.SVGProps<SVGSVGElement> & CustomProps;

export function RandomSamplingIcon({ title, titleId, ...props }: RandomSamplingIconProps) {
return (
<svg
width="15"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* 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 { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import React from 'react';
import { I18nProvider } from '@kbn/i18n-react';
import { ControlSlider } from '.';

describe('Slider Control', () => {
it('should basically work', () => {
render(
<I18nProvider>
<ControlSlider
values={[0.1, 1]}
currentValue={0.1}
onChange={jest.fn()}
data-test-subj="test-id"
/>
</I18nProvider>
);
const input = screen.getByTestId('test-id') as HTMLInputElement;
expect(input.value).toBe('0'); // index 0 of the values array
});

it('should fallback to 1 when the provided value is not present within the values', () => {
render(
<I18nProvider>
<ControlSlider
values={[0.1, 0.5, 1]}
currentValue={2}
onChange={jest.fn()}
data-test-subj="test-id"
/>
</I18nProvider>
);
const input = screen.getByTestId('test-id') as HTMLInputElement;
expect(input.value).toBe('2'); // index 2 of the values array
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* 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 { EuiFlexGroup, EuiFlexItem, EuiRange, EuiText, useEuiTheme } from '@elastic/eui';
import React from 'react';
import { FormattedMessage } from '@kbn/i18n-react';
import { TooltipWrapper } from './tooltip_wrapper';

export interface ControlSliderProps {
/** Allowed values to show on the Control Slider */
values: number[];
/** Current value set */
currentValue: number | undefined;
/** When set will show the control in a disabled state */
disabled?: boolean;
/** An explanation for the disabled state of the control */
disabledReason?: string;
/** A way to pass the test id parameter */
'data-test-subj'?: string;
/** A callback for when the slider value changes */
onChange: (newValue: number) => void;
}

export function ControlSlider({
values,
currentValue,
disabled = false,
disabledReason = '',
onChange,
'data-test-subj': dataTestSubj,
}: ControlSliderProps) {
const { euiTheme } = useEuiTheme();
const samplingIndex = values.findIndex((v) => v === currentValue);
const currentSamplingIndex = samplingIndex > -1 ? samplingIndex : values.length - 1;
return (
<TooltipWrapper
tooltipContent={disabledReason}
condition={disabled}
delay="regular"
display="block"
>
<EuiFlexGroup gutterSize="none">
<EuiFlexItem grow={false}>
<EuiText
color={disabled ? euiTheme.colors.disabledText : euiTheme.colors.subduedText}
size="xs"
>
<FormattedMessage
id="randomSampling.ui.sliderControl.performanceLabel"
defaultMessage="Performance"
/>
</EuiText>
</EuiFlexItem>
<EuiFlexItem>
<EuiRange
data-test-subj={dataTestSubj}
value={currentSamplingIndex}
disabled={disabled}
fullWidth
onChange={(e) => {
onChange(values[Number(e.currentTarget.value)]);
}}
showInput={false}
showRange={false}
showTicks
step={1}
min={0}
max={values.length - 1}
ticks={values.map((v, i) => ({
// Remove the initial 0 from values with decimal digits: 0.001 => .001
label: `${v * 100}%`.slice(Number.isInteger(v * 100) ? 0 : 1),
value: i,
}))}
/>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiText
color={disabled ? euiTheme.colors.disabledText : euiTheme.colors.subduedText}
size="xs"
>
<FormattedMessage
id="randomSampling.ui.sliderControl.accuracyLabel"
defaultMessage="Accuracy"
/>
</EuiText>
</EuiFlexItem>
</EuiFlexGroup>
</TooltipWrapper>
);
}
Loading

0 comments on commit ca780c5

Please sign in to comment.