TimePickerInput.tsx 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import React, { PureComponent, ChangeEvent } from 'react';
  2. import { TimeFragment, TIME_FORMAT, TimeZone, isDateTime } from '@grafana/data';
  3. import { Input } from '../Input/Input';
  4. import { stringToDateTimeType, isValidTimeString } from './time';
  5. export interface Props {
  6. value: TimeFragment;
  7. roundup?: boolean;
  8. timeZone?: TimeZone;
  9. onChange: (value: string, isValid: boolean) => void;
  10. tabIndex?: number;
  11. }
  12. export class TimePickerInput extends PureComponent<Props> {
  13. isValid = (value: string) => {
  14. const { timeZone, roundup } = this.props;
  15. if (value.indexOf('now') !== -1) {
  16. const isValid = isValidTimeString(value);
  17. return isValid;
  18. }
  19. const parsed = stringToDateTimeType(value, roundup, timeZone);
  20. const isValid = parsed.isValid();
  21. return isValid;
  22. };
  23. onChange = (event: ChangeEvent<HTMLInputElement>) => {
  24. const { onChange } = this.props;
  25. const value = event.target.value;
  26. onChange(value, this.isValid(value));
  27. };
  28. valueToString = (value: TimeFragment) => {
  29. if (isDateTime(value)) {
  30. return value.format(TIME_FORMAT);
  31. } else {
  32. return value;
  33. }
  34. };
  35. render() {
  36. const { value, tabIndex } = this.props;
  37. const valueString = this.valueToString(value);
  38. const error = !this.isValid(valueString);
  39. return (
  40. <Input
  41. type="text"
  42. onChange={this.onChange}
  43. onBlur={this.onChange}
  44. hideErrorMessage={true}
  45. value={valueString}
  46. className={`time-picker-input${error ? '-error' : ''}`}
  47. tabIndex={tabIndex}
  48. />
  49. );
  50. }
  51. }