index.tsx 51 KB

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