replaySearchBar.tsx 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import {useCallback, useEffect, useMemo} from 'react';
  2. import {fetchTagValues, loadOrganizationTags} from 'sentry/actionCreators/tags';
  3. import {SearchQueryBuilder} from 'sentry/components/searchQueryBuilder';
  4. import SmartSearchBar from 'sentry/components/smartSearchBar';
  5. import {MAX_QUERY_LENGTH, NEGATION_OPERATOR, SEARCH_WILDCARD} from 'sentry/constants';
  6. import {t} from 'sentry/locale';
  7. import type {Organization, PageFilters, Tag, TagCollection, TagValue} from 'sentry/types';
  8. import {SavedSearchType} from 'sentry/types/group';
  9. import {trackAnalytics} from 'sentry/utils/analytics';
  10. import {getUtcDateString} from 'sentry/utils/dates';
  11. import {isAggregateField} from 'sentry/utils/discover/fields';
  12. import {
  13. FieldKind,
  14. getFieldDefinition,
  15. REPLAY_CLICK_FIELDS,
  16. REPLAY_FIELDS,
  17. } from 'sentry/utils/fields';
  18. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  19. import useApi from 'sentry/utils/useApi';
  20. import useTags from 'sentry/utils/useTags';
  21. const SEARCH_SPECIAL_CHARS_REGEXP = new RegExp(
  22. `^${NEGATION_OPERATOR}|\\${SEARCH_WILDCARD}`,
  23. 'g'
  24. );
  25. /**
  26. * Prepare query string (e.g. strip special characters like negation operator)
  27. */
  28. function prepareQuery(searchQuery: string) {
  29. return searchQuery.replace(SEARCH_SPECIAL_CHARS_REGEXP, '');
  30. }
  31. const getReplayFieldDefinition = (key: string) => getFieldDefinition(key, 'replay');
  32. function fieldDefinitionsToTagCollection(fieldKeys: string[]): TagCollection {
  33. return Object.fromEntries(
  34. fieldKeys.map(key => [
  35. key,
  36. {
  37. key,
  38. name: key,
  39. ...getReplayFieldDefinition(key),
  40. },
  41. ])
  42. );
  43. }
  44. const REPLAY_FIELDS_AS_TAGS = fieldDefinitionsToTagCollection(REPLAY_FIELDS);
  45. const REPLAY_CLICK_FIELDS_AS_TAGS = fieldDefinitionsToTagCollection(REPLAY_CLICK_FIELDS);
  46. /**
  47. * Merges a list of supported tags and replay search fields into one collection.
  48. */
  49. function getReplaySearchTags(supportedTags: TagCollection): TagCollection {
  50. const allTags = {
  51. ...REPLAY_FIELDS_AS_TAGS,
  52. ...REPLAY_CLICK_FIELDS_AS_TAGS,
  53. ...Object.fromEntries(
  54. Object.keys(supportedTags).map(key => [
  55. key,
  56. {
  57. ...supportedTags[key],
  58. kind: getReplayFieldDefinition(key)?.kind ?? FieldKind.TAG,
  59. },
  60. ])
  61. ),
  62. };
  63. // A hack used to "sort" the dictionary for SearchQueryBuilder.
  64. // Technically dicts are unordered but this works in dev.
  65. // To guarantee ordering, we need to implement filterKeySections.
  66. const keys = Object.keys(allTags);
  67. keys.sort();
  68. return Object.fromEntries(keys.map(key => [key, allTags[key]]));
  69. }
  70. type Props = React.ComponentProps<typeof SmartSearchBar> & {
  71. organization: Organization;
  72. pageFilters: PageFilters;
  73. };
  74. function ReplaySearchBar(props: Props) {
  75. const {organization, pageFilters} = props;
  76. const api = useApi();
  77. const projectIds = pageFilters.projects;
  78. const organizationTags = useTags();
  79. useEffect(() => {
  80. loadOrganizationTags(api, organization.slug, pageFilters);
  81. }, [api, organization.slug, pageFilters]);
  82. const replayTags = useMemo(
  83. () => getReplaySearchTags(organizationTags),
  84. [organizationTags]
  85. );
  86. const getTagValues = useCallback(
  87. (tag: Tag, searchQuery: string): Promise<string[]> => {
  88. if (isAggregateField(tag.key)) {
  89. // We can't really auto suggest values for aggregate fields
  90. // or measurements, so we simply don't
  91. return Promise.resolve([]);
  92. }
  93. const endpointParams = {
  94. start: pageFilters.datetime.start
  95. ? getUtcDateString(pageFilters.datetime.start)
  96. : undefined,
  97. end: pageFilters.datetime.end
  98. ? getUtcDateString(pageFilters.datetime.end)
  99. : undefined,
  100. statsPeriod: pageFilters.datetime.period,
  101. };
  102. return fetchTagValues({
  103. api,
  104. orgSlug: organization.slug,
  105. tagKey: tag.key,
  106. search: searchQuery,
  107. projectIds: projectIds?.map(String),
  108. endpointParams,
  109. includeReplays: true,
  110. }).then(
  111. tagValues => (tagValues as TagValue[]).map(({value}) => value),
  112. () => {
  113. throw new Error('Unable to fetch event field values');
  114. }
  115. );
  116. },
  117. [
  118. api,
  119. organization.slug,
  120. projectIds,
  121. pageFilters.datetime.end,
  122. pageFilters.datetime.period,
  123. pageFilters.datetime.start,
  124. ]
  125. );
  126. const onSearch = props.onSearch;
  127. const onSearchWithAnalytics = useCallback(
  128. (query: string) => {
  129. onSearch?.(query);
  130. const conditions = new MutableSearch(query);
  131. const searchKeys = conditions.tokens.map(({key}) => key).filter(Boolean);
  132. if (searchKeys.length > 0) {
  133. trackAnalytics('replay.search', {
  134. search_keys: searchKeys.join(','),
  135. organization,
  136. });
  137. }
  138. },
  139. [onSearch, organization]
  140. );
  141. if (organization.features.includes('search-query-builder-replays')) {
  142. return (
  143. <SearchQueryBuilder
  144. {...props}
  145. onChange={undefined} // not implemented and different type from SmartSearchBar
  146. disallowLogicalOperators={undefined} // ^
  147. className={props.className}
  148. fieldDefinitionGetter={getReplayFieldDefinition}
  149. filterKeys={replayTags}
  150. filterKeySections={undefined}
  151. getTagValues={getTagValues}
  152. initialQuery={props.query ?? props.defaultQuery ?? ''}
  153. onSearch={onSearchWithAnalytics}
  154. searchSource={props.searchSource ?? 'replay_index'}
  155. placeholder={
  156. props.placeholder ??
  157. t('Search for users, duration, clicked elements, count_errors, and more')
  158. }
  159. recentSearches={SavedSearchType.REPLAY}
  160. />
  161. );
  162. }
  163. return (
  164. <SmartSearchBar
  165. {...props}
  166. onGetTagValues={getTagValues}
  167. supportedTags={replayTags}
  168. placeholder={
  169. props.placeholder ??
  170. t('Search for users, duration, clicked elements, count_errors, and more')
  171. }
  172. prepareQuery={prepareQuery}
  173. maxQueryLength={MAX_QUERY_LENGTH}
  174. searchSource={props.searchSource ?? 'replay_index'}
  175. savedSearchType={SavedSearchType.REPLAY}
  176. maxMenuHeight={500}
  177. hasRecentSearches
  178. projectIds={projectIds}
  179. fieldDefinitionGetter={getReplayFieldDefinition}
  180. mergeSearchGroupWith={{
  181. click: {
  182. documentation: t('Search by click selector. (Requires SDK version >= 7.44.0)'),
  183. },
  184. }}
  185. onSearch={onSearchWithAnalytics}
  186. />
  187. );
  188. }
  189. export default ReplaySearchBar;