mriField.tsx 5.4 KB

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