[Controls] Adds step setting for range slider control (#174717)

## Summary

Closes #174542.


bb9e0297-a0a5-48e9-8424-457976ac3188

This adds a step interval option to the range slider control. 

<img width="300" alt="Screenshot 2024-01-17 at 4 06 05 PM"
src="79984cc9-1b82-42e9-bb7f-7bb71307c894">


This step setting allows values greater than 0, including decimal step
intervals.


95247aab-045b-4c0c-9004-dce01f3a10b1

When a step interval is defined, the number fields still show the
absolute min/max range available as placeholders, but the range slider
in the popover will be rounded to the nearest min/max multiple of the
step interval.

<img width="400" alt="Screenshot 2024-01-17 at 4 05 26 PM"
src="cf9e17f7-75a6-4d37-97ff-8a54526615cf">

Even with a step interval defined, values that fall between the step
intervals can be entered directly in the number fields.

<img width="400" alt="Screenshot 2024-01-17 at 4 07 42 PM"
src="5af10454-5ce0-448b-8fda-075396e55b78">


### 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
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] 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>
This commit is contained in:
Catherine Liu 2024-02-01 14:08:56 -08:00 committed by GitHub
parent 8166d18a37
commit 80d01ecca4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 182 additions and 19 deletions

View file

@ -14,6 +14,7 @@ export type RangeValue = [string, string];
export interface RangeSliderEmbeddableInput extends DataControlInput {
value?: RangeValue;
step?: number;
}
export type RangeSliderInputWithType = Partial<RangeSliderEmbeddableInput> & { type: string };

View file

@ -187,10 +187,34 @@ describe('Data control editor', () => {
expect(searchOptions.exists()).toBe(false);
});
test('when creating range slider, does not have custom settings', async () => {
test('when creating range slider, does have custom settings', async () => {
findTestSubject(controlEditor, 'create__rangeSliderControl').simulate('click');
const searchOptions = findTestSubject(controlEditor, 'control-editor-custom-settings');
expect(searchOptions.exists()).toBe(false);
expect(searchOptions.exists()).toBe(true);
});
test('when creating range slider, validates step setting is greater than 0', async () => {
findTestSubject(controlEditor, 'create__rangeSliderControl').simulate('click');
const stepOption = findTestSubject(
controlEditor,
'rangeSliderControl__stepAdditionalSetting'
);
expect(stepOption.exists()).toBe(true);
const saveButton = findTestSubject(controlEditor, 'control-editor-save');
expect(saveButton.instance()).toBeEnabled();
stepOption.simulate('change', { target: { valueAsNumber: undefined } });
expect(saveButton.instance()).toBeDisabled();
stepOption.simulate('change', { target: { valueAsNumber: 0.5 } });
expect(saveButton.instance()).toBeEnabled();
stepOption.simulate('change', { target: { valueAsNumber: 0 } });
expect(saveButton.instance()).toBeDisabled();
stepOption.simulate('change', { target: { valueAsNumber: 1 } });
expect(saveButton.instance()).toBeEnabled();
});
});

View file

