useVisualize.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import {useCallback, useMemo} from 'react';
  2. import type {Location} from 'history';
  3. import {AggregationKey} from 'sentry/utils/fields';
  4. import {decodeScalar} from 'sentry/utils/queryString';
  5. import {useLocation} from 'sentry/utils/useLocation';
  6. import {useNavigate} from 'sentry/utils/useNavigate';
  7. import {SpanIndexedField} from 'sentry/views/insights/types';
  8. interface Options {
  9. location: Location;
  10. navigate: ReturnType<typeof useNavigate>;
  11. }
  12. // TODO: Extend the two lists below with more options upon backend support
  13. export const ALLOWED_VISUALIZE_FIELDS: SpanIndexedField[] = [
  14. SpanIndexedField.SPAN_DURATION,
  15. ];
  16. export const ALLOWED_VISUALIZE_AGGREGATES: AggregationKey[] = [AggregationKey.COUNT];
  17. export const DEFAULT_VISUALIZATION = `${ALLOWED_VISUALIZE_AGGREGATES[0]}(${ALLOWED_VISUALIZE_FIELDS[0]})`;
  18. export function useVisualize(): [string, (visualize: string) => void] {
  19. const location = useLocation();
  20. const navigate = useNavigate();
  21. const options = {location, navigate};
  22. return useVisualizeImpl(options);
  23. }
  24. function useVisualizeImpl({
  25. location,
  26. navigate,
  27. }: Options): [string, (visualize: string) => void] {
  28. const visualize: string | undefined = useMemo(() => {
  29. return decodeScalar(location.query.visualize) ?? DEFAULT_VISUALIZATION;
  30. }, [location.query.visualize]);
  31. const setVisualize = useCallback(
  32. (newVisualize: string) => {
  33. navigate({
  34. ...location,
  35. query: {
  36. ...location.query,
  37. visualize: newVisualize,
  38. },
  39. });
  40. },
  41. [location, navigate]
  42. );
  43. return [visualize, setVisualize];
  44. }