useBrowserSort.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import type {Sort} from 'sentry/utils/discover/fields';
  2. import {decodeSorts} from 'sentry/utils/queryString';
  3. import {useLocation} from 'sentry/utils/useLocation';
  4. import type {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 (
  22. decodeSorts(location.query[sortParameterName]).filter(isAValidSort)[0] ?? fallback
  23. );
  24. }
  25. const DEFAULT_SORT: Sort = {
  26. kind: 'desc',
  27. field: SORTABLE_FIELDS[0],
  28. };
  29. function isAValidSort(sort: Sort): sort is ValidSort {
  30. return (SORTABLE_FIELDS as unknown as string[]).includes(sort.field);
  31. }