@ -245,6 +245,7 @@ export const ControlEditor = ({
onChange={(settings) => setCustomSettings(settings)}
initialInput={embeddable?.getInput()}
fieldType={fieldRegistry[selectedField].field.type}
setControlEditorValid={setControlEditorValid}
/>
</EuiDescribedFormGroup>
);

View file

@ -19,11 +19,14 @@
text-align: center;
background-color: transparent;
&:invalid {
&.rangeSliderAnchor__fieldNumber--valid:invalid:not(:focus) {
background-image: none; // override the red underline for values between steps
}
&.rangeSliderAnchor__fieldNumber--invalid {
color: $euiTextSubduedColor;
text-decoration: line-through;
font-weight: $euiFontWeightRegular;
background-image: none; // hide the red bottom border
}
&:placeholder-shown, &::placeholder {

View file

@ -27,8 +27,9 @@ export const RangeSliderControl: FC = () => {
// Embeddable explicit input
const id = rangeSlider.select((state) => state.explicitInput.id);
const value = rangeSlider.select((state) => state.explicitInput.value);
const step = rangeSlider.select((state) => state.explicitInput.step);
// Embeddable cmponent state
// Embeddable component state
const min = rangeSlider.select((state) => state.componentState.min);
const max = rangeSlider.select((state) => state.componentState.max);
const error = rangeSlider.select((state) => state.componentState.error);
@ -62,8 +63,14 @@ export const RangeSliderControl: FC = () => {
selectedValue[0] === '' ? min : parseFloat(selectedValue[0]),
selectedValue[1] === '' ? max : parseFloat(selectedValue[1]),
];
return [Math.min(selectedMin, min), Math.max(selectedMax, max ?? Infinity)];
}, [min, max, value]);
if (!step) return [Math.min(selectedMin, min), Math.max(selectedMax, max ?? Infinity)];
const minTick = Math.floor(Math.min(selectedMin, min) / step) * step;
const maxTick = Math.ceil(Math.max(selectedMax, max) / step) * step;
return [Math.min(selectedMin, min, minTick), Math.max(selectedMax, max ?? Infinity, maxTick)];
}, [min, max, value, step]);
/**
* The following `useEffect` ensures that the changes to the value that come from the embeddable (for example,
@ -75,20 +82,33 @@ export const RangeSliderControl: FC = () => {
const ticks: EuiRangeTick[] = useMemo(() => {
return [
{ value: min ?? -Infinity, label: fieldFormatter(String(min)) },
{ value: max ?? Infinity, label: fieldFormatter(String(max)) },
{ value: displayedMin ?? -Infinity, label: fieldFormatter(String(displayedMin)) },
{ value: displayedMax ?? Infinity, label: fieldFormatter(String(displayedMax)) },
];
}, [min, max, fieldFormatter]);
}, [displayedMin, displayedMax, fieldFormatter]);
const levels = useMemo(() => {
if (!step || min === undefined || max === undefined) {
return [
{
min: min ?? -Infinity,
max: max ?? Infinity,
color: 'success',
},
];
}
const roundedMin = Math.floor(min / step) * step;
const roundedMax = Math.ceil(max / step) * step;
return [
{
min: min ?? -Infinity,
max: max ?? Infinity,
min: roundedMin,
max: roundedMax,
color: 'success',
},
];
}, [min, max]);
}, [step, min, max]);
const disablePopover = useMemo(
() =>
@ -110,15 +130,20 @@ export const RangeSliderControl: FC = () => {
placeholder: string;
}) => {
return {
isInvalid,
isInvalid: undefined, // disabling this prop to handle our own validation styling
placeholder,
readOnly: false, // overwrites `canOpenPopover` to ensure that the inputs are always clickable
className: 'rangeSliderAnchor__fieldNumber',
className: `rangeSliderAnchor__fieldNumber ${
isInvalid
? 'rangeSliderAnchor__fieldNumber--invalid'
: 'rangeSliderAnchor__fieldNumber--valid'
}`,
'data-test-subj': `rangeSlider__${testSubj}`,
value: inputValue === placeholder ? '' : inputValue,
title: !isInvalid && step ? '' : undefined, // overwrites native number input validation error when the value falls between two steps
};
},
[isInvalid]
[isInvalid, step]
);
return error ? (
@ -130,6 +155,7 @@ export const RangeSliderControl: FC = () => {
id={id}
fullWidth
showTicks
step={step}
ticks={ticks}
levels={levels}
min={displayedMin}

View file

@ -0,0 +1,42 @@
/*
* 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 React, { useState } from 'react';
import { EuiFormRow, EuiFieldNumber } from '@elastic/eui';
import type { RangeSliderEmbeddableInput } from '../../../common/range_slider/types';
import { ControlEditorProps } from '../../types';
import { RangeSliderStrings } from './range_slider_strings';
export const RangeSliderEditorOptions = ({
initialInput,
onChange,
setControlEditorValid,
}: ControlEditorProps<RangeSliderEmbeddableInput>) => {
const [step, setStep] = useState<number>(initialInput?.step || 1);
return (
<>
<EuiFormRow fullWidth label={RangeSliderStrings.editor.getStepTitle()}>
<EuiFieldNumber
value={step}
onChange={(event) => {
const newStep = event.target.valueAsNumber;
onChange({ step: newStep });
setStep(newStep);
setControlEditorValid(newStep > 0);
}}
min={0}
isInvalid={step <= 0}
data-test-subj="rangeSliderControl__stepAdditionalSetting"
/>
</EuiFormRow>
</>
);
};

View file

@ -9,6 +9,12 @@
import { i18n } from '@kbn/i18n';
export const RangeSliderStrings = {
editor: {
getStepTitle: () =>
i18n.translate('controls.rangeSlider.editor.stepSizeTitle', {
defaultMessage: 'Step size',
}),
},
popover: {
getNoAvailableDataHelpText: () =>
i18n.translate('controls.rangeSlider.popover.noAvailableDataHelpText', {

View file

@ -22,6 +22,7 @@ import {
RANGE_SLIDER_CONTROL,
} from '../../../common/range_slider/types';
import { ControlEmbeddable, IEditableControlFactory } from '../../types';
import { RangeSliderEditorOptions } from '../components/range_slider_editor_options';
export class RangeSliderEmbeddableFactory
implements EmbeddableFactoryDefinition, IEditableControlFactory<RangeSliderEmbeddableInput>
@ -44,6 +45,8 @@ export class RangeSliderEmbeddableFactory
public isEditable = () => Promise.resolve(true);
public controlEditorOptionsComponent = RangeSliderEditorOptions;
public async create(initialInput: RangeSliderEmbeddableInput, parent?: IContainer) {
const reduxEmbeddablePackage = await lazyLoadReduxToolsPackage();
const { RangeSliderEmbeddable } = await import('./range_slider_embeddable');

View file

@ -71,6 +71,7 @@ export interface ControlEditorProps<T extends ControlInput = ControlInput> {
initialInput?: Partial<T>;
fieldType: string;
onChange: (partial: Partial<T>) => void;
setControlEditorValid: (isValid: boolean) => void;
}
export interface DataControlField {

View file

@ -19,6 +19,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
const filterBar = getService('filterBar');
const testSubjects = getService('testSubjects');
const kibanaServer = getService('kibanaServer');
const browser = getService('browser');
const { dashboardControls, common, dashboard, header } = getPageObjects([
'dashboardControls',
'dashboard',
@ -74,6 +75,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
dataViewTitle: 'logstash-*',
fieldName: 'bytes',
width: 'small',
additionalSettings: { step: 10 },
});
expect(await dashboardControls.getControlsCount()).to.be(1);
await dashboard.clearUnsavedChanges();
@ -94,6 +96,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
dataViewTitle: 'kibana_sample_data_flights',
fieldName: 'AvgTicketPrice',
width: 'medium',
additionalSettings: { step: 100 },
});
expect(await dashboardControls.getControlsCount()).to.be(2);
const secondId = (await dashboardControls.getAllControlIds())[1];
@ -177,6 +180,38 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
await dashboard.clearUnsavedChanges();
});
it('can select a range on a defined step interval using arrow keys', async () => {
const secondId = (await dashboardControls.getAllControlIds())[1];
await testSubjects.click(
`range-slider-control-${secondId} > rangeSlider__lowerBoundFieldNumber`
);
// use arrow key to set lower bound to the next step up
await browser.pressKeys(browser.keys.ARROW_UP);
await dashboardControls.validateRange('value', secondId, '300', '');
// use arrow key to set lower bound to the next step up
await browser.pressKeys(browser.keys.ARROW_DOWN);
await dashboardControls.validateRange('value', secondId, '200', '');
await dashboardControls.rangeSliderSetUpperBound(secondId, '800');
await testSubjects.click(
`range-slider-control-${secondId} > rangeSlider__upperBoundFieldNumber`
);
// use arrow key to set upper bound to the next step up
await browser.pressKeys(browser.keys.ARROW_UP);
await dashboardControls.validateRange('value', secondId, '200', '900');
// use arrow key to set upper bound to the next step up
await browser.pressKeys(browser.keys.ARROW_DOWN);
await dashboardControls.validateRange('value', secondId, '200', '800');
await dashboard.clearUnsavedChanges();
});
it('can clear out selections by clicking the reset button', async () => {
const firstId = (await dashboardControls.getAllControlIds())[0];
await dashboardControls.clearControlSelections(firstId);

View file

@ -30,6 +30,10 @@ interface OptionsListAdditionalSettings {
hideSort?: boolean;
}
interface RangeSliderAdditionalSettings {
step?: number;
}
export const OPTIONS_LIST_ANIMAL_SOUND_SUGGESTIONS: { [key: string]: number } = {
hiss: 5,
ruff: 4,
@ -238,7 +242,7 @@ export class DashboardPageControls extends FtrService {
width?: ControlWidth;
dataViewTitle?: string;
grow?: boolean;
additionalSettings?: OptionsListAdditionalSettings;
additionalSettings?: OptionsListAdditionalSettings | RangeSliderAdditionalSettings;
}) {
this.log.debug(`Creating ${controlType} control ${title ?? fieldName}`);
await this.openCreateControlFlyout();
@ -254,8 +258,13 @@ export class DashboardPageControls extends FtrService {
if (additionalSettings) {
if (controlType === OPTIONS_LIST_CONTROL) {
// only options lists currently have additional settings
await this.optionsListSetAdditionalSettings(additionalSettings);
await this.optionsListSetAdditionalSettings(
additionalSettings as OptionsListAdditionalSettings
);
} else if (controlType === RANGE_SLIDER_CONTROL) {
await this.rangeSliderSetAdditionalSettings(
additionalSettings as RangeSliderAdditionalSettings
);
}
}
@ -627,6 +636,17 @@ export class DashboardPageControls extends FtrService {
return dataViewName;
}
// Range Slider editor functions
public async rangeSliderEditorSetStep(value: number) {
this.log.debug(`Setting range slider step to ${value}`);
await this.testSubjects.setValue('rangeSliderControl__stepAdditionalSetting', `${value}`);
}
public async rangeSliderSetAdditionalSettings({ step }: RangeSliderAdditionalSettings) {
this.log.debug(`Setting range slider step to ${step}`);
if (step) await this.rangeSliderEditorSetStep(step);
}
// Range slider functions
public async rangeSliderGetLowerBoundAttribute(controlId: string, attribute: string) {
this.log.debug(`Getting range slider lower bound ${attribute} for ${controlId}`);
@ -653,6 +673,7 @@ export class DashboardPageControls extends FtrService {
expect(await this.rangeSliderGetLowerBoundAttribute(controlId, 'value')).to.be(value);
});
}
public async rangeSliderSetUpperBound(controlId: string, value: string) {
this.log.debug(`Setting range slider lower bound to ${value}`);
await this.retry.try(async () => {