diff --git a/packages/grafana-sql/src/components/configuration/ConnectionLimits.tsx b/packages/grafana-sql/src/components/configuration/ConnectionLimits.tsx index 10f0eebb147..667bc7fe5cb 100644 --- a/packages/grafana-sql/src/components/configuration/ConnectionLimits.tsx +++ b/packages/grafana-sql/src/components/configuration/ConnectionLimits.tsx @@ -3,25 +3,17 @@ import React from 'react'; import { DataSourceSettings } from '@grafana/data'; import { ConfigSubSection, Stack } from '@grafana/experimental'; import { config } from '@grafana/runtime'; -import { Field, Icon, InlineLabel, Input, Label, Switch, Tooltip } from '@grafana/ui'; +import { Field, Icon, InlineLabel, Label, Switch, Tooltip } from '@grafana/ui'; import { SQLConnectionLimits, SQLOptions } from '../../types'; +import { NumberInput } from './NumberInput'; + interface Props { onOptionsChange: Function; options: DataSourceSettings; } -function toNumber(text: string): number { - if (text.trim() === '') { - // calling `Number('')` returns zero, - // so we have to handle this case - return NaN; - } - - return Number(text); -} - export const ConnectionLimits = (props: Props) => { const { onOptionsChange, options } = props; const jsonData = options.jsonData; @@ -115,15 +107,11 @@ export const ConnectionLimits = (props: Props) } > - { - const newVal = toNumber(e.currentTarget.value); - if (!Number.isNaN(newVal)) { - onMaxConnectionsChanged(newVal); - } + { + onMaxConnectionsChanged(value); }} width={labelWidth} /> @@ -133,7 +121,7 @@ export const ConnectionLimits = (props: Props) label={ } > - { - const newVal = toNumber(e.currentTarget.value); - if (!Number.isNaN(newVal)) { - onJSONDataNumberChanged('connMaxLifetime')(newVal); - } + { + onJSONDataNumberChanged('connMaxLifetime')(value); }} width={labelWidth} /> diff --git a/packages/grafana-sql/src/components/configuration/NumberInput.tsx b/packages/grafana-sql/src/components/configuration/NumberInput.tsx new file mode 100644 index 00000000000..875dc921116 --- /dev/null +++ b/packages/grafana-sql/src/components/configuration/NumberInput.tsx @@ -0,0 +1,34 @@ +import React from 'react'; + +import { Input } from '@grafana/ui/src/components/Input/Input'; + +type NumberInputProps = { + value: number; + defaultValue: number; + onChange: (value: number) => void; + width: number; +}; + +export function NumberInput({ value, defaultValue, onChange, width }: NumberInputProps) { + const [isEmpty, setIsEmpty] = React.useState(false); + return ( + { + if (e.currentTarget.value?.trim() === '') { + setIsEmpty(true); + onChange(defaultValue); + } else { + setIsEmpty(false); + const newVal = Number(e.currentTarget.value); + if (!Number.isNaN(newVal)) { + onChange(newVal); + } + } + }} + width={width} + /> + ); +}