useResultsMode.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 {useGroupBys} from 'sentry/views/explore/hooks/useGroupBys';
  7. import {useSampleFields} from 'sentry/views/explore/hooks/useSampleFields';
  8. interface Options {
  9. location: Location;
  10. navigate: ReturnType<typeof useNavigate>;
  11. }
  12. export type ResultMode = 'samples' | 'aggregate';
  13. export function useResultMode(): [ResultMode, (newMode: ResultMode) => void] {
  14. const location = useLocation();
  15. const navigate = useNavigate();
  16. const options = {location, navigate};
  17. return useResultModeImpl(options);
  18. }
  19. function useResultModeImpl({
  20. location,
  21. navigate,
  22. }: Options): [ResultMode, (newMode: ResultMode) => void] {
  23. const [sampleFields] = useSampleFields();
  24. const {groupBys} = useGroupBys();
  25. const resultMode: ResultMode = useMemo(() => {
  26. const rawMode = decodeScalar(location.query.mode);
  27. if (rawMode === 'aggregate') {
  28. return 'aggregate' as const;
  29. }
  30. return 'samples' as const;
  31. }, [location.query.mode]);
  32. const setResultMode = useCallback(
  33. (newMode: ResultMode) => {
  34. // When switching from the aggregates to samples mode, carry
  35. // over any group bys as they are helpful context when looking
  36. // for examples.
  37. const fields = [...sampleFields];
  38. if (newMode === 'samples') {
  39. for (const groupBy of groupBys) {
  40. if (groupBy && !fields.includes(groupBy)) {
  41. fields.push(groupBy);
  42. }
  43. }
  44. }
  45. navigate({
  46. ...location,
  47. query: {
  48. ...location.query,
  49. mode: newMode,
  50. field: fields,
  51. },
  52. });
  53. },
  54. [location, navigate, sampleFields, groupBys]
  55. );
  56. return [resultMode, setResultMode];
  57. }