useChartInterval.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import {useCallback, useMemo} from 'react';
  2. import type {Location} from 'history';
  3. import {decodeScalar} from 'sentry/utils/queryString';
  4. import {useLocation} from 'sentry/utils/useLocation';
  5. import {useNavigate} from 'sentry/utils/useNavigate';
  6. import usePageFilters from 'sentry/utils/usePageFilters';
  7. import {getIntervalOptionsForStatsPeriod} from 'sentry/views/metrics/utils/useMetricsIntervalParam';
  8. interface Options {
  9. location: Location;
  10. navigate: ReturnType<typeof useNavigate>;
  11. pagefilters: ReturnType<typeof usePageFilters>;
  12. }
  13. export function useChartInterval(): [
  14. string,
  15. (interval: string) => void,
  16. intervalOptions: {label: string; value: string}[],
  17. ] {
  18. const location = useLocation();
  19. const navigate = useNavigate();
  20. const pagefilters = usePageFilters();
  21. const options = {location, navigate, pagefilters};
  22. return useChartIntervalImpl(options);
  23. }
  24. function useChartIntervalImpl({
  25. location,
  26. navigate,
  27. pagefilters,
  28. }: Options): [
  29. string,
  30. (interval: string) => void,
  31. intervalOptions: {label: string; value: string}[],
  32. ] {
  33. const {datetime} = pagefilters.selection;
  34. const intervalOptions = useMemo(() => {
  35. return getIntervalOptionsForStatsPeriod(datetime);
  36. }, [datetime]);
  37. const interval: string = useMemo(() => {
  38. const decodedInterval = decodeScalar(location.query.interval);
  39. return decodedInterval &&
  40. intervalOptions.some(option => option.value === decodedInterval)
  41. ? decodedInterval
  42. : intervalOptions[0].value;
  43. }, [location.query.interval, intervalOptions]);
  44. const setInterval = useCallback(
  45. (newInterval: string) => {
  46. navigate({
  47. ...location,
  48. query: {
  49. ...location.query,
  50. interval: newInterval,
  51. },
  52. });
  53. },
  54. [location, navigate]
  55. );
  56. return [interval, setInterval, intervalOptions];
  57. }