grafana/public/app/features/variables/textbox/TextBoxVariablePicker.tsx
Josh Hunt 3c6e0e8ef8
Chore: ESlint import order (#44959)
* Add and configure eslint-plugin-import

* Fix the lint:ts npm command

* Autofix + prettier all the files

* Manually fix remaining files

* Move jquery code in jest-setup to external file to safely reorder imports

* Resolve issue caused by circular dependencies within Prometheus

* Update .betterer.results

* Fix missing // @ts-ignore

* ignore iconBundle.ts

* Fix missing // @ts-ignore
2022-04-22 14:33:13 +01:00

77 lines
2.2 KiB
TypeScript

import React, { ChangeEvent, FocusEvent, KeyboardEvent, ReactElement, useCallback, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { Input } from '@grafana/ui';
import { variableAdapters } from '../adapters';
import { VariablePickerProps } from '../pickers/types';
import { toKeyedAction } from '../state/keyedVariablesReducer';
import { changeVariableProp } from '../state/sharedReducer';
import { TextBoxVariableModel } from '../types';
import { toVariablePayload } from '../utils';
export interface Props extends VariablePickerProps<TextBoxVariableModel> {}
export function TextBoxVariablePicker({ variable, onVariableChange }: Props): ReactElement {
const dispatch = useDispatch();
const [updatedValue, setUpdatedValue] = useState(variable.current.value);
useEffect(() => {
setUpdatedValue(variable.current.value);
}, [variable]);
const updateVariable = useCallback(() => {
if (!variable.rootStateKey) {
console.error('Cannot update variable without rootStateKey');
return;
}
if (variable.current.value === updatedValue) {
return;
}
dispatch(
toKeyedAction(
variable.rootStateKey,
changeVariableProp(
toVariablePayload({ id: variable.id, type: variable.type }, { propName: 'query', propValue: updatedValue })
)
)
);
if (onVariableChange) {
onVariableChange({
...variable,
current: { ...variable.current, value: updatedValue },
});
return;
}
variableAdapters.get(variable.type).updateOptions(variable);
}, [variable, updatedValue, dispatch, onVariableChange]);
const onChange = useCallback(
(event: ChangeEvent<HTMLInputElement>) => setUpdatedValue(event.target.value),
[setUpdatedValue]
);
const onBlur = (e: FocusEvent<HTMLInputElement>) => updateVariable();
const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.keyCode === 13) {
event.preventDefault();
updateVariable();
}
};
return (
<Input
type="text"
value={updatedValue}
onChange={onChange}
onBlur={onBlur}
onKeyDown={onKeyDown}
placeholder="Enter variable value"
id={variable.id}
/>
);
}