From a8a36867859d05343a844834374d0683cfb81bdf Mon Sep 17 00:00:00 2001 From: Jack Westbrook Date: Mon, 26 Oct 2020 12:21:41 +0100 Subject: [PATCH] Grafana/ui: auto focus threshold editor input (#28360) * feat(grafana-ui): autofocus threshold editor input * refactor(grafana-ui): remove commented out css * feat(grafana-ui): use ref for autofocus new thresholds editor input * refactor(grafana-ui): conditionally set input ref for latest threshold * refactor(grafana-ui): put back createRef for input ref --- .../ThresholdsEditorNew/ThresholdsEditor.tsx | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/packages/grafana-ui/src/components/ThresholdsEditorNew/ThresholdsEditor.tsx b/packages/grafana-ui/src/components/ThresholdsEditorNew/ThresholdsEditor.tsx index 442f9ecdc03..54b093dcf24 100644 --- a/packages/grafana-ui/src/components/ThresholdsEditorNew/ThresholdsEditor.tsx +++ b/packages/grafana-ui/src/components/ThresholdsEditorNew/ThresholdsEditor.tsx @@ -38,6 +38,8 @@ interface State { } export class ThresholdsEditor extends PureComponent { + private latestThresholdInputRef: React.RefObject; + constructor(props: Props) { super(props); @@ -45,6 +47,7 @@ export class ThresholdsEditor extends PureComponent { steps[0].value = -Infinity; this.state = { steps }; + this.latestThresholdInputRef = React.createRef(); } onAddThreshold = () => { @@ -67,7 +70,12 @@ export class ThresholdsEditor extends PureComponent { const newThresholds = [...steps, add]; sortThresholds(newThresholds); - this.setState({ steps: newThresholds }, this.onChange); + this.setState({ steps: newThresholds }, () => { + if (this.latestThresholdInputRef.current) { + this.latestThresholdInputRef.current.focus(); + } + this.onChange(); + }); }; onRemoveThreshold = (threshold: ThresholdWithKey) => { @@ -136,7 +144,7 @@ export class ThresholdsEditor extends PureComponent { }); }; - renderInput(threshold: ThresholdWithKey, styles: ThresholdStyles) { + renderInput(threshold: ThresholdWithKey, styles: ThresholdStyles, idx: number) { const isPercent = this.props.thresholds.mode === ThresholdsMode.Percentage; if (!isFinite(threshold.value)) { @@ -167,6 +175,7 @@ export class ThresholdsEditor extends PureComponent { key={isPercent.toString()} onChange={(event: ChangeEvent) => this.onChangeThresholdValue(event, threshold)} value={threshold.value} + ref={idx === 0 ? this.latestThresholdInputRef : null} onBlur={this.onBlur} prefix={
@@ -208,13 +217,11 @@ export class ThresholdsEditor extends PureComponent { {steps .slice(0) .reverse() - .map(threshold => { - return ( -
- {this.renderInput(threshold, styles)} -
- ); - })} + .map((threshold, idx) => ( +
+ {this.renderInput(threshold, styles, idx)} +
+ ))}
@@ -279,7 +286,6 @@ const getStyles = stylesFactory( wrapper: css` display: flex; flex-direction: column; - // margin-bottom: -${theme.spacing.formSpacingBase * 2}px; `, thresholds: css` display: flex;