mriField.tsx 5.5 KB

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