searchBar.tsx 5.9 KB

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