useDateNavigation.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import {useCallback} from 'react';
  2. import moment from 'moment';
  3. import {updateDateTime} from 'sentry/actionCreators/pageFilters';
  4. import getDuration from 'sentry/utils/duration/getDuration';
  5. import useRouter from 'sentry/utils/useRouter';
  6. import {useMonitorDates} from './useMonitorDates';
  7. export interface DateNavigation {
  8. /**
  9. * Is the windows end aligned to the current time?
  10. */
  11. endIsNow: boolean;
  12. /**
  13. * A duration label indicating how far the navigation will navigate
  14. */
  15. label: React.ReactNode;
  16. /**
  17. * Updates the page filter date range to the next period using the current
  18. * period as a reference.
  19. */
  20. navigateToNextPeriod: () => void;
  21. /**
  22. * Updates the page filter date range to the previous period using the
  23. * current period as a reference.
  24. */
  25. navigateToPreviousPeriod: () => void;
  26. }
  27. export function useDateNavigation(): DateNavigation {
  28. const router = useRouter();
  29. const {since, until, nowRef} = useMonitorDates();
  30. const windowMs = until.getTime() - since.getTime();
  31. const navigateToPreviousPeriod = useCallback(() => {
  32. const nextUntil = moment(until).subtract(windowMs, 'milliseconds');
  33. const nextSince = moment(nextUntil).subtract(windowMs, 'milliseconds');
  34. updateDateTime({start: nextSince.toDate(), end: nextUntil.toDate()}, router);
  35. }, [windowMs, router, until]);
  36. const navigateToNextPeriod = useCallback(() => {
  37. // Do not navigate past the current time
  38. const nextUntil = moment.min(
  39. moment(until).add(windowMs, 'milliseconds'),
  40. moment(nowRef.current)
  41. );
  42. const nextSince = moment(nextUntil).subtract(windowMs, 'milliseconds');
  43. updateDateTime({start: nextSince.toDate(), end: nextUntil.toDate()}, router);
  44. }, [until, windowMs, nowRef, router]);
  45. return {
  46. endIsNow: until.getTime() === nowRef.current.getTime(),
  47. label: getDuration(windowMs / 1000),
  48. navigateToPreviousPeriod,
  49. navigateToNextPeriod,
  50. };
  51. }