From 0b033106b07d1574c406d7f432242f2bb0590564 Mon Sep 17 00:00:00 2001 From: Joao Silva <100691367+JoaoSilvaGrafana@users.noreply.github.com> Date: Thu, 14 Mar 2024 14:41:54 +0000 Subject: [PATCH] Cascader: Add clear button (#84449) --- .../src/components/Cascader/Cascader.tsx | 37 +++++++++++++++---- .../src/components/UnitPicker/UnitPicker.tsx | 1 + 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/packages/grafana-ui/src/components/Cascader/Cascader.tsx b/packages/grafana-ui/src/components/Cascader/Cascader.tsx index c4a46551db6..2e99cc65260 100644 --- a/packages/grafana-ui/src/components/Cascader/Cascader.tsx +++ b/packages/grafana-ui/src/components/Cascader/Cascader.tsx @@ -6,7 +6,9 @@ import React, { PureComponent } from 'react'; import { SelectableValue } from '@grafana/data'; import { Icon } from '../Icon/Icon'; +import { IconButton } from '../IconButton/IconButton'; import { Input } from '../Input/Input'; +import { Stack } from '../Layout/Stack/Stack'; import { Select } from '../Select/Select'; import { onChangeCascader } from './optionMappings'; @@ -40,6 +42,8 @@ export interface CascaderProps { disabled?: boolean; /** ID for the underlying Select/Cascader component */ id?: string; + /** Whether you can clear the selected value or not */ + isClearable?: boolean; } interface CascaderState { @@ -217,8 +221,17 @@ export class Cascader extends PureComponent { }; render() { - const { allowCustomValue, formatCreateLabel, placeholder, width, changeOnSelect, options, disabled, id } = - this.props; + const { + allowCustomValue, + formatCreateLabel, + placeholder, + width, + changeOnSelect, + options, + disabled, + id, + isClearable, + } = this.props; const { focusCascade, isSearching, rcValue, activeLabel, inputValue } = this.state; const searchableOptions = this.getSearchableOptions(options); @@ -262,11 +275,21 @@ export class Cascader extends PureComponent { onKeyDown={this.onInputKeyDown} onChange={() => {}} suffix={ - focusCascade ? ( - - ) : ( - - ) + + {isClearable && activeLabel !== '' && ( + { + e.preventDefault(); + e.stopPropagation(); + this.setState({ rcValue: [], activeLabel: '', inputValue: '' }); + this.props.onSelect(''); + }} + /> + )} + + } disabled={disabled} id={id} diff --git a/packages/grafana-ui/src/components/UnitPicker/UnitPicker.tsx b/packages/grafana-ui/src/components/UnitPicker/UnitPicker.tsx index 983aded2a6c..b9142f46b0d 100644 --- a/packages/grafana-ui/src/components/UnitPicker/UnitPicker.tsx +++ b/packages/grafana-ui/src/components/UnitPicker/UnitPicker.tsx @@ -62,6 +62,7 @@ export class UnitPicker extends PureComponent { formatCreateLabel={formatCreateLabel} options={groupOptions} placeholder="Choose" + isClearable onSelect={this.props.onChange} /> );