useMonitorDates.tsx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 SelectionQuery {
  14. resolution: string;
  15. since: number;
  16. until: number;
  17. }
  18. interface UseMonitorTimesResult {
  19. /**
  20. * Contains values used in the monitor-stats API query
  21. */
  22. selectionQuery: SelectionQuery;
  23. /**
  24. * The computed timeWindowConfig
  25. */
  26. timeWindowConfig: TimeWindowConfig;
  27. }
  28. /**
  29. * Computes since, until, and resolution for monitor stats based on the current
  30. * selected page filters.
  31. */
  32. export function useMonitorTimes({timelineWidth}: Options): UseMonitorTimesResult {
  33. const nowRef = useRef<Date>(new Date());
  34. const {selection} = usePageFilters();
  35. const {start, end, period} = selection.datetime;
  36. let since: Date;
  37. let until: Date;
  38. if (!start || !end) {
  39. until = nowRef.current;
  40. since = moment(nowRef.current)
  41. .subtract(intervalToMilliseconds(period ?? '24h'), 'milliseconds')
  42. .toDate();
  43. } else {
  44. since = new Date(start);
  45. until = new Date(end);
  46. }
  47. const timeWindowConfig = getConfigFromTimeRange(since, until, timelineWidth);
  48. const elapsedMinutes = timeWindowConfig.elapsedMinutes;
  49. const rollup = Math.floor((elapsedMinutes * 60) / timelineWidth);
  50. const selectionQuery = {
  51. since: Math.floor(since.getTime() / 1000),
  52. until: Math.floor(until.getTime() / 1000),
  53. resolution: `${rollup}s`,
  54. };
  55. return {selectionQuery, timeWindowConfig};
  56. }