metricSearchBar.tsx 4.9 KB

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