VariableInput.tsx 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import React, { PureComponent } from 'react';
  2. import { NavigationKey } from '../types';
  3. export interface Props extends Omit<React.HTMLProps<HTMLInputElement>, 'onChange' | 'value'> {
  4. onChange: (value: string) => void;
  5. onNavigate: (key: NavigationKey, clearOthers: boolean) => void;
  6. value: string | null;
  7. }
  8. export class VariableInput extends PureComponent<Props> {
  9. onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
  10. if (NavigationKey[event.keyCode]) {
  11. const clearOthers = event.ctrlKey || event.metaKey || event.shiftKey;
  12. this.props.onNavigate(event.keyCode as NavigationKey, clearOthers);
  13. event.preventDefault();
  14. }
  15. };
  16. onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  17. this.props.onChange(event.target.value);
  18. };
  19. render() {
  20. const { value, id, onNavigate, ...restProps } = this.props;
  21. return (
  22. <input
  23. {...restProps}
  24. ref={(instance) => {
  25. if (instance) {
  26. instance.focus();
  27. instance.setAttribute('style', `width:${Math.max(instance.width, 150)}px`);
  28. }
  29. }}
  30. type="text"
  31. className="gf-form-input"
  32. value={value ?? ''}
  33. onChange={this.onChange}
  34. onKeyDown={this.onKeyDown}
  35. placeholder="Enter variable value"
  36. />
  37. );
  38. }
  39. }