index.tsx 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020
  1. import {Component, createRef, VFC} from 'react';
  2. import TextareaAutosize from 'react-autosize-textarea';
  3. // eslint-disable-next-line no-restricted-imports
  4. import {withRouter, WithRouterProps} from 'react-router';
  5. import isPropValid from '@emotion/is-prop-valid';
  6. import styled from '@emotion/styled';
  7. import * as Sentry from '@sentry/react';
  8. import debounce from 'lodash/debounce';
  9. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  10. import {fetchRecentSearches, saveRecentSearch} from 'sentry/actionCreators/savedSearches';
  11. import {Client} from 'sentry/api';
  12. import ButtonBar from 'sentry/components/buttonBar';
  13. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  14. import {
  15. FilterType,
  16. ParseResult,
  17. parseSearch,
  18. SearchConfig,
  19. TermOperator,
  20. Token,
  21. TokenResult,
  22. } from 'sentry/components/searchSyntax/parser';
  23. import HighlightQuery from 'sentry/components/searchSyntax/renderer';
  24. import {
  25. getKeyName,
  26. isOperator,
  27. isWithinToken,
  28. treeResultLocator,
  29. } from 'sentry/components/searchSyntax/utils';
  30. import {
  31. DEFAULT_DEBOUNCE_DURATION,
  32. MAX_AUTOCOMPLETE_RELEASES,
  33. NEGATION_OPERATOR,
  34. } from 'sentry/constants';
  35. import {IconClose, IconEllipsis, IconSearch} from 'sentry/icons';
  36. import {t} from 'sentry/locale';
  37. import MemberListStore from 'sentry/stores/memberListStore';
  38. import space from 'sentry/styles/space';
  39. import {Organization, SavedSearchType, Tag, TagCollection, User} from 'sentry/types';
  40. import {defined} from 'sentry/utils';
  41. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  42. import {callIfFunction} from 'sentry/utils/callIfFunction';
  43. import {CustomMeasurementCollection} from 'sentry/utils/customMeasurements/customMeasurements';
  44. import {FieldDefinition, FieldValueType, getFieldDefinition} from 'sentry/utils/fields';
  45. import getDynamicComponent from 'sentry/utils/getDynamicComponent';
  46. import withApi from 'sentry/utils/withApi';
  47. import withOrganization from 'sentry/utils/withOrganization';
  48. import DropdownMenuControl from '../dropdownMenuControl';
  49. import {MenuItemProps} from '../dropdownMenuItem';
  50. import {ActionButton} from './actions';
  51. import SearchBarDatePicker from './searchBarDatePicker';
  52. import SearchDropdown from './searchDropdown';
  53. import SearchHotkeysListener from './searchHotkeysListener';
  54. import {
  55. AutocompleteGroup,
  56. ItemType,
  57. SearchGroup,
  58. SearchItem,
  59. Shortcut,
  60. ShortcutType,
  61. } from './types';
  62. import {
  63. addSpace,
  64. createSearchGroups,
  65. filterKeysFromQuery,
  66. generateOperatorEntryMap,
  67. getDateTagAutocompleteGroups,
  68. getSearchConfigFromCustomPerformanceMetrics,
  69. getSearchGroupWithItemMarkedActive,
  70. getTagItemsFromKeys,
  71. getValidOps,
  72. removeSpace,
  73. shortcuts,
  74. } from './utils';
  75. /**
  76. * The max width in pixels of the search bar at which the buttons will
  77. * have overflowed into the dropdown.
  78. */
  79. const ACTION_OVERFLOW_WIDTH = 400;
  80. /**
  81. * Actions are moved to the overflow dropdown after each pixel step is reached.
  82. */
  83. const ACTION_OVERFLOW_STEPS = 75;
  84. const generateOpAutocompleteGroup = (
  85. validOps: readonly TermOperator[],
  86. tagName: string
  87. ): AutocompleteGroup => {
  88. const operatorMap = generateOperatorEntryMap(tagName);
  89. const operatorItems = validOps.map(op => operatorMap[op]);
  90. return {
  91. searchItems: operatorItems,
  92. recentSearchItems: undefined,
  93. tagName: '',
  94. type: ItemType.TAG_OPERATOR,
  95. };
  96. };
  97. const escapeValue = (value: string): string => {
  98. // Wrap in quotes if there is a space
  99. return value.includes(' ') || value.includes('"')
  100. ? `"${value.replace(/"/g, '\\"')}"`
  101. : value;
  102. };
  103. export type ActionProps = {
  104. api: Client;
  105. /**
  106. * The organization
  107. */
  108. organization: Organization;
  109. /**
  110. * The current query
  111. */
  112. query: string;
  113. /**
  114. * The saved search type passed to the search bar
  115. */
  116. savedSearchType?: SavedSearchType;
  117. };
  118. export type ActionBarItem = {
  119. /**
  120. * Name of the action
  121. */
  122. key: string;
  123. makeAction: (props: ActionProps) => {Button: VFC; menuItem: MenuItemProps};
  124. };
  125. type DefaultProps = {
  126. defaultQuery: string;
  127. /**
  128. * Search items to display when there's no tag key. Is a tuple of search
  129. * items and recent search items
  130. */
  131. defaultSearchItems: [SearchItem[], SearchItem[]];
  132. /**
  133. * The lookup strategy for field definitions.
  134. * Each SmartSearchBar instance can support a different list of fields and tags,
  135. * their definitions may not overlap.
  136. */
  137. fieldDefinitionGetter: (key: string) => FieldDefinition | null;
  138. /**
  139. * Called when the user makes a search
  140. */
  141. onSearch: (query: string) => void;
  142. /**
  143. * Input placeholder
  144. */
  145. placeholder: string;
  146. query: string | null;
  147. /**
  148. * If this is defined, attempt to save search term scoped to the user and
  149. * the current org
  150. */
  151. savedSearchType: SavedSearchType;
  152. /**
  153. * Map of tags
  154. */
  155. supportedTags: TagCollection;
  156. /**
  157. * Wrap the input with a form. Useful if search bar is used within a parent
  158. * form
  159. */
  160. useFormWrapper: boolean;
  161. };
  162. type Props = WithRouterProps &
  163. Partial<DefaultProps> & {
  164. api: Client;
  165. organization: Organization;
  166. /**
  167. * Additional components to render as actions on the right of the search bar
  168. */
  169. actionBarItems?: ActionBarItem[];
  170. className?: string;
  171. /**
  172. * Custom Performance Metrics for query string unit parsing
  173. */
  174. customPerformanceMetrics?: CustomMeasurementCollection;
  175. /**
  176. * Disabled control (e.g. read-only)
  177. */
  178. disabled?: boolean;
  179. dropdownClassName?: string;
  180. /**
  181. * A list of tags to exclude from the autocompletion list, for ex environment may be excluded
  182. * because we don't want to treat environment as a tag in some places such
  183. * as the stream view where it is a top level concept
  184. */
  185. excludedTags?: string[];
  186. /**
  187. * List user's recent searches
  188. */
  189. hasRecentSearches?: boolean;
  190. /**
  191. * Whether or not to highlight unsupported tags red
  192. */
  193. highlightUnsupportedTags?: boolean;
  194. /**
  195. * Allows additional content to be played before the search bar and icon
  196. */
  197. inlineLabel?: React.ReactNode;
  198. /**
  199. * Maximum height for the search dropdown menu
  200. */
  201. maxMenuHeight?: number;
  202. /**
  203. * Used to enforce length on the query
  204. */
  205. maxQueryLength?: number;
  206. /**
  207. * Maximum number of search items to display or a falsey value for no
  208. * maximum
  209. */
  210. maxSearchItems?: number;
  211. /**
  212. * While the data is unused, this list of members can be updated to
  213. * trigger re-renders.
  214. */
  215. members?: User[];
  216. /**
  217. * Called when the search input is blurred.
  218. * Note that the input may be blurred when the user selects an autocomplete
  219. * value - if you don't want that, onClose may be a better option.
  220. */
  221. onBlur?: (value: string) => void;
  222. /**
  223. * Called when the search input changes
  224. */
  225. onChange?: (value: string, e: React.ChangeEvent) => void;
  226. /**
  227. * Called when the user has closed the search dropdown.
  228. * Occurs on escape, tab, or clicking outside the component.
  229. */
  230. onClose?: (value: string, additionalSearchBarState: {validSearch: boolean}) => void;
  231. /**
  232. * Get a list of recent searches for the current query
  233. */
  234. onGetRecentSearches?: (query: string) => Promise<SearchItem[]>;
  235. /**
  236. * Get a list of tag values for the passed tag
  237. */
  238. onGetTagValues?: (tag: Tag, query: string, params: object) => Promise<string[]>;
  239. /**
  240. * Called on key down
  241. */
  242. onKeyDown?: (evt: React.KeyboardEvent<HTMLTextAreaElement>) => void;
  243. /**
  244. * Called when a recent search is saved
  245. */
  246. onSavedRecentSearch?: (query: string) => void;
  247. /**
  248. * Prepare query value before filtering dropdown items
  249. */
  250. prepareQuery?: (query: string) => string;
  251. /**
  252. * Indicates the usage of the search bar for analytics
  253. */
  254. searchSource?: string;
  255. /**
  256. * Type of supported tags
  257. */
  258. supportedTagType?: ItemType;
  259. };
  260. type State = {
  261. /**
  262. * Index of the focused search item
  263. */
  264. activeSearchItem: number;
  265. flatSearchItems: SearchItem[];
  266. inputHasFocus: boolean;
  267. loading: boolean;
  268. /**
  269. * The number of actions that are not in the overflow menu.
  270. */
  271. numActionsVisible: number;
  272. /**
  273. * The query parsed into an AST. If the query fails to parse this will be
  274. * null.
  275. */
  276. parsedQuery: ParseResult | null;
  277. /**
  278. * The current search query in the input
  279. */
  280. query: string;
  281. searchGroups: SearchGroup[];
  282. /**
  283. * The current search term (or 'key') that that we will be showing
  284. * autocompletion for.
  285. */
  286. searchTerm: string;
  287. /**
  288. * Boolean indicating if dropdown should be shown
  289. */
  290. showDropdown: boolean;
  291. tags: Record<string, string>;
  292. /**
  293. * Indicates that we have a query that we've already determined not to have
  294. * any values. This is used to stop the autocompleter from querying if we
  295. * know we will find nothing.
  296. */
  297. noValueQuery?: string;
  298. /**
  299. * The query in the input since we last updated our autocomplete list.
  300. */
  301. previousQuery?: string;
  302. };
  303. class SmartSearchBar extends Component<DefaultProps & Props, State> {
  304. static defaultProps = {
  305. defaultQuery: '',
  306. query: null,
  307. onSearch: function () {},
  308. placeholder: t('Search for events, users, tags, and more'),
  309. supportedTags: {},
  310. defaultSearchItems: [[], []],
  311. useFormWrapper: true,
  312. savedSearchType: SavedSearchType.ISSUE,
  313. fieldDefinitionGetter: getFieldDefinition,
  314. } as DefaultProps;
  315. state: State = {
  316. query: this.initialQuery,
  317. showDropdown: false,
  318. parsedQuery: parseSearch(this.initialQuery, {
  319. ...getSearchConfigFromCustomPerformanceMetrics(this.props.customPerformanceMetrics),
  320. supportedTags: this.props.supportedTags,
  321. validateKeys: this.props.highlightUnsupportedTags,
  322. }),
  323. searchTerm: '',
  324. searchGroups: [],
  325. flatSearchItems: [],
  326. activeSearchItem: -1,
  327. tags: {},
  328. inputHasFocus: false,
  329. loading: false,
  330. numActionsVisible: this.props.actionBarItems?.length ?? 0,
  331. };
  332. componentDidMount() {
  333. if (!window.ResizeObserver) {
  334. return;
  335. }
  336. if (this.containerRef.current === null) {
  337. return;
  338. }
  339. this.inputResizeObserver = new ResizeObserver(this.updateActionsVisible);
  340. this.inputResizeObserver.observe(this.containerRef.current);
  341. }
  342. componentDidUpdate(prevProps: Props) {
  343. const {query, customPerformanceMetrics} = this.props;
  344. const {query: lastQuery, customPerformanceMetrics: lastCustomPerformanceMetrics} =
  345. prevProps;
  346. if (
  347. (query !== lastQuery && (defined(query) || defined(lastQuery))) ||
  348. customPerformanceMetrics !== lastCustomPerformanceMetrics
  349. ) {
  350. // eslint-disable-next-line react/no-did-update-set-state
  351. this.setState(this.makeQueryState(addSpace(query ?? undefined)));
  352. }
  353. }
  354. componentWillUnmount() {
  355. this.inputResizeObserver?.disconnect();
  356. document.removeEventListener('pointerup', this.onBackgroundPointerUp);
  357. }
  358. get initialQuery() {
  359. const {query, defaultQuery} = this.props;
  360. return query !== null ? addSpace(query) : defaultQuery ?? '';
  361. }
  362. makeQueryState(query: string) {
  363. const additionalConfig: Partial<SearchConfig> = {
  364. ...getSearchConfigFromCustomPerformanceMetrics(this.props.customPerformanceMetrics),
  365. supportedTags: this.props.supportedTags,
  366. validateKeys: this.props.highlightUnsupportedTags,
  367. };
  368. return {
  369. query,
  370. parsedQuery: parseSearch(query, additionalConfig),
  371. };
  372. }
  373. /**
  374. * Ref to the search element itself
  375. */
  376. searchInput = createRef<HTMLTextAreaElement>();
  377. /**
  378. * Ref to the search container
  379. */
  380. containerRef = createRef<HTMLDivElement>();
  381. /**
  382. * Used to determine when actions should be moved to the action overflow menu
  383. */
  384. inputResizeObserver: ResizeObserver | null = null;
  385. /**
  386. * Only closes the dropdown when pointer events occur outside of this component
  387. */
  388. onBackgroundPointerUp = (e: PointerEvent) => {
  389. if (this.containerRef.current?.contains(e.target as Node)) {
  390. return;
  391. }
  392. this.close();
  393. };
  394. /**
  395. * Updates the numActionsVisible count as the search bar is resized
  396. */
  397. updateActionsVisible = (entries: ResizeObserverEntry[]) => {
  398. if (entries.length === 0) {
  399. return;
  400. }
  401. const entry = entries[0];
  402. const {width} = entry.contentRect;
  403. const actionCount = this.props.actionBarItems?.length ?? 0;
  404. const numActionsVisible = Math.min(
  405. actionCount,
  406. Math.floor(Math.max(0, width - ACTION_OVERFLOW_WIDTH) / ACTION_OVERFLOW_STEPS)
  407. );
  408. if (this.state.numActionsVisible === numActionsVisible) {
  409. return;
  410. }
  411. this.setState({numActionsVisible});
  412. };
  413. blur() {
  414. if (!this.searchInput.current) {
  415. return;
  416. }
  417. this.searchInput.current.blur();
  418. this.close();
  419. }
  420. async doSearch() {
  421. this.blur();
  422. const query = removeSpace(this.state.query);
  423. const {organization, savedSearchType, searchSource} = this.props;
  424. if (!this.hasValidSearch) {
  425. trackAdvancedAnalyticsEvent('search.search_with_invalid', {
  426. organization,
  427. query,
  428. search_type: savedSearchType === 0 ? 'issues' : 'events',
  429. search_source: searchSource,
  430. });
  431. return;
  432. }
  433. const {onSearch, onSavedRecentSearch, api} = this.props;
  434. trackAdvancedAnalyticsEvent('search.searched', {
  435. organization,
  436. query,
  437. search_type: savedSearchType === 0 ? 'issues' : 'events',
  438. search_source: searchSource,
  439. });
  440. onSearch?.(query);
  441. // Only save recent search query if we have a savedSearchType (also 0 is a valid value)
  442. // Do not save empty string queries (i.e. if they clear search)
  443. if (typeof savedSearchType === 'undefined' || !query) {
  444. return;
  445. }
  446. try {
  447. await saveRecentSearch(api, organization.slug, savedSearchType, query);
  448. if (onSavedRecentSearch) {
  449. onSavedRecentSearch(query);
  450. }
  451. } catch (err) {
  452. // Silently capture errors if it fails to save
  453. Sentry.captureException(err);
  454. }
  455. }
  456. moveToNextToken = (filterTokens: TokenResult<Token.Filter>[]) => {
  457. const token = this.cursorToken;
  458. if (this.searchInput.current && filterTokens.length > 0) {
  459. this.searchInput.current.focus();
  460. let offset = filterTokens[0].location.end.offset;
  461. if (token) {
  462. const tokenIndex = filterTokens.findIndex(tok => tok === token);
  463. if (tokenIndex !== -1 && tokenIndex + 1 < filterTokens.length) {
  464. offset = filterTokens[tokenIndex + 1].location.end.offset;
  465. }
  466. }
  467. this.searchInput.current.selectionStart = offset;
  468. this.searchInput.current.selectionEnd = offset;
  469. this.updateAutoCompleteItems();
  470. }
  471. };
  472. deleteToken = () => {
  473. const {query} = this.state;
  474. const token = this.cursorToken ?? undefined;
  475. const filterTokens = this.filterTokens;
  476. const hasExecCommand = typeof document.execCommand === 'function';
  477. if (token && filterTokens.length > 0) {
  478. const index = filterTokens.findIndex(tok => tok === token) ?? -1;
  479. const newQuery =
  480. // We trim to remove any remaining spaces
  481. query.slice(0, token.location.start.offset).trim() +
  482. (index > 0 && index < filterTokens.length - 1 ? ' ' : '') +
  483. query.slice(token.location.end.offset).trim();
  484. if (this.searchInput.current) {
  485. // Only use exec command if exists
  486. this.searchInput.current.focus();
  487. this.searchInput.current.selectionStart = 0;
  488. this.searchInput.current.selectionEnd = query.length;
  489. // Because firefox doesn't support inserting an empty string, we insert a newline character instead
  490. // But because of this, only on firefox, if you delete the last token you won't be able to undo.
  491. if (
  492. (navigator.userAgent.toLowerCase().includes('firefox') &&
  493. newQuery.length === 0) ||
  494. !hasExecCommand ||
  495. !document.execCommand('insertText', false, newQuery)
  496. ) {
  497. // This will run either when newQuery is empty on firefox or when execCommand fails.
  498. this.updateQuery(newQuery);
  499. }
  500. }
  501. }
  502. };
  503. negateToken = () => {
  504. const {query} = this.state;
  505. const token = this.cursorToken ?? undefined;
  506. const hasExecCommand = typeof document.execCommand === 'function';
  507. if (token && token.type === Token.Filter) {
  508. if (token.negated) {
  509. if (this.searchInput.current) {
  510. this.searchInput.current.focus();
  511. const tokenCursorOffset = this.cursorPosition - token.key.location.start.offset;
  512. // Select the whole token so we can replace it.
  513. this.searchInput.current.selectionStart = token.location.start.offset;
  514. this.searchInput.current.selectionEnd = token.location.end.offset;
  515. // We can't call insertText with an empty string on Firefox, so we have to do this.
  516. if (
  517. !hasExecCommand ||
  518. !document.execCommand('insertText', false, token.text.slice(1))
  519. ) {
  520. // Fallback when execCommand fails
  521. const newQuery =
  522. query.slice(0, token.location.start.offset) +
  523. query.slice(token.key.location.start.offset);
  524. this.updateQuery(newQuery, this.cursorPosition - 1);
  525. }
  526. // Return the cursor to where it should be
  527. const newCursorPosition = token.location.start.offset + tokenCursorOffset;
  528. this.searchInput.current.selectionStart = newCursorPosition;
  529. this.searchInput.current.selectionEnd = newCursorPosition;
  530. }
  531. } else {
  532. if (this.searchInput.current) {
  533. this.searchInput.current.focus();
  534. const tokenCursorOffset = this.cursorPosition - token.key.location.start.offset;
  535. this.searchInput.current.selectionStart = token.location.start.offset;
  536. this.searchInput.current.selectionEnd = token.location.start.offset;
  537. if (!hasExecCommand || !document.execCommand('insertText', false, '!')) {
  538. // Fallback when execCommand fails
  539. const newQuery =
  540. query.slice(0, token.key.location.start.offset) +
  541. '!' +
  542. query.slice(token.key.location.start.offset);
  543. this.updateQuery(newQuery, this.cursorPosition + 1);
  544. }
  545. // Return the cursor to where it should be, +1 for the ! character we added
  546. const newCursorPosition = token.location.start.offset + tokenCursorOffset + 1;
  547. this.searchInput.current.selectionStart = newCursorPosition;
  548. this.searchInput.current.selectionEnd = newCursorPosition;
  549. }
  550. }
  551. }
  552. };
  553. logShortcutEvent = (shortcutType: ShortcutType, shortcutMethod: 'click' | 'hotkey') => {
  554. const {searchSource, savedSearchType, organization} = this.props;
  555. const {query} = this.state;
  556. trackAdvancedAnalyticsEvent('search.shortcut_used', {
  557. organization,
  558. search_type: savedSearchType === 0 ? 'issues' : 'events',
  559. search_source: searchSource,
  560. shortcut_method: shortcutMethod,
  561. shortcut_type: shortcutType,
  562. query,
  563. });
  564. };
  565. runShortcutOnClick = (shortcut: Shortcut) => {
  566. this.runShortcut(shortcut);
  567. this.logShortcutEvent(shortcut.shortcutType, 'click');
  568. };
  569. runShortcutOnHotkeyPress = (shortcut: Shortcut) => {
  570. this.runShortcut(shortcut);
  571. this.logShortcutEvent(shortcut.shortcutType, 'hotkey');
  572. };
  573. runShortcut = (shortcut: Shortcut) => {
  574. const token = this.cursorToken;
  575. const filterTokens = this.filterTokens;
  576. const {shortcutType, canRunShortcut} = shortcut;
  577. if (canRunShortcut(token, this.filterTokens.length)) {
  578. switch (shortcutType) {
  579. case ShortcutType.Delete: {
  580. this.deleteToken();
  581. break;
  582. }
  583. case ShortcutType.Negate: {
  584. this.negateToken();
  585. break;
  586. }
  587. case ShortcutType.Next: {
  588. this.moveToNextToken(filterTokens);
  589. break;
  590. }
  591. case ShortcutType.Previous: {
  592. this.moveToNextToken(filterTokens.reverse());
  593. break;
  594. }
  595. default:
  596. break;
  597. }
  598. }
  599. };
  600. onSubmit = (evt: React.FormEvent) => {
  601. evt.preventDefault();
  602. this.doSearch();
  603. };
  604. clearSearch = () => {
  605. this.setState(this.makeQueryState(''), () => {
  606. this.close();
  607. this.props.onSearch?.(this.state.query);
  608. });
  609. };
  610. close = () => {
  611. this.setState({showDropdown: false});
  612. this.props.onClose?.(this.state.query, {validSearch: this.hasValidSearch});
  613. document.removeEventListener('pointerup', this.onBackgroundPointerUp);
  614. };
  615. open = () => {
  616. this.setState({showDropdown: true});
  617. document.addEventListener('pointerup', this.onBackgroundPointerUp);
  618. };
  619. onQueryFocus = () => {
  620. this.open();
  621. this.setState({inputHasFocus: true});
  622. };
  623. onQueryBlur = (e: React.FocusEvent<HTMLTextAreaElement>) => {
  624. this.setState({inputHasFocus: false});
  625. this.props.onBlur?.(e.target.value);
  626. };
  627. onQueryChange = (evt: React.ChangeEvent<HTMLTextAreaElement>) => {
  628. const query = evt.target.value.replace('\n', '');
  629. this.setState(this.makeQueryState(query), this.updateAutoCompleteItems);
  630. this.props.onChange?.(evt.target.value, evt);
  631. };
  632. /**
  633. * Prevent pasting extra spaces from formatted text
  634. */
  635. onPaste = (evt: React.ClipboardEvent<HTMLTextAreaElement>) => {
  636. // Cancel paste
  637. evt.preventDefault();
  638. // Get text representation of clipboard
  639. const text = evt.clipboardData.getData('text/plain').replace('\n', '').trim();
  640. // Create new query
  641. const currentQuery = this.state.query;
  642. const cursorPosStart = this.searchInput.current!.selectionStart;
  643. const cursorPosEnd = this.searchInput.current!.selectionEnd;
  644. const textBefore = currentQuery.substring(0, cursorPosStart);
  645. const textAfter = currentQuery.substring(cursorPosEnd, currentQuery.length);
  646. const mergedText = `${textBefore}${text}${textAfter}`;
  647. // Insert text manually
  648. this.setState(this.makeQueryState(mergedText), () => {
  649. this.updateAutoCompleteItems();
  650. // Update cursor position after updating text
  651. const newCursorPosition = cursorPosStart + text.length;
  652. this.searchInput.current!.selectionStart = newCursorPosition;
  653. this.searchInput.current!.selectionEnd = newCursorPosition;
  654. });
  655. callIfFunction(this.props.onChange, mergedText, evt);
  656. };
  657. onInputClick = () => {
  658. this.open();
  659. this.updateAutoCompleteItems();
  660. };
  661. /**
  662. * Handle keyboard navigation
  663. */
  664. onKeyDown = (evt: React.KeyboardEvent<HTMLTextAreaElement>) => {
  665. const {onKeyDown} = this.props;
  666. const {key} = evt;
  667. onKeyDown?.(evt);
  668. const hasSearchGroups = this.state.searchGroups.length > 0;
  669. const isSelectingDropdownItems = this.state.activeSearchItem !== -1;
  670. if (!this.state.showDropdown && key !== 'Escape') {
  671. this.open();
  672. }
  673. if ((key === 'ArrowDown' || key === 'ArrowUp') && hasSearchGroups) {
  674. evt.preventDefault();
  675. const {flatSearchItems, activeSearchItem} = this.state;
  676. let searchGroups = [...this.state.searchGroups];
  677. const currIndex = isSelectingDropdownItems ? activeSearchItem : 0;
  678. const totalItems = flatSearchItems.length;
  679. // Move the selected index up/down
  680. const nextActiveSearchItem =
  681. key === 'ArrowUp'
  682. ? (currIndex - 1 + totalItems) % totalItems
  683. : isSelectingDropdownItems
  684. ? (currIndex + 1) % totalItems
  685. : 0;
  686. // Clear previous selection
  687. const prevItem = flatSearchItems[currIndex];
  688. searchGroups = getSearchGroupWithItemMarkedActive(searchGroups, prevItem, false);
  689. // Set new selection
  690. const activeItem = flatSearchItems[nextActiveSearchItem];
  691. searchGroups = getSearchGroupWithItemMarkedActive(searchGroups, activeItem, true);
  692. this.setState({searchGroups, activeSearchItem: nextActiveSearchItem});
  693. }
  694. if (
  695. (key === 'Tab' || key === 'Enter') &&
  696. isSelectingDropdownItems &&
  697. hasSearchGroups
  698. ) {
  699. evt.preventDefault();
  700. const {activeSearchItem, flatSearchItems} = this.state;
  701. const item = flatSearchItems[activeSearchItem];
  702. if (item) {
  703. if (item.callback) {
  704. item.callback();
  705. } else {
  706. this.onAutoComplete(item.value ?? '', item);
  707. }
  708. }
  709. return;
  710. }
  711. // If not selecting an item, allow tab to exit search and close the dropdown
  712. if (key === 'Tab' && !isSelectingDropdownItems) {
  713. this.close();
  714. return;
  715. }
  716. if (key === 'Enter' && !isSelectingDropdownItems) {
  717. this.doSearch();
  718. return;
  719. }
  720. const cursorToken = this.cursorToken;
  721. if (
  722. key === '[' &&
  723. cursorToken?.type === Token.Filter &&
  724. cursorToken.value.text.length === 0 &&
  725. isWithinToken(cursorToken.value, this.cursorPosition)
  726. ) {
  727. const {query} = this.state;
  728. evt.preventDefault();
  729. let clauseStart: null | number = null;
  730. let clauseEnd: null | number = null;
  731. // the new text that will exist between clauseStart and clauseEnd
  732. const replaceToken = '[]';
  733. const location = cursorToken.value.location;
  734. const keyLocation = cursorToken.key.location;
  735. // Include everything after the ':'
  736. clauseStart = keyLocation.end.offset + 1;
  737. clauseEnd = location.end.offset + 1;
  738. const beforeClause = query.substring(0, clauseStart);
  739. let endClause = query.substring(clauseEnd);
  740. // Add space before next clause if it exists
  741. if (endClause) {
  742. endClause = ` ${endClause}`;
  743. }
  744. const newQuery = `${beforeClause}${replaceToken}${endClause}`;
  745. // Place cursor between inserted brackets
  746. this.updateQuery(newQuery, beforeClause.length + replaceToken.length - 1);
  747. return;
  748. }
  749. };
  750. onKeyUp = (evt: React.KeyboardEvent<HTMLTextAreaElement>) => {
  751. if (evt.key === 'ArrowLeft' || evt.key === 'ArrowRight') {
  752. this.updateAutoCompleteItems();
  753. }
  754. // Other keys are managed at onKeyDown function
  755. if (evt.key !== 'Escape') {
  756. return;
  757. }
  758. evt.preventDefault();
  759. if (!this.state.showDropdown) {
  760. this.blur();
  761. return;
  762. }
  763. const {flatSearchItems, activeSearchItem} = this.state;
  764. const isSelectingDropdownItems = this.state.activeSearchItem > -1;
  765. let searchGroups = [...this.state.searchGroups];
  766. if (isSelectingDropdownItems) {
  767. searchGroups = getSearchGroupWithItemMarkedActive(
  768. searchGroups,
  769. flatSearchItems[activeSearchItem],
  770. false
  771. );
  772. }
  773. this.setState({
  774. activeSearchItem: -1,
  775. searchGroups,
  776. });
  777. this.close();
  778. };
  779. /**
  780. * Check if any filters are invalid within the search query
  781. */
  782. get hasValidSearch() {
  783. const {parsedQuery} = this.state;
  784. // If we fail to parse be optimistic that it's valid
  785. if (parsedQuery === null) {
  786. return true;
  787. }
  788. return treeResultLocator<boolean>({
  789. tree: parsedQuery,
  790. noResultValue: true,
  791. visitorTest: ({token, returnResult, skipToken}) =>
  792. token.type !== Token.Filter
  793. ? null
  794. : token.invalid
  795. ? returnResult(false)
  796. : skipToken,
  797. });
  798. }
  799. /**
  800. * Get the active filter or free text actively focused.
  801. */
  802. get cursorToken() {
  803. const matchedTokens = [Token.Filter, Token.FreeText] as const;
  804. return this.findTokensAtCursor(matchedTokens);
  805. }
  806. /**
  807. * Get the active parsed text value
  808. */
  809. get cursorValue() {
  810. const matchedTokens = [Token.ValueText] as const;
  811. return this.findTokensAtCursor(matchedTokens);
  812. }
  813. /**
  814. * Get the active filter
  815. */
  816. get cursorFilter() {
  817. const matchedTokens = [Token.Filter] as const;
  818. return this.findTokensAtCursor(matchedTokens);
  819. }
  820. get cursorValueIsoDate(): TokenResult<Token.ValueIso8601Date> | null {
  821. const matchedTokens = [Token.ValueIso8601Date] as const;
  822. return this.findTokensAtCursor(matchedTokens);
  823. }
  824. get cursorValueRelativeDate() {
  825. const matchedTokens = [Token.ValueRelativeDate] as const;
  826. return this.findTokensAtCursor(matchedTokens);
  827. }
  828. get currentFieldDefinition() {
  829. if (!this.cursorToken || this.cursorToken.type !== Token.Filter) {
  830. return null;
  831. }
  832. const tagName = getKeyName(this.cursorToken.key, {aggregateWithArgs: true});
  833. return this.props.fieldDefinitionGetter(tagName);
  834. }
  835. /**
  836. * Determines when the date picker should be shown instead of normal dropdown options.
  837. * This should return true when the cursor is within a date tag value and the user has
  838. * typed in an operator (or already has a date value).
  839. */
  840. get shouldShowDatePicker() {
  841. if (
  842. !this.state.showDropdown ||
  843. !this.cursorToken ||
  844. this.currentFieldDefinition?.valueType !== FieldValueType.DATE ||
  845. this.cursorValueRelativeDate ||
  846. !(
  847. this.cursorToken.type === Token.Filter &&
  848. isWithinToken(this.cursorToken.value, this.cursorPosition)
  849. )
  850. ) {
  851. return false;
  852. }
  853. const textValue = this.cursorFilter?.value?.text ?? '';
  854. if (
  855. // Cursor is in a valid ISO date value
  856. this.cursorValueIsoDate ||
  857. // Cursor is in a value that has an operator
  858. this.cursorFilter?.operator ||
  859. // Cursor is in raw text value that matches one of the non-empty operators
  860. (textValue && isOperator(textValue))
  861. ) {
  862. return true;
  863. }
  864. return false;
  865. }
  866. get shouldShowAutocomplete() {
  867. return this.state.showDropdown && !this.shouldShowDatePicker;
  868. }
  869. /**
  870. * Get the current cursor position within the input
  871. */
  872. get cursorPosition() {
  873. if (!this.searchInput.current) {
  874. return -1;
  875. }
  876. return this.searchInput.current.selectionStart ?? -1;
  877. }
  878. /**
  879. * Get the search term at the current cursor position
  880. */
  881. get cursorSearchTerm() {
  882. const cursorPosition = this.cursorPosition;
  883. const cursorToken = this.cursorToken;
  884. if (!cursorToken) {
  885. return null;
  886. }
  887. const LIMITER_CHARS = [' ', ':'];
  888. const innerStart = cursorPosition - cursorToken.location.start.offset;
  889. let tokenStart = innerStart;
  890. while (tokenStart > 0 && !LIMITER_CHARS.includes(cursorToken.text[tokenStart - 1])) {
  891. tokenStart--;
  892. }
  893. let tokenEnd = innerStart;
  894. while (
  895. tokenEnd < cursorToken.text.length &&
  896. !LIMITER_CHARS.includes(cursorToken.text[tokenEnd])
  897. ) {
  898. tokenEnd++;
  899. }
  900. let searchTerm = cursorToken.text.slice(tokenStart, tokenEnd);
  901. if (searchTerm.startsWith(NEGATION_OPERATOR)) {
  902. tokenStart++;
  903. }
  904. searchTerm = searchTerm.replace(new RegExp(`^${NEGATION_OPERATOR}`), '');
  905. return {
  906. end: cursorToken.location.start.offset + tokenEnd,
  907. searchTerm,
  908. start: cursorToken.location.start.offset + tokenStart,
  909. };
  910. }
  911. get filterTokens(): TokenResult<Token.Filter>[] {
  912. return (this.state.parsedQuery?.filter(tok => tok.type === Token.Filter) ??
  913. []) as TokenResult<Token.Filter>[];
  914. }
  915. /**
  916. * Finds tokens that exist at the current cursor position
  917. * @param matchedTokens acceptable list of tokens
  918. */
  919. findTokensAtCursor<T extends readonly Token[]>(matchedTokens: T) {
  920. const {parsedQuery} = this.state;
  921. if (parsedQuery === null) {
  922. return null;
  923. }
  924. const cursor = this.cursorPosition;
  925. return treeResultLocator<TokenResult<T[number]> | null>({
  926. tree: parsedQuery,
  927. noResultValue: null,
  928. visitorTest: ({token, returnResult, skipToken}) =>
  929. !matchedTokens.includes(token.type)
  930. ? null
  931. : isWithinToken(token, cursor)
  932. ? returnResult(token)
  933. : skipToken,
  934. });
  935. }
  936. /**
  937. * Returns array of possible key values that substring match `query`
  938. */
  939. getTagKeys(searchTerm: string): [SearchItem[], ItemType] {
  940. const {
  941. excludedTags,
  942. fieldDefinitionGetter,
  943. organization,
  944. prepareQuery,
  945. supportedTags = {},
  946. supportedTagType,
  947. } = this.props;
  948. let tagKeys = Object.keys(supportedTags).sort((a, b) => a.localeCompare(b));
  949. if (searchTerm) {
  950. const preparedSearchTerm = prepareQuery ? prepareQuery(searchTerm) : searchTerm;
  951. tagKeys = filterKeysFromQuery(tagKeys, preparedSearchTerm, fieldDefinitionGetter);
  952. }
  953. // removes any tags that are marked for exclusion
  954. if (excludedTags) {
  955. tagKeys = tagKeys.filter(key => !excludedTags?.includes(key));
  956. }
  957. const allTagItems = getTagItemsFromKeys(
  958. tagKeys,
  959. supportedTags,
  960. fieldDefinitionGetter
  961. );
  962. // Filter out search items that are behind feature flags
  963. const tagItems = allTagItems.filter(
  964. item =>
  965. item.featureFlag === undefined || organization.features.includes(item.featureFlag)
  966. );
  967. return [tagItems, supportedTagType ?? ItemType.TAG_KEY];
  968. }
  969. /**
  970. * Returns array of tag values that substring match `query`; invokes `callback`
  971. * with data when ready
  972. */
  973. getTagValues = debounce(
  974. async (tag: Tag, query: string): Promise<SearchItem[]> => {
  975. // Strip double quotes if there are any
  976. query = query.replace(/"/g, '').trim();
  977. if (!this.props.onGetTagValues) {
  978. return [];
  979. }
  980. if (
  981. this.state.noValueQuery !== undefined &&
  982. query.startsWith(this.state.noValueQuery)
  983. ) {
  984. return [];
  985. }
  986. const {location} = this.props;
  987. const endpointParams = normalizeDateTimeParams(location.query);
  988. this.setState({loading: true});
  989. let values: string[] = [];
  990. try {
  991. values = await this.props.onGetTagValues(tag, query, endpointParams);
  992. this.setState({loading: false});
  993. } catch (err) {
  994. this.setState({loading: false});
  995. Sentry.captureException(err);
  996. return [];
  997. }
  998. if (tag.key === 'release:' && !values.includes('latest')) {
  999. values.unshift('latest');
  1000. }
  1001. const noValueQuery = values.length === 0 && query.length > 0 ? query : undefined;
  1002. this.setState({noValueQuery});
  1003. return values.map(value => {
  1004. const escapedValue = escapeValue(value);
  1005. return {
  1006. value: escapedValue,
  1007. desc: escapedValue,
  1008. type: ItemType.TAG_VALUE,
  1009. };
  1010. });
  1011. },
  1012. DEFAULT_DEBOUNCE_DURATION,
  1013. {leading: true}
  1014. );
  1015. /**
  1016. * Returns array of tag values that substring match `query`; invokes `callback`
  1017. * with results
  1018. */
  1019. getPredefinedTagValues = (tag: Tag, query: string): SearchItem[] =>
  1020. (tag.values ?? [])
  1021. .filter(value => value.indexOf(query) > -1)
  1022. .map((value, i) => {
  1023. const escapedValue = escapeValue(value);
  1024. return {
  1025. value: escapedValue,
  1026. desc: escapedValue,
  1027. type: ItemType.TAG_VALUE,
  1028. ignoreMaxSearchItems: tag.maxSuggestedValues
  1029. ? i < tag.maxSuggestedValues
  1030. : false,
  1031. };
  1032. });
  1033. /**
  1034. * Get recent searches
  1035. */
  1036. getRecentSearches = debounce(
  1037. async () => {
  1038. const {savedSearchType, hasRecentSearches, onGetRecentSearches} = this.props;
  1039. // `savedSearchType` can be 0
  1040. if (!defined(savedSearchType) || !hasRecentSearches) {
  1041. return [];
  1042. }
  1043. const fetchFn = onGetRecentSearches || this.fetchRecentSearches;
  1044. return await fetchFn(this.state.query);
  1045. },
  1046. DEFAULT_DEBOUNCE_DURATION,
  1047. {leading: true}
  1048. );
  1049. fetchRecentSearches = async (fullQuery: string): Promise<SearchItem[]> => {
  1050. const {api, organization, savedSearchType} = this.props;
  1051. if (savedSearchType === undefined) {
  1052. return [];
  1053. }
  1054. try {
  1055. const recentSearches: any[] = await fetchRecentSearches(
  1056. api,
  1057. organization.slug,
  1058. savedSearchType,
  1059. fullQuery
  1060. );
  1061. // If `recentSearches` is undefined or not an array, the function will
  1062. // return an array anyway
  1063. return recentSearches.map(searches => ({
  1064. desc: searches.query,
  1065. value: searches.query,
  1066. type: ItemType.RECENT_SEARCH,
  1067. }));
  1068. } catch (e) {
  1069. Sentry.captureException(e);
  1070. }
  1071. return [];
  1072. };
  1073. getReleases = debounce(
  1074. async (tag: Tag, query: string) => {
  1075. const releasePromise = this.fetchReleases(query);
  1076. const tags = this.getPredefinedTagValues(tag, query);
  1077. const tagValues = tags.map<SearchItem>(v => ({
  1078. ...v,
  1079. type: ItemType.FIRST_RELEASE,
  1080. }));
  1081. const releases = await releasePromise;
  1082. const releaseValues = releases.map<SearchItem>((r: any) => ({
  1083. value: r.shortVersion,
  1084. desc: r.shortVersion,
  1085. type: ItemType.FIRST_RELEASE,
  1086. }));
  1087. return [...tagValues, ...releaseValues];
  1088. },
  1089. DEFAULT_DEBOUNCE_DURATION,
  1090. {leading: true}
  1091. );
  1092. /**
  1093. * Fetches latest releases from a organization/project. Returns an empty array
  1094. * if an error is encountered.
  1095. */
  1096. fetchReleases = async (releaseVersion: string): Promise<any[]> => {
  1097. const {api, location, organization} = this.props;
  1098. const project = location && location.query ? location.query.projectId : undefined;
  1099. const url = `/organizations/${organization.slug}/releases/`;
  1100. const fetchQuery: {[key: string]: string | number} = {
  1101. per_page: MAX_AUTOCOMPLETE_RELEASES,
  1102. };
  1103. if (releaseVersion) {
  1104. fetchQuery.query = releaseVersion;
  1105. }
  1106. if (project) {
  1107. fetchQuery.project = project;
  1108. }
  1109. try {
  1110. return await api.requestPromise(url, {
  1111. method: 'GET',
  1112. query: fetchQuery,
  1113. });
  1114. } catch (e) {
  1115. addErrorMessage(t('Unable to fetch releases'));
  1116. Sentry.captureException(e);
  1117. }
  1118. return [];
  1119. };
  1120. async generateTagAutocompleteGroup(tagName: string): Promise<AutocompleteGroup> {
  1121. const [tagKeys, tagType] = this.getTagKeys(tagName);
  1122. const recentSearches = await this.getRecentSearches();
  1123. return {
  1124. searchItems: tagKeys,
  1125. recentSearchItems: recentSearches ?? [],
  1126. tagName,
  1127. type: tagType,
  1128. };
  1129. }
  1130. generateValueAutocompleteGroup = async (
  1131. tagName: string,
  1132. query: string
  1133. ): Promise<AutocompleteGroup | null> => {
  1134. const {prepareQuery, excludedTags, organization, savedSearchType, searchSource} =
  1135. this.props;
  1136. const supportedTags = this.props.supportedTags ?? {};
  1137. const preparedQuery =
  1138. typeof prepareQuery === 'function' ? prepareQuery(query) : query;
  1139. // filter existing items immediately, until API can return
  1140. // with actual tag value results
  1141. const filteredSearchGroups = !preparedQuery
  1142. ? this.state.searchGroups
  1143. : this.state.searchGroups.filter(
  1144. item => item.value && item.value.indexOf(preparedQuery) !== -1
  1145. );
  1146. this.setState({
  1147. searchTerm: query,
  1148. searchGroups: filteredSearchGroups,
  1149. });
  1150. const tag = supportedTags[tagName];
  1151. if (!tag) {
  1152. trackAdvancedAnalyticsEvent('search.invalid_field', {
  1153. organization,
  1154. search_type: savedSearchType === 0 ? 'issues' : 'events',
  1155. search_source: searchSource,
  1156. attempted_field_name: tagName,
  1157. });
  1158. return {
  1159. searchItems: [
  1160. {
  1161. type: ItemType.INVALID_TAG,
  1162. desc: tagName,
  1163. callback: () =>
  1164. window.open(
  1165. 'https://docs.sentry.io/product/sentry-basics/search/searchable-properties/'
  1166. ),
  1167. },
  1168. ],
  1169. recentSearchItems: [],
  1170. tagName,
  1171. type: ItemType.INVALID_TAG,
  1172. };
  1173. }
  1174. if (excludedTags && excludedTags.includes(tagName)) {
  1175. return null;
  1176. }
  1177. const fetchTagValuesFn =
  1178. tag.key === 'firstRelease'
  1179. ? this.getReleases
  1180. : tag.predefined
  1181. ? this.getPredefinedTagValues
  1182. : this.getTagValues;
  1183. const [tagValues, recentSearches] = await Promise.all([
  1184. fetchTagValuesFn(tag, preparedQuery),
  1185. this.getRecentSearches(),
  1186. ]);
  1187. return {
  1188. searchItems: tagValues ?? [],
  1189. recentSearchItems: recentSearches ?? [],
  1190. tagName: tag.key,
  1191. type: ItemType.TAG_VALUE,
  1192. };
  1193. };
  1194. showDefaultSearches = async () => {
  1195. const {query} = this.state;
  1196. const [defaultSearchItems, defaultRecentItems] = this.props.defaultSearchItems!;
  1197. // Always clear searchTerm on showing default state.
  1198. this.setState({searchTerm: ''});
  1199. if (!defaultSearchItems.length) {
  1200. // Update searchTerm, otherwise <SearchDropdown> will have wrong state
  1201. // (e.g. if you delete a query, the last letter will be highlighted if `searchTerm`
  1202. // does not get updated)
  1203. const [tagKeys, tagType] = this.getTagKeys('');
  1204. const recentSearches = await this.getRecentSearches();
  1205. if (this.state.query === query) {
  1206. this.updateAutoCompleteState(tagKeys, recentSearches ?? [], '', tagType);
  1207. }
  1208. return;
  1209. }
  1210. this.updateAutoCompleteState(
  1211. defaultSearchItems,
  1212. defaultRecentItems,
  1213. '',
  1214. ItemType.DEFAULT
  1215. );
  1216. return;
  1217. };
  1218. updateAutoCompleteFromAst = async () => {
  1219. const cursor = this.cursorPosition;
  1220. const cursorToken = this.cursorToken;
  1221. if (!cursorToken) {
  1222. this.showDefaultSearches();
  1223. return;
  1224. }
  1225. if (cursorToken.type === Token.Filter) {
  1226. const tagName = getKeyName(cursorToken.key, {aggregateWithArgs: true});
  1227. // check if we are on the tag, value, or operator
  1228. if (isWithinToken(cursorToken.value, cursor)) {
  1229. const node = cursorToken.value;
  1230. const cursorValue = this.cursorValue;
  1231. let searchText = cursorValue?.text ?? node.text;
  1232. if (searchText === '[]' || cursorValue === null) {
  1233. searchText = '';
  1234. }
  1235. const fieldDefinition = this.props.fieldDefinitionGetter(tagName);
  1236. const isDate = fieldDefinition?.valueType === FieldValueType.DATE;
  1237. if (isDate) {
  1238. const groups = getDateTagAutocompleteGroups(tagName);
  1239. this.updateAutoCompleteStateMultiHeader(groups);
  1240. return;
  1241. }
  1242. const valueGroup = await this.generateValueAutocompleteGroup(tagName, searchText);
  1243. const autocompleteGroups = valueGroup ? [valueGroup] : [];
  1244. // show operator group if at beginning of value
  1245. if (cursor === node.location.start.offset) {
  1246. const opGroup = generateOpAutocompleteGroup(getValidOps(cursorToken), tagName);
  1247. if (valueGroup?.type !== ItemType.INVALID_TAG && !isDate) {
  1248. autocompleteGroups.unshift(opGroup);
  1249. }
  1250. }
  1251. if (cursor === this.cursorPosition) {
  1252. this.updateAutoCompleteStateMultiHeader(autocompleteGroups);
  1253. }
  1254. return;
  1255. }
  1256. if (isWithinToken(cursorToken.key, cursor)) {
  1257. const node = cursorToken.key;
  1258. const autocompleteGroups = [await this.generateTagAutocompleteGroup(tagName)];
  1259. // show operator group if at end of key
  1260. if (cursor === node.location.end.offset) {
  1261. const opGroup = generateOpAutocompleteGroup(getValidOps(cursorToken), tagName);
  1262. autocompleteGroups.unshift(opGroup);
  1263. }
  1264. if (cursor === this.cursorPosition) {
  1265. this.setState({
  1266. searchTerm: tagName,
  1267. });
  1268. this.updateAutoCompleteStateMultiHeader(autocompleteGroups);
  1269. }
  1270. return;
  1271. }
  1272. // show operator autocomplete group
  1273. const opGroup = generateOpAutocompleteGroup(getValidOps(cursorToken), tagName);
  1274. this.updateAutoCompleteStateMultiHeader([opGroup]);
  1275. return;
  1276. }
  1277. const cursorSearchTerm = this.cursorSearchTerm;
  1278. if (cursorToken.type === Token.FreeText && cursorSearchTerm) {
  1279. const autocompleteGroups = [
  1280. await this.generateTagAutocompleteGroup(cursorSearchTerm.searchTerm),
  1281. ];
  1282. if (cursor === this.cursorPosition) {
  1283. this.setState({
  1284. searchTerm: cursorSearchTerm.searchTerm,
  1285. });
  1286. this.updateAutoCompleteStateMultiHeader(autocompleteGroups);
  1287. }
  1288. return;
  1289. }
  1290. };
  1291. updateAutoCompleteItems = () => {
  1292. this.updateAutoCompleteFromAst();
  1293. };
  1294. /**
  1295. * Updates autocomplete dropdown items and autocomplete index state
  1296. *
  1297. * @param searchItems List of search item objects with keys: title, desc, value
  1298. * @param recentSearchItems List of recent search items, same format as searchItem
  1299. * @param tagName The current tag name in scope
  1300. * @param type Defines the type/state of the dropdown menu items
  1301. */
  1302. updateAutoCompleteState(
  1303. searchItems: SearchItem[],
  1304. recentSearchItems: SearchItem[],
  1305. tagName: string,
  1306. type: ItemType
  1307. ) {
  1308. const {fieldDefinitionGetter, hasRecentSearches, maxSearchItems, maxQueryLength} =
  1309. this.props;
  1310. const {query} = this.state;
  1311. const queryCharsLeft =
  1312. maxQueryLength && query ? maxQueryLength - query.length : undefined;
  1313. const searchGroups = createSearchGroups(
  1314. searchItems,
  1315. hasRecentSearches ? recentSearchItems : undefined,
  1316. tagName,
  1317. type,
  1318. maxSearchItems,
  1319. queryCharsLeft,
  1320. true,
  1321. fieldDefinitionGetter
  1322. );
  1323. this.setState(searchGroups);
  1324. }
  1325. /**
  1326. * Updates autocomplete dropdown items and autocomplete index state
  1327. *
  1328. * @param groups Groups that will be used to populate the autocomplete dropdown
  1329. */
  1330. updateAutoCompleteStateMultiHeader = (groups: AutocompleteGroup[]) => {
  1331. const {fieldDefinitionGetter, hasRecentSearches, maxSearchItems, maxQueryLength} =
  1332. this.props;
  1333. const {query} = this.state;
  1334. const queryCharsLeft =
  1335. maxQueryLength && query ? maxQueryLength - query.length : undefined;
  1336. const searchGroups = groups
  1337. .map(({searchItems, recentSearchItems, tagName, type}) =>
  1338. createSearchGroups(
  1339. searchItems,
  1340. hasRecentSearches ? recentSearchItems : undefined,
  1341. tagName,
  1342. type,
  1343. maxSearchItems,
  1344. queryCharsLeft,
  1345. false,
  1346. fieldDefinitionGetter
  1347. )
  1348. )
  1349. .reduce(
  1350. (acc, item) => ({
  1351. searchGroups: [...acc.searchGroups, ...item.searchGroups],
  1352. flatSearchItems: [...acc.flatSearchItems, ...item.flatSearchItems],
  1353. activeSearchItem: -1,
  1354. }),
  1355. {
  1356. searchGroups: [] as SearchGroup[],
  1357. flatSearchItems: [] as SearchItem[],
  1358. activeSearchItem: -1,
  1359. }
  1360. );
  1361. this.setState(searchGroups);
  1362. };
  1363. updateQuery = (newQuery: string, cursorPosition?: number) =>
  1364. this.setState(this.makeQueryState(newQuery), () => {
  1365. // setting a new input value will lose focus; restore it
  1366. if (this.searchInput.current) {
  1367. this.searchInput.current.focus();
  1368. if (cursorPosition) {
  1369. this.searchInput.current.selectionStart = cursorPosition;
  1370. this.searchInput.current.selectionEnd = cursorPosition;
  1371. }
  1372. }
  1373. // then update the autocomplete box with new items
  1374. this.updateAutoCompleteItems();
  1375. this.props.onChange?.(newQuery, new MouseEvent('click') as any);
  1376. });
  1377. onAutoCompleteFromAst = (replaceText: string, item: SearchItem) => {
  1378. const cursor = this.cursorPosition;
  1379. const {query} = this.state;
  1380. const cursorToken = this.cursorToken;
  1381. if (!cursorToken) {
  1382. this.updateQuery(`${query}${replaceText}`);
  1383. return;
  1384. }
  1385. // the start and end of what to replace
  1386. let clauseStart: null | number = null;
  1387. let clauseEnd: null | number = null;
  1388. // the new text that will exist between clauseStart and clauseEnd
  1389. let replaceToken = replaceText;
  1390. if (cursorToken.type === Token.Filter) {
  1391. if (item.type === ItemType.TAG_OPERATOR) {
  1392. trackAdvancedAnalyticsEvent('search.operator_autocompleted', {
  1393. organization: this.props.organization,
  1394. query: removeSpace(query),
  1395. search_operator: replaceText,
  1396. search_type: this.props.savedSearchType === 0 ? 'issues' : 'events',
  1397. });
  1398. const valueLocation = cursorToken.value.location;
  1399. clauseStart = cursorToken.location.start.offset;
  1400. clauseEnd = valueLocation.start.offset;
  1401. if (replaceText === '!:') {
  1402. replaceToken = `!${cursorToken.key.text}:`;
  1403. } else {
  1404. replaceToken = `${cursorToken.key.text}${replaceText}`;
  1405. }
  1406. } else if (isWithinToken(cursorToken.value, cursor)) {
  1407. const valueToken = this.cursorValue ?? cursorToken.value;
  1408. const location = valueToken.location;
  1409. if (cursorToken.filter === FilterType.TextIn) {
  1410. // Current value can be null when adding a 2nd value
  1411. // ▼ cursor
  1412. // key:[value1, ]
  1413. const currentValueNull = this.cursorValue === null;
  1414. clauseStart = currentValueNull
  1415. ? this.cursorPosition
  1416. : valueToken.location.start.offset;
  1417. clauseEnd = currentValueNull
  1418. ? this.cursorPosition
  1419. : valueToken.location.end.offset;
  1420. } else {
  1421. const keyLocation = cursorToken.key.location;
  1422. clauseStart = keyLocation.end.offset + 1;
  1423. clauseEnd = location.end.offset + 1;
  1424. // The user tag often contains : within its value and we need to quote it.
  1425. if (getKeyName(cursorToken.key) === 'user') {
  1426. replaceToken = `"${replaceText.trim()}"`;
  1427. }
  1428. // handle using autocomplete with key:[]
  1429. if (valueToken.text === '[]') {
  1430. clauseStart += 1;
  1431. clauseEnd -= 2;
  1432. // For ISO date values, we want to keep the cursor within the token
  1433. } else if (item.type !== ItemType.TAG_VALUE_ISO_DATE) {
  1434. replaceToken += ' ';
  1435. }
  1436. }
  1437. } else if (isWithinToken(cursorToken.key, cursor)) {
  1438. const location = cursorToken.key.location;
  1439. clauseStart = location.start.offset;
  1440. // If the token is a key, then trim off the end to avoid duplicate ':'
  1441. clauseEnd = location.end.offset + 1;
  1442. }
  1443. }
  1444. const cursorSearchTerm = this.cursorSearchTerm;
  1445. if (cursorToken.type === Token.FreeText && cursorSearchTerm) {
  1446. clauseStart = cursorSearchTerm.start;
  1447. clauseEnd = cursorSearchTerm.end;
  1448. }
  1449. if (clauseStart !== null && clauseEnd !== null) {
  1450. const beforeClause = query.substring(0, clauseStart);
  1451. const endClause = query.substring(clauseEnd);
  1452. // Adds a space between the replaceToken and endClause when necessary
  1453. const replaceTokenEndClauseJoiner =
  1454. !endClause ||
  1455. endClause.startsWith(' ') ||
  1456. replaceToken.endsWith(' ') ||
  1457. replaceToken.endsWith(':')
  1458. ? ''
  1459. : ' ';
  1460. const newQuery = `${beforeClause}${replaceToken}${replaceTokenEndClauseJoiner}${endClause}`;
  1461. this.updateQuery(newQuery, beforeClause.length + replaceToken.length);
  1462. }
  1463. };
  1464. onAutoComplete = (replaceText: string, item: SearchItem) => {
  1465. if (item.type === ItemType.RECENT_SEARCH) {
  1466. trackAdvancedAnalyticsEvent('search.searched', {
  1467. organization: this.props.organization,
  1468. query: replaceText,
  1469. search_type: this.props.savedSearchType === 0 ? 'issues' : 'events',
  1470. search_source: 'recent_search',
  1471. });
  1472. this.setState(this.makeQueryState(replaceText), () => {
  1473. // Propagate onSearch and save to recent searches
  1474. this.doSearch();
  1475. });
  1476. return;
  1477. }
  1478. this.onAutoCompleteFromAst(replaceText, item);
  1479. };
  1480. onAutoCompleteIsoDate = (isoDate: string) => {
  1481. const dateItem = {type: ItemType.TAG_VALUE_ISO_DATE};
  1482. if (
  1483. this.cursorFilter?.filter === FilterType.Date ||
  1484. this.cursorFilter?.filter === FilterType.SpecificDate
  1485. ) {
  1486. this.onAutoCompleteFromAst(`${this.cursorFilter.operator}${isoDate}`, dateItem);
  1487. } else if (this.cursorFilter?.filter === FilterType.Text) {
  1488. const valueText = this.cursorFilter.value.text;
  1489. if (valueText && isOperator(valueText)) {
  1490. this.onAutoCompleteFromAst(`${valueText}${isoDate}`, dateItem);
  1491. }
  1492. }
  1493. };
  1494. get showSearchDropdown(): boolean {
  1495. return this.state.loading || this.state.searchGroups.length > 0;
  1496. }
  1497. render() {
  1498. const {
  1499. api,
  1500. className,
  1501. savedSearchType,
  1502. dropdownClassName,
  1503. actionBarItems,
  1504. organization,
  1505. placeholder,
  1506. disabled,
  1507. useFormWrapper,
  1508. inlineLabel,
  1509. maxQueryLength,
  1510. maxMenuHeight,
  1511. customPerformanceMetrics,
  1512. supportedTags,
  1513. } = this.props;
  1514. const {
  1515. query,
  1516. parsedQuery,
  1517. searchGroups,
  1518. searchTerm,
  1519. inputHasFocus,
  1520. numActionsVisible,
  1521. loading,
  1522. } = this.state;
  1523. const input = (
  1524. <SearchInput
  1525. type="text"
  1526. placeholder={placeholder}
  1527. id="smart-search-input"
  1528. data-test-id="smart-search-input"
  1529. name="query"
  1530. ref={this.searchInput}
  1531. autoComplete="off"
  1532. value={query}
  1533. onFocus={this.onQueryFocus}
  1534. onBlur={this.onQueryBlur}
  1535. onKeyUp={this.onKeyUp}
  1536. onKeyDown={this.onKeyDown}
  1537. onChange={this.onQueryChange}
  1538. onClick={this.onInputClick}
  1539. onPaste={this.onPaste}
  1540. disabled={disabled}
  1541. maxLength={maxQueryLength}
  1542. spellCheck={false}
  1543. />
  1544. );
  1545. // Segment actions into visible and overflowed groups
  1546. const actionItems = actionBarItems ?? [];
  1547. const actionProps = {
  1548. api,
  1549. organization,
  1550. query,
  1551. savedSearchType,
  1552. };
  1553. const visibleActions = actionItems
  1554. .slice(0, numActionsVisible)
  1555. .map(({key, makeAction}) => {
  1556. const ActionBarButton = makeAction(actionProps).Button;
  1557. return <ActionBarButton key={key} />;
  1558. });
  1559. const overflowedActions = actionItems
  1560. .slice(numActionsVisible)
  1561. .map(({makeAction}) => makeAction(actionProps).menuItem);
  1562. const cursor = this.cursorPosition;
  1563. const visibleShortcuts = shortcuts.filter(
  1564. shortcut =>
  1565. shortcut.hotkeys &&
  1566. shortcut.canRunShortcut(this.cursorToken, this.filterTokens.length)
  1567. );
  1568. return (
  1569. <Container
  1570. ref={this.containerRef}
  1571. className={className}
  1572. inputHasFocus={inputHasFocus}
  1573. data-test-id="smart-search-bar"
  1574. >
  1575. <SearchHotkeysListener
  1576. visibleShortcuts={visibleShortcuts}
  1577. runShortcut={this.runShortcutOnHotkeyPress}
  1578. />
  1579. <SearchLabel htmlFor="smart-search-input" aria-label={t('Search events')}>
  1580. <IconSearch />
  1581. {inlineLabel}
  1582. </SearchLabel>
  1583. <InputWrapper>
  1584. <Highlight>
  1585. {parsedQuery !== null ? (
  1586. <HighlightQuery
  1587. parsedQuery={parsedQuery}
  1588. cursorPosition={this.state.showDropdown ? cursor : -1}
  1589. />
  1590. ) : (
  1591. query
  1592. )}
  1593. </Highlight>
  1594. {useFormWrapper ? <form onSubmit={this.onSubmit}>{input}</form> : input}
  1595. </InputWrapper>
  1596. <ActionsBar gap={0.5}>
  1597. {query !== '' && (
  1598. <ActionButton
  1599. onClick={this.clearSearch}
  1600. icon={<IconClose size="xs" />}
  1601. title={t('Clear search')}
  1602. aria-label={t('Clear search')}
  1603. />
  1604. )}
  1605. {visibleActions}
  1606. {overflowedActions.length > 0 && (
  1607. <OverlowingActionsMenu
  1608. position="bottom-end"
  1609. trigger={props => (
  1610. <ActionButton
  1611. {...props}
  1612. aria-label={t('Show more')}
  1613. icon={<VerticalEllipsisIcon size="xs" />}
  1614. />
  1615. )}
  1616. triggerLabel={t('Show more')}
  1617. items={overflowedActions}
  1618. size="sm"
  1619. />
  1620. )}
  1621. </ActionsBar>
  1622. {this.shouldShowDatePicker && (
  1623. <SearchBarDatePicker
  1624. date={this.cursorValueIsoDate?.value}
  1625. dateString={this.cursorValueIsoDate?.text}
  1626. handleSelectDateTime={value => {
  1627. this.onAutoCompleteIsoDate(value);
  1628. }}
  1629. />
  1630. )}
  1631. {this.shouldShowAutocomplete && (
  1632. <SearchDropdown
  1633. className={dropdownClassName}
  1634. items={searchGroups}
  1635. onClick={this.onAutoComplete}
  1636. loading={loading}
  1637. searchSubstring={searchTerm}
  1638. runShortcut={this.runShortcutOnClick}
  1639. visibleShortcuts={visibleShortcuts}
  1640. maxMenuHeight={maxMenuHeight}
  1641. customPerformanceMetrics={customPerformanceMetrics}
  1642. supportedTags={supportedTags}
  1643. />
  1644. )}
  1645. </Container>
  1646. );
  1647. }
  1648. }
  1649. type ContainerState = {
  1650. members: ReturnType<typeof MemberListStore.getAll>;
  1651. };
  1652. class SmartSearchBarContainer extends Component<Props, ContainerState> {
  1653. state: ContainerState = {
  1654. members: MemberListStore.getAll(),
  1655. };
  1656. componentWillUnmount() {
  1657. this.unsubscribe();
  1658. }
  1659. unsubscribe = MemberListStore.listen(
  1660. (members: ContainerState['members']) => this.setState({members}),
  1661. undefined
  1662. );
  1663. render() {
  1664. // SmartSearchBar doesn't use members, but we forward it to cause a re-render.
  1665. return <SmartSearchBar {...this.props} members={this.state.members} />;
  1666. }
  1667. }
  1668. export default withApi(withRouter(withOrganization(SmartSearchBarContainer)));
  1669. export {SmartSearchBar, Props as SmartSearchBarProps};
  1670. const Container = styled('div')<{inputHasFocus: boolean}>`
  1671. min-height: ${p => p.theme.form.md.height}px;
  1672. border: 1px solid ${p => p.theme.border};
  1673. box-shadow: inset ${p => p.theme.dropShadowLight};
  1674. background: ${p => p.theme.background};
  1675. padding: 6px ${space(1)};
  1676. position: relative;
  1677. display: grid;
  1678. grid-template-columns: max-content 1fr max-content;
  1679. gap: ${space(1)};
  1680. align-items: start;
  1681. border-radius: ${p => p.theme.borderRadius};
  1682. .show-sidebar & {
  1683. background: ${p => p.theme.backgroundSecondary};
  1684. }
  1685. ${p =>
  1686. p.inputHasFocus &&
  1687. `
  1688. border-color: ${p.theme.focusBorder};
  1689. box-shadow: 0 0 0 1px ${p.theme.focusBorder};
  1690. `}
  1691. `;
  1692. const SearchLabel = styled('label')`
  1693. display: flex;
  1694. padding: ${space(0.5)} 0;
  1695. margin: 0;
  1696. color: ${p => p.theme.gray300};
  1697. `;
  1698. const InputWrapper = styled('div')`
  1699. position: relative;
  1700. `;
  1701. const Highlight = styled('div')`
  1702. position: absolute;
  1703. top: 0;
  1704. left: 0;
  1705. right: 0;
  1706. bottom: 0;
  1707. user-select: none;
  1708. white-space: pre-wrap;
  1709. word-break: break-word;
  1710. line-height: 25px;
  1711. font-size: ${p => p.theme.fontSizeSmall};
  1712. font-family: ${p => p.theme.text.familyMono};
  1713. `;
  1714. const SearchInput = styled(
  1715. getDynamicComponent<typeof TextareaAutosize>({
  1716. value: TextareaAutosize,
  1717. fixed: 'textarea',
  1718. }),
  1719. {
  1720. shouldForwardProp: prop => typeof prop === 'string' && isPropValid(prop),
  1721. }
  1722. )`
  1723. position: relative;
  1724. display: flex;
  1725. resize: none;
  1726. outline: none;
  1727. border: 0;
  1728. width: 100%;
  1729. padding: 0;
  1730. line-height: 25px;
  1731. margin-bottom: -1px;
  1732. background: transparent;
  1733. font-size: ${p => p.theme.fontSizeSmall};
  1734. font-family: ${p => p.theme.text.familyMono};
  1735. caret-color: ${p => p.theme.subText};
  1736. color: transparent;
  1737. &::selection {
  1738. background: rgba(0, 0, 0, 0.2);
  1739. }
  1740. &::placeholder {
  1741. color: ${p => p.theme.formPlaceholder};
  1742. }
  1743. [disabled] {
  1744. color: ${p => p.theme.disabled};
  1745. }
  1746. `;
  1747. const ActionsBar = styled(ButtonBar)`
  1748. height: 100%;
  1749. `;
  1750. const VerticalEllipsisIcon = styled(IconEllipsis)`
  1751. transform: rotate(90deg);
  1752. `;
  1753. const OverlowingActionsMenu = styled(DropdownMenuControl)`
  1754. display: flex;
  1755. `;