searchBar.tsx 6.0 KB

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