useMonitorDates.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import {useRef} from 'react';
  2. import moment from 'moment';
  3. import {intervalToMilliseconds} from 'sentry/utils/dates';
  4. import usePageFilters from 'sentry/utils/usePageFilters';
  5. import {getConfigFromTimeRange} from 'sentry/views/monitors/components/overviewTimeline/utils';
  6. import type {TimeWindowConfig} from '../components/overviewTimeline/types';
  7. interface Options {
  8. /**
  9. * The width of the timeline influences how we calculate the rollup value
  10. */
  11. timelineWidth: number;
  12. }
  13. interface Dates {
  14. end: Date;
  15. start: Date;
  16. }
  17. interface SelectionQuery {
  18. resolution: string;
  19. since: number;
  20. until: number;
  21. }
  22. interface UseMonitorTimesResult {
  23. /**
  24. * Contains Date objects representing the start and end times of the
  25. * selection.
  26. */
  27. dates: Dates;
  28. /**
  29. * Contains values used in the monitor-stats API query
  30. */
  31. selectionQuery: SelectionQuery;
  32. /**
  33. * The computed timeWindowConfig
  34. */
  35. timeWindowConfig: TimeWindowConfig;
  36. }
  37. /**
  38. * Computes since, until, and resolution for monitor stats based on the current
  39. * selected page filters.
  40. */
  41. export function useMonitorTimes({timelineWidth}: Options): UseMonitorTimesResult {
  42. const nowRef = useRef<Date>(new Date());
  43. const {selection} = usePageFilters();
  44. const {start, end, period} = selection.datetime;
  45. let since: Date;
  46. let until: Date;
  47. if (!start || !end) {
  48. until = nowRef.current;
  49. since = moment(nowRef.current)
  50. .subtract(intervalToMilliseconds(period ?? '24h'), 'milliseconds')
  51. .toDate();
  52. } else {
  53. since = new Date(start);
  54. until = new Date(end);
  55. }
  56. const timeWindowConfig = getConfigFromTimeRange(since, until, timelineWidth);
  57. const elapsedMinutes = timeWindowConfig.elapsedMinutes;
  58. const rollup = Math.floor((elapsedMinutes * 60) / timelineWidth);
  59. const dates = {
  60. start: since,
  61. end: until,
  62. };
  63. const selectionQuery = {
  64. since: Math.floor(since.getTime() / 1000),
  65. until: Math.floor(until.getTime() / 1000),
  66. resolution: `${rollup}s`,
  67. };
  68. return {selectionQuery, dates, timeWindowConfig};
  69. }