useBrowserSort.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import {fromSorts} from 'sentry/utils/discover/eventView';
  2. import type {Sort} from 'sentry/utils/discover/fields';
  3. import {useLocation} from 'sentry/utils/useLocation';
  4. import {QueryParameterNames} from 'sentry/views/starfish/views/queryParameters';
  5. type Query = {
  6. sort?: string;
  7. };
  8. const SORTABLE_FIELDS = ['count()', 'p75(transaction.duration)', 'transaction'] as const;
  9. export type ValidSort = Sort & {
  10. field: (typeof SORTABLE_FIELDS)[number];
  11. };
  12. /**
  13. * Parses a `Sort` object from the URL. In case of multiple specified sorts
  14. * picks the first one, since span module UIs only support one sort at a time.
  15. */
  16. export function useBrowserSort(
  17. sortParameterName: QueryParameterNames | 'sort' = 'sort',
  18. fallback: Sort = DEFAULT_SORT
  19. ) {
  20. const location = useLocation<Query>();
  21. return fromSorts(location.query[sortParameterName]).filter(isAValidSort)[0] ?? fallback;
  22. }
  23. const DEFAULT_SORT: Sort = {
  24. kind: 'desc',
  25. field: SORTABLE_FIELDS[0],
  26. };
  27. function isAValidSort(sort: Sort): sort is ValidSort {
  28. return (SORTABLE_FIELDS as unknown as string[]).includes(sort.field);
  29. }