replaySearchBar.tsx 6.4 KB

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