mriField.tsx 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import {Fragment, useCallback, useEffect, useMemo} from 'react';
  2. import styled from '@emotion/styled';
  3. import SelectControl from 'sentry/components/forms/controls/selectControl';
  4. import Tag from 'sentry/components/tag';
  5. import {t} from 'sentry/locale';
  6. import {space} from 'sentry/styles/space';
  7. import {MetricMeta, MRI, ParsedMRI, Project} from 'sentry/types';
  8. import {getReadableMetricType, isAllowedOp} from 'sentry/utils/metrics';
  9. import {
  10. DEFAULT_METRIC_ALERT_FIELD,
  11. formatMRI,
  12. MRIToField,
  13. parseField,
  14. parseMRI,
  15. } from 'sentry/utils/metrics/mri';
  16. import {useMetricsMeta} from 'sentry/utils/metrics/useMetricsMeta';
  17. import {middleEllipsis} from 'sentry/utils/middleEllipsis';
  18. interface Props {
  19. aggregate: string;
  20. onChange: (value: string, meta: Record<string, any>) => void;
  21. project: Project;
  22. }
  23. function filterAndSortOperations(operations: string[]) {
  24. return operations.filter(isAllowedOp).sort((a, b) => a.localeCompare(b));
  25. }
  26. function MriField({aggregate, project, onChange}: Props) {
  27. const {data: meta, isLoading} = useMetricsMeta([parseInt(project.id, 10)], {
  28. useCases: ['custom'],
  29. });
  30. const metaArr = useMemo(() => {
  31. return Object.values(meta)
  32. .map(
  33. metric =>
  34. ({
  35. ...metric,
  36. ...parseMRI(metric.mri),
  37. }) as ParsedMRI & MetricMeta
  38. )
  39. .sort((a, b) => a.name.localeCompare(b.name));
  40. }, [meta]);
  41. const selectedValues = parseField(aggregate) ?? {mri: '' as MRI, op: ''};
  42. const selectedMriMeta = selectedValues.mri ? meta[selectedValues.mri] : null;
  43. useEffect(() => {
  44. // Auto-select the first mri if none of the available ones is selected
  45. if (!selectedMriMeta && !isLoading) {
  46. const newSelection = metaArr[0];
  47. if (newSelection) {
  48. onChange(
  49. MRIToField(
  50. newSelection.mri,
  51. filterAndSortOperations(newSelection.operations)[0]
  52. ),
  53. {}
  54. );
  55. } else if (aggregate !== DEFAULT_METRIC_ALERT_FIELD) {
  56. onChange(DEFAULT_METRIC_ALERT_FIELD, {});
  57. }
  58. }
  59. }, [metaArr, onChange, selectedMriMeta, isLoading, aggregate]);
  60. const handleMriChange = useCallback(
  61. option => {
  62. // Make sure that the selected operation matches the new metric
  63. const availableOps = filterAndSortOperations(meta[option.value].operations);
  64. const selectedOp =
  65. selectedValues.op && availableOps.includes(selectedValues.op)
  66. ? selectedValues.op
  67. : availableOps[0];
  68. onChange(MRIToField(option.value, selectedOp), {});
  69. },
  70. [meta, onChange, selectedValues.op]
  71. );
  72. const operationOptions = useMemo(
  73. () =>
  74. filterAndSortOperations(selectedMriMeta?.operations ?? []).map(op => ({
  75. label: op,
  76. value: op,
  77. })),
  78. [selectedMriMeta]
  79. );
  80. // As SelectControl does not support an options size limit out of the box
  81. // we work around it by using the async variant of the control
  82. const getMriOptions = useCallback(
  83. (searchText: string) => {
  84. const filteredMeta = metaArr.filter(
  85. ({name}) =>
  86. searchText === '' || name.toLowerCase().includes(searchText.toLowerCase())
  87. );
  88. const options = filteredMeta.splice(0, 100).map<{
  89. label: React.ReactNode;
  90. value: string;
  91. disabled?: boolean;
  92. trailingItems?: React.ReactNode;
  93. }>(metric => ({
  94. label: middleEllipsis(metric.name, 50, /\.|-|_/),
  95. value: metric.mri,
  96. trailingItems: (
  97. <Fragment>
  98. <Tag tooltipText={t('Type')}>{getReadableMetricType(metric.type)}</Tag>
  99. <Tag tooltipText={t('Unit')}>{metric.unit}</Tag>
  100. </Fragment>
  101. ),
  102. }));
  103. if (filteredMeta.length > options.length) {
  104. options.push({
  105. label: (
  106. <SizeLimitMessage>{t('Use search to find more options…')}</SizeLimitMessage>
  107. ),
  108. value: '',
  109. disabled: true,
  110. });
  111. }
  112. return options;
  113. },
  114. [metaArr]
  115. );
  116. // When using the async variant of SelectControl, we need to pass in an option object instead of just the value
  117. const selectedMriOption = selectedMriMeta && {
  118. label: formatMRI(selectedMriMeta.mri),
  119. value: selectedMriMeta.mri,
  120. };
  121. return (
  122. <Wrapper>
  123. <StyledSelectControl
  124. searchable
  125. isDisabled={isLoading}
  126. placeholder={t('Select a metric')}
  127. noOptionsMessage={() =>
  128. metaArr.length === 0 ? t('No metrics in this project') : t('No options')
  129. }
  130. async
  131. defaultOptions={getMriOptions('')}
  132. loadOptions={searchText => Promise.resolve(getMriOptions(searchText))}
  133. filterOption={() => true}
  134. value={selectedMriOption}
  135. onChange={handleMriChange}
  136. />
  137. <StyledSelectControl
  138. searchable
  139. isDisabled={isLoading || !selectedMriMeta}
  140. placeholder={t('Select an operation')}
  141. options={operationOptions}
  142. value={selectedValues.op}
  143. onChange={option => {
  144. onChange(`${option.value}(${selectedValues.mri})`, {});
  145. }}
  146. />
  147. </Wrapper>
  148. );
  149. }
  150. export default MriField;
  151. const Wrapper = styled('div')`
  152. display: grid;
  153. gap: ${space(1)};
  154. grid-template-columns: 1fr 1fr;
  155. `;
  156. const StyledSelectControl = styled(SelectControl)`
  157. width: 200px;
  158. `;
  159. const SizeLimitMessage = styled('span')`
  160. font-size: ${p => p.theme.fontSizeSmall};
  161. display: block;
  162. width: 100%;
  163. text-align: center;
  164. `;