searchBar.tsx 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import {useEffect} from 'react';
  2. import assign from 'lodash/assign';
  3. import flatten from 'lodash/flatten';
  4. import memoize from 'lodash/memoize';
  5. import omit from 'lodash/omit';
  6. import {fetchTagValues} from 'sentry/actionCreators/tags';
  7. import SmartSearchBar from 'sentry/components/smartSearchBar';
  8. import {NEGATION_OPERATOR, SEARCH_WILDCARD} from 'sentry/constants';
  9. import {Organization, SavedSearchType, TagCollection} from 'sentry/types';
  10. import {defined} from 'sentry/utils';
  11. import {CustomMeasurementCollection} from 'sentry/utils/customMeasurements/customMeasurements';
  12. import {
  13. Field,
  14. FIELD_TAGS,
  15. isAggregateField,
  16. isEquation,
  17. isMeasurement,
  18. SEMVER_TAGS,
  19. SPAN_OP_BREAKDOWN_FIELDS,
  20. TRACING_FIELDS,
  21. } from 'sentry/utils/discover/fields';
  22. import {FieldKey, FieldKind} from 'sentry/utils/fields';
  23. import Measurements from 'sentry/utils/measurements/measurements';
  24. import useApi from 'sentry/utils/useApi';
  25. import withTags from 'sentry/utils/withTags';
  26. const SEARCH_SPECIAL_CHARS_REGEXP = new RegExp(
  27. `^${NEGATION_OPERATOR}|\\${SEARCH_WILDCARD}`,
  28. 'g'
  29. );
  30. const getFunctionTags = (fields: Readonly<Field[]>) =>
  31. Object.fromEntries(
  32. fields
  33. .filter(
  34. item => !Object.keys(FIELD_TAGS).includes(item.field) && !isEquation(item.field)
  35. )
  36. .map(item => [
  37. item.field,
  38. {key: item.field, name: item.field, kind: FieldKind.FUNCTION},
  39. ])
  40. );
  41. const getFieldTags = () =>
  42. Object.fromEntries(
  43. Object.keys(FIELD_TAGS).map(key => [
  44. key,
  45. {
  46. ...FIELD_TAGS[key],
  47. kind: FieldKind.FIELD,
  48. },
  49. ])
  50. );
  51. const getMeasurementTags = (
  52. measurements: Parameters<
  53. React.ComponentProps<typeof Measurements>['children']
  54. >[0]['measurements']
  55. ) =>
  56. Object.fromEntries(
  57. Object.keys(measurements).map(key => [
  58. key,
  59. {
  60. ...measurements[key],
  61. kind: FieldKind.MEASUREMENT,
  62. },
  63. ])
  64. );
  65. const getSpanTags = () => {
  66. return Object.fromEntries(
  67. SPAN_OP_BREAKDOWN_FIELDS.map(key => [key, {key, name: key, kind: FieldKind.METRICS}])
  68. );
  69. };
  70. const getSemverTags = () =>
  71. Object.fromEntries(
  72. Object.keys(SEMVER_TAGS).map(key => [
  73. key,
  74. {
  75. ...SEMVER_TAGS[key],
  76. kind: FieldKind.FIELD,
  77. },
  78. ])
  79. );
  80. export type SearchBarProps = Omit<React.ComponentProps<typeof SmartSearchBar>, 'tags'> & {
  81. organization: Organization;
  82. tags: TagCollection;
  83. customMeasurements?: CustomMeasurementCollection;
  84. fields?: Readonly<Field[]>;
  85. includeSessionTagsValues?: boolean;
  86. /**
  87. * Used to define the max height of the menu in px.
  88. */
  89. maxMenuHeight?: number;
  90. maxSearchItems?: React.ComponentProps<typeof SmartSearchBar>['maxSearchItems'];
  91. omitTags?: string[];
  92. projectIds?: number[] | Readonly<number[]>;
  93. };
  94. function SearchBar(props: SearchBarProps) {
  95. const {
  96. maxSearchItems,
  97. organization,
  98. tags,
  99. omitTags,
  100. fields,
  101. projectIds,
  102. includeSessionTagsValues,
  103. maxMenuHeight,
  104. customMeasurements,
  105. } = props;
  106. const api = useApi();
  107. useEffect(() => {
  108. // Clear memoized data on mount to make tests more consistent.
  109. getEventFieldValues.cache.clear?.();
  110. // eslint-disable-next-line react-hooks/exhaustive-deps
  111. }, [projectIds]);
  112. // Returns array of tag values that substring match `query`; invokes `callback`
  113. // with data when ready
  114. const getEventFieldValues = memoize(
  115. (tag, query, endpointParams): Promise<string[]> => {
  116. const projectIdStrings = (projectIds as Readonly<number>[])?.map(String);
  117. if (isAggregateField(tag.key) || isMeasurement(tag.key)) {
  118. // We can't really auto suggest values for aggregate fields
  119. // or measurements, so we simply don't
  120. return Promise.resolve([]);
  121. }
  122. return fetchTagValues(
  123. api,
  124. organization.slug,
  125. tag.key,
  126. query,
  127. projectIdStrings,
  128. endpointParams,
  129. // allows searching for tags on transactions as well
  130. true,
  131. // allows searching for tags on sessions as well
  132. includeSessionTagsValues
  133. ).then(
  134. results =>
  135. flatten(results.filter(({name}) => defined(name)).map(({name}) => name)),
  136. () => {
  137. throw new Error('Unable to fetch event field values');
  138. }
  139. );
  140. },
  141. ({key}, query) => `${key}-${query}`
  142. );
  143. const getTagList = (
  144. measurements: Parameters<
  145. React.ComponentProps<typeof Measurements>['children']
  146. >[0]['measurements']
  147. ) => {
  148. const functionTags = getFunctionTags(fields ?? []);
  149. const fieldTags = getFieldTags();
  150. const measurementsWithKind = getMeasurementTags(measurements);
  151. const spanTags = getSpanTags();
  152. const semverTags = getSemverTags();
  153. const orgHasPerformanceView = organization.features.includes('performance-view');
  154. const combinedTags: TagCollection = orgHasPerformanceView
  155. ? Object.assign({}, measurementsWithKind, spanTags, fieldTags, functionTags)
  156. : omit(fieldTags, TRACING_FIELDS);
  157. const tagsWithKind = Object.fromEntries(
  158. Object.keys(tags).map(key => [
  159. key,
  160. {
  161. ...tags[key],
  162. kind: FieldKind.TAG,
  163. },
  164. ])
  165. );
  166. assign(combinedTags, tagsWithKind, fieldTags, semverTags);
  167. const sortedTagKeys = Object.keys(combinedTags);
  168. sortedTagKeys.sort((a, b) => {
  169. return a.toLowerCase().localeCompare(b.toLowerCase());
  170. });
  171. combinedTags.has = {
  172. key: FieldKey.HAS,
  173. name: 'Has property',
  174. values: sortedTagKeys,
  175. predefined: true,
  176. kind: FieldKind.FIELD,
  177. };
  178. return omit(combinedTags, omitTags ?? []);
  179. };
  180. return (
  181. <Measurements>
  182. {({measurements}) => (
  183. <SmartSearchBar
  184. hasRecentSearches
  185. savedSearchType={SavedSearchType.EVENT}
  186. onGetTagValues={getEventFieldValues}
  187. supportedTags={getTagList({...measurements, ...(customMeasurements ?? {})})}
  188. prepareQuery={query => {
  189. // Prepare query string (e.g. strip special characters like negation operator)
  190. return query.replace(SEARCH_SPECIAL_CHARS_REGEXP, '');
  191. }}
  192. maxSearchItems={maxSearchItems}
  193. excludeEnvironment
  194. maxMenuHeight={maxMenuHeight ?? 300}
  195. {...props}
  196. />
  197. )}
  198. </Measurements>
  199. );
  200. }
  201. export default withTags(SearchBar);