metricSearchBar.tsx 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import {useCallback, useMemo} from 'react';
  2. import styled from '@emotion/styled';
  3. import memoize from 'lodash/memoize';
  4. import type {SearchConfig} from 'sentry/components/searchSyntax/parser';
  5. import {
  6. FilterType,
  7. joinQuery,
  8. parseSearch,
  9. Token,
  10. } from 'sentry/components/searchSyntax/parser';
  11. import {treeTransformer} from 'sentry/components/searchSyntax/utils';
  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. const newTree = treeTransformer({
  41. tree: parsedSearch,
  42. transform: token => {
  43. if (token.type === Token.FILTER && token.filter === FilterType.TEXT) {
  44. if (!token.value.quoted) {
  45. return {
  46. ...token,
  47. // joinQuery() does not access nested tokens, so we need to manipulate the text of the filter instead of it's value
  48. text: `${token.key.text}:"${token.value.text}"`,
  49. };
  50. }
  51. }
  52. return token;
  53. },
  54. });
  55. return joinQuery(newTree);
  56. }
  57. export function MetricSearchBar({
  58. mri,
  59. blockedTags,
  60. disabled,
  61. onChange,
  62. query,
  63. projectIds,
  64. ...props
  65. }: MetricSearchBarProps) {
  66. const org = useOrganization();
  67. const api = useApi();
  68. const {selection} = usePageFilters();
  69. const projectIdNumbers = useMemo(
  70. () => projectIds?.map(id => parseInt(id, 10)),
  71. [projectIds]
  72. );
  73. const {data: tags = EMPTY_ARRAY, isLoading} = useMetricsTags(
  74. mri,
  75. {
  76. ...selection,
  77. projects: projectIdNumbers,
  78. },
  79. true,
  80. blockedTags
  81. );
  82. const supportedTags: TagCollection = useMemo(
  83. () => tags.reduce((acc, tag) => ({...acc, [tag.key]: tag}), {}),
  84. [tags]
  85. );
  86. const searchConfig = useMemo(
  87. () => ({
  88. booleanKeys: EMPTY_SET,
  89. dateKeys: EMPTY_SET,
  90. durationKeys: EMPTY_SET,
  91. numericKeys: EMPTY_SET,
  92. percentageKeys: EMPTY_SET,
  93. sizeKeys: EMPTY_SET,
  94. textOperatorKeys: EMPTY_SET,
  95. supportedTags,
  96. disallowFreeText: true,
  97. }),
  98. [supportedTags]
  99. );
  100. const fetchTagValues = useMemo(() => {
  101. const fn = memoize((tagKey: string) => {
  102. // clear response from cache after 10 seconds
  103. setTimeout(() => {
  104. fn.cache.delete(tagKey);
  105. }, 10000);
  106. return api.requestPromise(`/organizations/${org.slug}/metrics/tags/${tagKey}/`, {
  107. query: {
  108. metric: mri,
  109. useCase: getUseCaseFromMRI(mri),
  110. project: selection.projects,
  111. },
  112. });
  113. });
  114. return fn;
  115. }, [api, mri, org.slug, selection.projects]);
  116. const getTagValues = useCallback(
  117. async (tag: any, search: string) => {
  118. const tagsValues = await fetchTagValues(tag.key);
  119. return tagsValues
  120. .filter(
  121. tv =>
  122. tv.value !== '' &&
  123. tv.value.toLocaleLowerCase().includes(search.toLocaleLowerCase())
  124. )
  125. .map(tv => tv.value);
  126. },
  127. [fetchTagValues]
  128. );
  129. const handleChange = useCallback(
  130. (value: string, {validSearch} = {validSearch: true}) => {
  131. if (!validSearch) {
  132. return;
  133. }
  134. onChange(ensureQuotedTextFilters(value, searchConfig));
  135. },
  136. [onChange, searchConfig]
  137. );
  138. return (
  139. <WideSearchBar
  140. disabled={disabled}
  141. maxMenuHeight={220}
  142. organization={org}
  143. onGetTagValues={getTagValues}
  144. // don't highlight tags while loading as we don't know yet if they are supported
  145. highlightUnsupportedTags={!isLoading}
  146. onClose={handleChange}
  147. onSearch={handleChange}
  148. placeholder={t('Filter by tags')}
  149. query={query}
  150. savedSearchType={SavedSearchType.METRIC}
  151. {...searchConfig}
  152. {...props}
  153. />
  154. );
  155. }
  156. const WideSearchBar = styled(SmartSearchBar)`
  157. width: 100%;
  158. opacity: ${p => (p.disabled ? '0.6' : '1')};
  159. `;