TextBoxVariablePicker.tsx 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import React, { ChangeEvent, FocusEvent, KeyboardEvent, ReactElement, useCallback, useEffect, useState } from 'react';
  2. import { useDispatch } from 'react-redux';
  3. import { Input } from '@grafana/ui';
  4. import { variableAdapters } from '../adapters';
  5. import { VariablePickerProps } from '../pickers/types';
  6. import { toKeyedAction } from '../state/keyedVariablesReducer';
  7. import { changeVariableProp } from '../state/sharedReducer';
  8. import { TextBoxVariableModel } from '../types';
  9. import { toVariablePayload } from '../utils';
  10. export interface Props extends VariablePickerProps<TextBoxVariableModel> {}
  11. export function TextBoxVariablePicker({ variable, onVariableChange }: Props): ReactElement {
  12. const dispatch = useDispatch();
  13. const [updatedValue, setUpdatedValue] = useState(variable.current.value);
  14. useEffect(() => {
  15. setUpdatedValue(variable.current.value);
  16. }, [variable]);
  17. const updateVariable = useCallback(() => {
  18. if (!variable.rootStateKey) {
  19. console.error('Cannot update variable without rootStateKey');
  20. return;
  21. }
  22. if (variable.current.value === updatedValue) {
  23. return;
  24. }
  25. dispatch(
  26. toKeyedAction(
  27. variable.rootStateKey,
  28. changeVariableProp(
  29. toVariablePayload({ id: variable.id, type: variable.type }, { propName: 'query', propValue: updatedValue })
  30. )
  31. )
  32. );
  33. if (onVariableChange) {
  34. onVariableChange({
  35. ...variable,
  36. current: { ...variable.current, value: updatedValue },
  37. });
  38. return;
  39. }
  40. variableAdapters.get(variable.type).updateOptions(variable);
  41. }, [variable, updatedValue, dispatch, onVariableChange]);
  42. const onChange = useCallback(
  43. (event: ChangeEvent<HTMLInputElement>) => setUpdatedValue(event.target.value),
  44. [setUpdatedValue]
  45. );
  46. const onBlur = (e: FocusEvent<HTMLInputElement>) => updateVariable();
  47. const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
  48. if (event.keyCode === 13) {
  49. event.preventDefault();
  50. updateVariable();
  51. }
  52. };
  53. return (
  54. <Input
  55. type="text"
  56. value={updatedValue}
  57. onChange={onChange}
  58. onBlur={onBlur}
  59. onKeyDown={onKeyDown}
  60. placeholder="Enter variable value"
  61. id={`var-${variable.id}`}
  62. />
  63. );
  64. }