toolbarSortBy.tsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import {useCallback, useMemo} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {SelectOption} from 'sentry/components/compactSelect';
  4. import {CompactSelect} from 'sentry/components/compactSelect';
  5. import {t} from 'sentry/locale';
  6. import type {Sort} from 'sentry/utils/discover/fields';
  7. import type {Field} from 'sentry/views/explore/hooks/useSampleFields';
  8. import {ToolbarHeading, ToolbarSection} from './styles';
  9. interface ToolbarSortByProps {
  10. fields: Field[];
  11. setSorts: (newSorts: Sort[]) => void;
  12. sorts: Sort[];
  13. }
  14. export function ToolbarSortBy({fields, setSorts, sorts}: ToolbarSortByProps) {
  15. const fieldOptions: SelectOption<Field>[] = useMemo(() => {
  16. return fields.map(field => {
  17. return {
  18. label: field,
  19. value: field,
  20. };
  21. });
  22. }, [fields]);
  23. const setSortField = useCallback(
  24. (i: number, {value}: SelectOption<Field>) => {
  25. if (sorts[i]) {
  26. setSorts([
  27. {
  28. field: value,
  29. kind: sorts[i].kind,
  30. },
  31. ]);
  32. }
  33. },
  34. [setSorts, sorts]
  35. );
  36. const kindOptions: SelectOption<Sort['kind']>[] = useMemo(() => {
  37. return [
  38. {
  39. label: 'Descending',
  40. value: 'desc',
  41. },
  42. {
  43. label: 'Ascending',
  44. value: 'asc',
  45. },
  46. ];
  47. }, []);
  48. const setSortKind = useCallback(
  49. (i: number, {value}: SelectOption<Sort['kind']>) => {
  50. if (sorts[i]) {
  51. setSorts([
  52. {
  53. field: sorts[i].field,
  54. kind: value,
  55. },
  56. ]);
  57. }
  58. },
  59. [setSorts, sorts]
  60. );
  61. return (
  62. <ToolbarSection data-test-id="section-sort-by">
  63. <ToolbarHeading>{t('Sort By')}</ToolbarHeading>
  64. <ToolbarContent>
  65. <CompactSelect
  66. size="md"
  67. options={fieldOptions}
  68. value={sorts[0]?.field}
  69. onChange={newSortField => setSortField(0, newSortField)}
  70. />
  71. <CompactSelect
  72. size="md"
  73. options={kindOptions}
  74. value={sorts[0]?.kind}
  75. onChange={newSortKind => setSortKind(0, newSortKind)}
  76. />
  77. </ToolbarContent>
  78. </ToolbarSection>
  79. );
  80. }
  81. const ToolbarContent = styled('div')`
  82. display: flex;
  83. `;