SilencePeriod.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { css } from '@emotion/css';
  2. import React from 'react';
  3. import { useController, useFormContext } from 'react-hook-form';
  4. import { dateTime, GrafanaTheme } from '@grafana/data';
  5. import { Field, TimeRangeInput, useStyles } from '@grafana/ui';
  6. import { SilenceFormFields } from '../../types/silence-form';
  7. export const SilencePeriod = () => {
  8. const { control, getValues } = useFormContext<SilenceFormFields>();
  9. const styles = useStyles(getStyles);
  10. const {
  11. field: { onChange: onChangeStartsAt, value: startsAt },
  12. fieldState: { invalid: startsAtInvalid },
  13. } = useController({
  14. name: 'startsAt',
  15. control,
  16. rules: {
  17. validate: (value) => getValues().endsAt > value,
  18. },
  19. });
  20. const {
  21. field: { onChange: onChangeEndsAt, value: endsAt },
  22. fieldState: { invalid: endsAtInvalid },
  23. } = useController({
  24. name: 'endsAt',
  25. control,
  26. rules: {
  27. validate: (value) => getValues().startsAt < value,
  28. },
  29. });
  30. const {
  31. field: { onChange: onChangeTimeZone, value: timeZone },
  32. } = useController({
  33. name: 'timeZone',
  34. control,
  35. });
  36. const invalid = startsAtInvalid || endsAtInvalid;
  37. const from = dateTime(startsAt);
  38. const to = dateTime(endsAt);
  39. return (
  40. <Field
  41. className={styles.timeRange}
  42. label="Silence start and end"
  43. error={invalid ? 'To is before or the same as from' : ''}
  44. invalid={invalid}
  45. >
  46. <TimeRangeInput
  47. value={{
  48. from,
  49. to,
  50. raw: {
  51. from,
  52. to,
  53. },
  54. }}
  55. timeZone={timeZone}
  56. onChange={(newValue) => {
  57. onChangeStartsAt(dateTime(newValue.from));
  58. onChangeEndsAt(dateTime(newValue.to));
  59. }}
  60. onChangeTimeZone={(newValue) => onChangeTimeZone(newValue)}
  61. hideTimeZone={false}
  62. hideQuickRanges={true}
  63. placeholder={'Select time range'}
  64. />
  65. </Field>
  66. );
  67. };
  68. const getStyles = (theme: GrafanaTheme) => ({
  69. timeRange: css`
  70. width: 400px;
  71. `,
  72. });