metricSearchBar.tsx 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import {useCallback, useMemo} from 'react';
  2. import styled from '@emotion/styled';
  3. import {useId} from '@react-aria/utils';
  4. import memoize from 'lodash/memoize';
  5. import type {SearchConfig} from 'sentry/components/searchSyntax/parser';
  6. import {
  7. FilterType,
  8. joinQuery,
  9. parseSearch,
  10. Token,
  11. } from 'sentry/components/searchSyntax/parser';
  12. import type {SmartSearchBarProps} from 'sentry/components/smartSearchBar';
  13. import SmartSearchBar from 'sentry/components/smartSearchBar';
  14. import {t} from 'sentry/locale';
  15. import type {MRI, TagCollection} from 'sentry/types';
  16. import {SavedSearchType} from 'sentry/types';
  17. import {getUseCaseFromMRI} from 'sentry/utils/metrics/mri';
  18. import {useMetricsTags} from 'sentry/utils/metrics/useMetricsTags';
  19. import useApi from 'sentry/utils/useApi';
  20. import useOrganization from 'sentry/utils/useOrganization';
  21. import usePageFilters from 'sentry/utils/usePageFilters';
  22. import {useSelectedProjects} from 'sentry/views/metrics/utils/useSelectedProjects';
  23. interface MetricSearchBarProps extends Partial<SmartSearchBarProps> {
  24. onChange: (value: string) => void;
  25. blockedTags?: string[];
  26. disabled?: boolean;
  27. mri?: MRI;
  28. projectIds?: string[];
  29. query?: string;
  30. }
  31. const EMPTY_ARRAY = [];
  32. const EMPTY_SET = new Set<never>();
  33. export function ensureQuotedTextFilters(
  34. query: string,
  35. configOverrides?: Partial<SearchConfig>
  36. ) {
  37. const parsedSearch = parseSearch(query, configOverrides);
  38. if (!parsedSearch) {
  39. return query;
  40. }
  41. for (let i = 0; i < parsedSearch.length; i++) {
  42. const token = parsedSearch[i];
  43. if (token.type === Token.FILTER && token.filter === FilterType.TEXT) {
  44. // joinQuery() does not access nested tokens, so we need to manipulate the text of the filter instead of it's value
  45. if (!token.value.quoted) {
  46. token.text = `${token.key.text}:"${token.value.text}"`;
  47. }
  48. const spaceToken = parsedSearch[i + 1];
  49. const afterSpaceToken = parsedSearch[i + 2];
  50. if (
  51. spaceToken &&
  52. afterSpaceToken &&
  53. spaceToken.type === Token.SPACES &&
  54. spaceToken.text === '' &&
  55. afterSpaceToken.type === Token.FILTER
  56. ) {
  57. // Ensure there is a space between two filters
  58. spaceToken.text = ' ';
  59. }
  60. }
  61. }
  62. return joinQuery(parsedSearch);
  63. }
  64. export function MetricSearchBar({
  65. mri,
  66. blockedTags,
  67. disabled,
  68. onChange,
  69. query,
  70. projectIds,
  71. id: idProp,
  72. ...props
  73. }: MetricSearchBarProps) {
  74. const org = useOrganization();
  75. const api = useApi();
  76. const {selection} = usePageFilters();
  77. const selectedProjects = useSelectedProjects();
  78. const id = useId(idProp);
  79. const projectIdNumbers = useMemo(
  80. () => projectIds?.map(projectId => parseInt(projectId, 10)),
  81. [projectIds]
  82. );
  83. const {data: tags = EMPTY_ARRAY, isLoading} = useMetricsTags(
  84. mri,
  85. {
  86. ...selection,
  87. projects: projectIdNumbers,
  88. },
  89. true,
  90. blockedTags
  91. );
  92. const supportedTags: TagCollection = useMemo(
  93. () => tags.reduce((acc, tag) => ({...acc, [tag.key]: tag}), {}),
  94. [tags]
  95. );
  96. const searchConfig = useMemo(
  97. () => ({
  98. booleanKeys: EMPTY_SET,
  99. dateKeys: EMPTY_SET,
  100. durationKeys: EMPTY_SET,
  101. numericKeys: EMPTY_SET,
  102. percentageKeys: EMPTY_SET,
  103. sizeKeys: EMPTY_SET,
  104. textOperatorKeys: EMPTY_SET,
  105. supportedTags,
  106. disallowFreeText: true,
  107. }),
  108. [supportedTags]
  109. );
  110. const fetchTagValues = useMemo(() => {
  111. const fn = memoize((tagKey: string) => {
  112. // clear response from cache after 10 seconds
  113. setTimeout(() => {
  114. fn.cache.delete(tagKey);
  115. }, 10000);
  116. return api.requestPromise(`/organizations/${org.slug}/metrics/tags/${tagKey}/`, {
  117. query: {
  118. metric: mri,
  119. useCase: getUseCaseFromMRI(mri),
  120. project: selection.projects,
  121. },
  122. });
  123. });
  124. return fn;
  125. }, [api, mri, org.slug, selection.projects]);
  126. const getTagValues = useCallback(
  127. async (tag: any, search: string) => {
  128. // The tag endpoint cannot provide values for the project tag
  129. if (tag.key === 'project') {
  130. return selectedProjects.map(project => project.slug);
  131. }
  132. const tagsValues = await fetchTagValues(tag.key);
  133. return tagsValues
  134. .filter(
  135. tv =>
  136. tv.value !== '' &&
  137. tv.value.toLocaleLowerCase().includes(search.toLocaleLowerCase())
  138. )
  139. .map(tv => tv.value);
  140. },
  141. [fetchTagValues, selectedProjects]
  142. );
  143. const handleChange = useCallback(
  144. (value: string, {validSearch} = {validSearch: true}) => {
  145. if (!validSearch) {
  146. return;
  147. }
  148. onChange(ensureQuotedTextFilters(value, searchConfig));
  149. },
  150. [onChange, searchConfig]
  151. );
  152. return (
  153. <WideSearchBar
  154. id={id}
  155. disabled={disabled}
  156. maxMenuHeight={220}
  157. organization={org}
  158. onGetTagValues={getTagValues}
  159. // don't highlight tags while loading as we don't know yet if they are supported
  160. highlightUnsupportedTags={!isLoading}
  161. onClose={handleChange}
  162. onSearch={handleChange}
  163. placeholder={t('Filter by tags')}
  164. query={query}
  165. savedSearchType={SavedSearchType.METRIC}
  166. disallowWildcard
  167. {...searchConfig}
  168. {...props}
  169. />
  170. );
  171. }
  172. const WideSearchBar = styled(SmartSearchBar)`
  173. width: 100%;
  174. opacity: ${p => (p.disabled ? '0.6' : '1')};
  175. `;