index.tsx 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. import * as React from 'react';
  2. import TextareaAutosize from 'react-autosize-textarea';
  3. import {withRouter, WithRouterProps} from 'react-router';
  4. import isPropValid from '@emotion/is-prop-valid';
  5. import styled from '@emotion/styled';
  6. import * as Sentry from '@sentry/react';
  7. import debounce from 'lodash/debounce';
  8. import {addErrorMessage} from 'app/actionCreators/indicator';
  9. import {fetchRecentSearches, saveRecentSearch} from 'app/actionCreators/savedSearches';
  10. import {Client} from 'app/api';
  11. import ButtonBar from 'app/components/buttonBar';
  12. import DropdownLink from 'app/components/dropdownLink';
  13. import {getParams} from 'app/components/organizations/globalSelectionHeader/getParams';
  14. import renderQuery from 'app/components/searchSyntax/renderer';
  15. import {
  16. DEFAULT_DEBOUNCE_DURATION,
  17. MAX_AUTOCOMPLETE_RELEASES,
  18. NEGATION_OPERATOR,
  19. } from 'app/constants';
  20. import {IconClose, IconEllipsis, IconSearch} from 'app/icons';
  21. import {t} from 'app/locale';
  22. import MemberListStore from 'app/stores/memberListStore';
  23. import space from 'app/styles/space';
  24. import {LightWeightOrganization, SavedSearchType, Tag, User} from 'app/types';
  25. import {defined} from 'app/utils';
  26. import {trackAnalyticsEvent} from 'app/utils/analytics';
  27. import {callIfFunction} from 'app/utils/callIfFunction';
  28. import withApi from 'app/utils/withApi';
  29. import withOrganization from 'app/utils/withOrganization';
  30. import {ActionButton} from './actions';
  31. import SearchDropdown from './searchDropdown';
  32. import {ItemType, SearchGroup, SearchItem} from './types';
  33. import {
  34. addSpace,
  35. createSearchGroups,
  36. filterSearchGroupsByIndex,
  37. getLastTermIndex,
  38. getQueryTerms,
  39. removeSpace,
  40. } from './utils';
  41. const DROPDOWN_BLUR_DURATION = 200;
  42. /**
  43. * The max width in pixels of the search bar at which the buttons will
  44. * have overflowed into the dropdown.
  45. */
  46. const ACTION_OVERFLOW_WIDTH = 400;
  47. /**
  48. * Actions are moved to the overflow dropdown after each pixel step is reached.
  49. */
  50. const ACTION_OVERFLOW_STEPS = 75;
  51. /**
  52. * Is the SearchItem a default item
  53. */
  54. const isDefaultDropdownItem = (item: SearchItem) => item?.type === 'default';
  55. type ActionProps = {
  56. api: Client;
  57. /**
  58. * Render the actions as a menu item
  59. */
  60. menuItemVariant?: boolean;
  61. /**
  62. * The current query
  63. */
  64. query: string;
  65. /**
  66. * The organization
  67. */
  68. organization: LightWeightOrganization;
  69. /**
  70. * The saved search type passed to the search bar
  71. */
  72. savedSearchType?: SavedSearchType;
  73. };
  74. type ActionBarItem = {
  75. /**
  76. * Name of the action
  77. */
  78. key: string;
  79. /**
  80. * The action component to render
  81. */
  82. Action: React.ComponentType<ActionProps>;
  83. };
  84. type Props = WithRouterProps & {
  85. api: Client;
  86. organization: LightWeightOrganization;
  87. dropdownClassName?: string;
  88. className?: string;
  89. defaultQuery?: string;
  90. query?: string | null;
  91. /**
  92. * Additional components to render as actions on the right of the search bar
  93. */
  94. actionBarItems?: ActionBarItem[];
  95. /**
  96. * Prepare query value before filtering dropdown items
  97. */
  98. prepareQuery?: (query: string) => string;
  99. /**
  100. * Search items to display when there's no tag key. Is a tuple of search
  101. * items and recent search items
  102. */
  103. defaultSearchItems?: [SearchItem[], SearchItem[]];
  104. /**
  105. * Disabled control (e.g. read-only)
  106. */
  107. disabled?: boolean;
  108. /**
  109. * Input placeholder
  110. */
  111. placeholder?: string;
  112. /**
  113. * Allows additional content to be played before the search bar and icon
  114. */
  115. inlineLabel?: React.ReactNode;
  116. /**
  117. * Map of tags
  118. */
  119. supportedTags?: {[key: string]: Tag};
  120. /**
  121. * Maximum number of search items to display or a falsey value for no
  122. * maximum
  123. */
  124. maxSearchItems?: number;
  125. /**
  126. * List user's recent searches
  127. */
  128. hasRecentSearches?: boolean;
  129. /**
  130. * Wrap the input with a form. Useful if search bar is used within a parent
  131. * form
  132. */
  133. useFormWrapper?: boolean;
  134. /**
  135. * If this is defined, attempt to save search term scoped to the user and
  136. * the current org
  137. */
  138. savedSearchType?: SavedSearchType;
  139. /**
  140. * Get a list of tag values for the passed tag
  141. */
  142. onGetTagValues?: (tag: Tag, query: string, params: object) => Promise<string[]>;
  143. /**
  144. * Get a list of recent searches for the current query
  145. */
  146. onGetRecentSearches?: (query: string) => Promise<SearchItem[]>;
  147. /**
  148. * Called when the user makes a search
  149. */
  150. onSearch?: (query: string) => void;
  151. /**
  152. * Called when the search input changes
  153. */
  154. onChange?: (value: string, e: React.ChangeEvent) => void;
  155. /**
  156. * Called when the search is blurred
  157. */
  158. onBlur?: (value: string) => void;
  159. /**
  160. * Called on key down
  161. */
  162. onKeyDown?: (evt: React.KeyboardEvent<HTMLTextAreaElement>) => void;
  163. /**
  164. * Called when a recent search is saved
  165. */
  166. onSavedRecentSearch?: (query: string) => void;
  167. /**
  168. * If true, excludes the environment tag from the autocompletion list. This
  169. * is because we don't want to treat environment as a tag in some places such
  170. * as the stream view where it is a top level concept
  171. */
  172. excludeEnvironment?: boolean;
  173. /**
  174. * Used to enforce length on the query
  175. */
  176. maxQueryLength?: number;
  177. /**
  178. * While the data is unused, this list of members can be updated to
  179. * trigger re-renders.
  180. */
  181. members?: User[];
  182. };
  183. type State = {
  184. /**
  185. * The current search query in the input
  186. */
  187. query: string;
  188. /**
  189. * The query in the input since we last updated our autocomplete list.
  190. */
  191. previousQuery?: string;
  192. /**
  193. * Indicates that we have a query that we've already determined not to have
  194. * any values. This is used to stop the autocompleter from querying if we
  195. * know we will find nothing.
  196. */
  197. noValueQuery?: string;
  198. /**
  199. * The current search term (or 'key') that that we will be showing
  200. * autocompletion for.
  201. */
  202. searchTerm: string;
  203. searchGroups: SearchGroup[];
  204. flatSearchItems: SearchItem[];
  205. /**
  206. * Index of the focused search item
  207. */
  208. activeSearchItem: number;
  209. tags: Record<string, string>;
  210. dropdownVisible: boolean;
  211. loading: boolean;
  212. /**
  213. * The number of actions that are not in the overflow menu.
  214. */
  215. numActionsVisible: number;
  216. };
  217. class SmartSearchBar extends React.Component<Props, State> {
  218. static defaultProps = {
  219. defaultQuery: '',
  220. query: null,
  221. onSearch: function () {},
  222. excludeEnvironment: false,
  223. placeholder: t('Search for events, users, tags, and more'),
  224. supportedTags: {},
  225. defaultSearchItems: [[], []],
  226. useFormWrapper: true,
  227. savedSearchType: SavedSearchType.ISSUE,
  228. };
  229. state: State = {
  230. query:
  231. this.props.query !== null
  232. ? addSpace(this.props.query)
  233. : this.props.defaultQuery ?? '',
  234. searchTerm: '',
  235. searchGroups: [],
  236. flatSearchItems: [],
  237. activeSearchItem: -1,
  238. tags: {},
  239. dropdownVisible: false,
  240. loading: false,
  241. numActionsVisible: this.props.actionBarItems?.length ?? 0,
  242. };
  243. componentDidMount() {
  244. if (!window.ResizeObserver) {
  245. return;
  246. }
  247. if (this.containerRef.current === null) {
  248. return;
  249. }
  250. this.inputResizeObserver = new ResizeObserver(this.updateActionsVisible);
  251. this.inputResizeObserver.observe(this.containerRef.current);
  252. }
  253. componentDidUpdate(prevProps: Props) {
  254. const {query} = this.props;
  255. const {query: lastQuery} = prevProps;
  256. if (query !== lastQuery && defined(query)) {
  257. // eslint-disable-next-line react/no-did-update-set-state
  258. this.setState({query: addSpace(query)});
  259. }
  260. }
  261. componentWillUnmount() {
  262. this.inputResizeObserver?.disconnect();
  263. if (this.blurTimeout) {
  264. clearTimeout(this.blurTimeout);
  265. }
  266. }
  267. /**
  268. * Tracks the dropdown blur
  269. */
  270. blurTimeout?: number;
  271. /**
  272. * Ref to the search element itself
  273. */
  274. searchInput = React.createRef<HTMLTextAreaElement>();
  275. /**
  276. * Ref to the search container
  277. */
  278. containerRef = React.createRef<HTMLDivElement>();
  279. /**
  280. * Used to determine when actions should be moved to the action overflow menu
  281. */
  282. inputResizeObserver: ResizeObserver | null = null;
  283. /**
  284. * Updates the numActionsVisible count as the search bar is resized
  285. */
  286. updateActionsVisible = (entries: ResizeObserverEntry[]) => {
  287. if (entries.length === 0) {
  288. return;
  289. }
  290. const entry = entries[0];
  291. const {width} = entry.contentRect;
  292. const actionCount = this.props.actionBarItems?.length ?? 0;
  293. const numActionsVisible = Math.min(
  294. actionCount,
  295. Math.floor(Math.max(0, width - ACTION_OVERFLOW_WIDTH) / ACTION_OVERFLOW_STEPS)
  296. );
  297. if (this.state.numActionsVisible === numActionsVisible) {
  298. return;
  299. }
  300. this.setState({numActionsVisible});
  301. };
  302. blur() {
  303. if (!this.searchInput.current) {
  304. return;
  305. }
  306. this.searchInput.current.blur();
  307. }
  308. async doSearch() {
  309. const {onSearch, onSavedRecentSearch, api, organization, savedSearchType} =
  310. this.props;
  311. this.blur();
  312. const query = removeSpace(this.state.query);
  313. callIfFunction(onSearch, query);
  314. // Only save recent search query if we have a savedSearchType (also 0 is a valid value)
  315. // Do not save empty string queries (i.e. if they clear search)
  316. if (typeof savedSearchType === 'undefined' || !query) {
  317. return;
  318. }
  319. try {
  320. await saveRecentSearch(api, organization.slug, savedSearchType, query);
  321. if (onSavedRecentSearch) {
  322. onSavedRecentSearch(query);
  323. }
  324. } catch (err) {
  325. // Silently capture errors if it fails to save
  326. Sentry.captureException(err);
  327. }
  328. }
  329. onSubmit = (evt: React.FormEvent) => {
  330. const {organization, savedSearchType} = this.props;
  331. evt.preventDefault();
  332. trackAnalyticsEvent({
  333. eventKey: 'search.searched',
  334. eventName: 'Search: Performed search',
  335. organization_id: organization.id,
  336. query: removeSpace(this.state.query),
  337. search_type: savedSearchType === 0 ? 'issues' : 'events',
  338. search_source: 'main_search',
  339. });
  340. this.doSearch();
  341. };
  342. clearSearch = () =>
  343. this.setState({query: ''}, () =>
  344. callIfFunction(this.props.onSearch, this.state.query)
  345. );
  346. onQueryFocus = () => this.setState({dropdownVisible: true});
  347. onQueryBlur = (e: React.FocusEvent<HTMLTextAreaElement>) => {
  348. // wait before closing dropdown in case blur was a result of clicking a
  349. // menu option
  350. const value = e.target.value;
  351. const blurHandler = () => {
  352. this.blurTimeout = undefined;
  353. this.setState({dropdownVisible: false});
  354. callIfFunction(this.props.onBlur, value);
  355. };
  356. this.blurTimeout = window.setTimeout(blurHandler, DROPDOWN_BLUR_DURATION);
  357. };
  358. onQueryChange = (evt: React.ChangeEvent<HTMLTextAreaElement>) => {
  359. const query = evt.target.value.replace('\n', '');
  360. this.setState({query}, this.updateAutoCompleteItems);
  361. callIfFunction(this.props.onChange, evt.target.value, evt);
  362. };
  363. onInputClick = () => this.updateAutoCompleteItems();
  364. /**
  365. * Handle keyboard navigation
  366. */
  367. onKeyDown = (evt: React.KeyboardEvent<HTMLTextAreaElement>) => {
  368. const {onKeyDown} = this.props;
  369. const {key} = evt;
  370. callIfFunction(onKeyDown, evt);
  371. if (!this.state.searchGroups.length) {
  372. return;
  373. }
  374. const isSelectingDropdownItems = this.state.activeSearchItem !== -1;
  375. if (key === 'ArrowDown' || key === 'ArrowUp') {
  376. evt.preventDefault();
  377. const {flatSearchItems, activeSearchItem} = this.state;
  378. const searchGroups = [...this.state.searchGroups];
  379. const [groupIndex, childrenIndex] = isSelectingDropdownItems
  380. ? filterSearchGroupsByIndex(searchGroups, activeSearchItem)
  381. : [];
  382. // Remove the previous 'active' property
  383. if (typeof groupIndex !== 'undefined') {
  384. if (
  385. childrenIndex !== undefined &&
  386. searchGroups[groupIndex]?.children?.[childrenIndex]
  387. ) {
  388. delete searchGroups[groupIndex].children[childrenIndex].active;
  389. }
  390. }
  391. const currIndex = isSelectingDropdownItems ? activeSearchItem : 0;
  392. const totalItems = flatSearchItems.length;
  393. // Move the selected index up/down
  394. const nextActiveSearchItem =
  395. key === 'ArrowUp'
  396. ? (currIndex - 1 + totalItems) % totalItems
  397. : isSelectingDropdownItems
  398. ? (currIndex + 1) % totalItems
  399. : 0;
  400. const [nextGroupIndex, nextChildrenIndex] = filterSearchGroupsByIndex(
  401. searchGroups,
  402. nextActiveSearchItem
  403. );
  404. // Make sure search items exist (e.g. both groups could be empty) and
  405. // attach the 'active' property to the item
  406. if (
  407. nextGroupIndex !== undefined &&
  408. nextChildrenIndex !== undefined &&
  409. searchGroups[nextGroupIndex]?.children
  410. ) {
  411. searchGroups[nextGroupIndex].children[nextChildrenIndex] = {
  412. ...searchGroups[nextGroupIndex].children[nextChildrenIndex],
  413. active: true,
  414. };
  415. }
  416. this.setState({searchGroups, activeSearchItem: nextActiveSearchItem});
  417. }
  418. if ((key === 'Tab' || key === 'Enter') && isSelectingDropdownItems) {
  419. evt.preventDefault();
  420. const {activeSearchItem, searchGroups} = this.state;
  421. const [groupIndex, childrenIndex] = filterSearchGroupsByIndex(
  422. searchGroups,
  423. activeSearchItem
  424. );
  425. const item =
  426. groupIndex !== undefined &&
  427. childrenIndex !== undefined &&
  428. searchGroups[groupIndex].children[childrenIndex];
  429. if (item && !isDefaultDropdownItem(item)) {
  430. this.onAutoComplete(item.value, item);
  431. }
  432. return;
  433. }
  434. if (key === 'Enter' && !isSelectingDropdownItems) {
  435. this.doSearch();
  436. return;
  437. }
  438. };
  439. onKeyUp = (evt: React.KeyboardEvent<HTMLTextAreaElement>) => {
  440. // Other keys are managed at onKeyDown function
  441. if (evt.key !== 'Escape') {
  442. return;
  443. }
  444. evt.preventDefault();
  445. const isSelectingDropdownItems = this.state.activeSearchItem > -1;
  446. if (!isSelectingDropdownItems) {
  447. this.blur();
  448. return;
  449. }
  450. const {searchGroups, activeSearchItem} = this.state;
  451. const [groupIndex, childrenIndex] = isSelectingDropdownItems
  452. ? filterSearchGroupsByIndex(searchGroups, activeSearchItem)
  453. : [];
  454. if (groupIndex !== undefined && childrenIndex !== undefined) {
  455. delete searchGroups[groupIndex].children[childrenIndex].active;
  456. }
  457. this.setState({
  458. activeSearchItem: -1,
  459. searchGroups: [...this.state.searchGroups],
  460. });
  461. };
  462. getCursorPosition() {
  463. if (!this.searchInput.current) {
  464. return -1;
  465. }
  466. return this.searchInput.current.selectionStart ?? -1;
  467. }
  468. /**
  469. * Returns array of possible key values that substring match `query`
  470. */
  471. getTagKeys(query: string): SearchItem[] {
  472. const {prepareQuery} = this.props;
  473. const supportedTags = this.props.supportedTags ?? {};
  474. // Return all if query is empty
  475. let tagKeys = Object.keys(supportedTags).map(key => `${key}:`);
  476. if (query) {
  477. const preparedQuery =
  478. typeof prepareQuery === 'function' ? prepareQuery(query) : query;
  479. tagKeys = tagKeys.filter(key => key.indexOf(preparedQuery) > -1);
  480. }
  481. // If the environment feature is active and excludeEnvironment = true
  482. // then remove the environment key
  483. if (this.props.excludeEnvironment) {
  484. tagKeys = tagKeys.filter(key => key !== 'environment:');
  485. }
  486. return tagKeys.map(value => ({value, desc: value}));
  487. }
  488. /**
  489. * Returns array of tag values that substring match `query`; invokes `callback`
  490. * with data when ready
  491. */
  492. getTagValues = debounce(
  493. async (tag: Tag, query: string) => {
  494. // Strip double quotes if there are any
  495. query = query.replace(/"/g, '').trim();
  496. if (!this.props.onGetTagValues) {
  497. return [];
  498. }
  499. if (
  500. this.state.noValueQuery !== undefined &&
  501. query.startsWith(this.state.noValueQuery)
  502. ) {
  503. return [];
  504. }
  505. const {location} = this.props;
  506. const endpointParams = getParams(location.query);
  507. this.setState({loading: true});
  508. let values: string[] = [];
  509. try {
  510. values = await this.props.onGetTagValues(tag, query, endpointParams);
  511. this.setState({loading: false});
  512. } catch (err) {
  513. this.setState({loading: false});
  514. Sentry.captureException(err);
  515. return [];
  516. }
  517. if (tag.key === 'release:' && !values.includes('latest')) {
  518. values.unshift('latest');
  519. }
  520. const noValueQuery = values.length === 0 && query.length > 0 ? query : undefined;
  521. this.setState({noValueQuery});
  522. return values.map(value => {
  523. // Wrap in quotes if there is a space
  524. const escapedValue =
  525. value.includes(' ') || value.includes('"')
  526. ? `"${value.replace(/"/g, '\\"')}"`
  527. : value;
  528. return {value: escapedValue, desc: escapedValue, type: 'tag-value' as ItemType};
  529. });
  530. },
  531. DEFAULT_DEBOUNCE_DURATION,
  532. {leading: true}
  533. );
  534. /**
  535. * Returns array of tag values that substring match `query`; invokes `callback`
  536. * with results
  537. */
  538. getPredefinedTagValues = (tag: Tag, query: string): SearchItem[] =>
  539. (tag.values ?? [])
  540. .filter(value => value.indexOf(query) > -1)
  541. .map((value, i) => ({
  542. value,
  543. desc: value,
  544. type: 'tag-value',
  545. ignoreMaxSearchItems: tag.maxSuggestedValues ? i < tag.maxSuggestedValues : false,
  546. }));
  547. /**
  548. * Get recent searches
  549. */
  550. getRecentSearches = debounce(
  551. async () => {
  552. const {savedSearchType, hasRecentSearches, onGetRecentSearches} = this.props;
  553. // `savedSearchType` can be 0
  554. if (!defined(savedSearchType) || !hasRecentSearches) {
  555. return [];
  556. }
  557. const fetchFn = onGetRecentSearches || this.fetchRecentSearches;
  558. return await fetchFn(this.state.query);
  559. },
  560. DEFAULT_DEBOUNCE_DURATION,
  561. {leading: true}
  562. );
  563. fetchRecentSearches = async (fullQuery: string): Promise<SearchItem[]> => {
  564. const {api, organization, savedSearchType} = this.props;
  565. if (savedSearchType === undefined) {
  566. return [];
  567. }
  568. try {
  569. const recentSearches: any[] = await fetchRecentSearches(
  570. api,
  571. organization.slug,
  572. savedSearchType,
  573. fullQuery
  574. );
  575. // If `recentSearches` is undefined or not an array, the function will
  576. // return an array anyway
  577. return recentSearches.map(searches => ({
  578. desc: searches.query,
  579. value: searches.query,
  580. type: 'recent-search',
  581. }));
  582. } catch (e) {
  583. Sentry.captureException(e);
  584. }
  585. return [];
  586. };
  587. getReleases = debounce(
  588. async (tag: Tag, query: string) => {
  589. const releasePromise = this.fetchReleases(query);
  590. const tags = this.getPredefinedTagValues(tag, query);
  591. const tagValues = tags.map<SearchItem>(v => ({
  592. ...v,
  593. type: 'first-release',
  594. }));
  595. const releases = await releasePromise;
  596. const releaseValues = releases.map<SearchItem>((r: any) => ({
  597. value: r.shortVersion,
  598. desc: r.shortVersion,
  599. type: 'first-release',
  600. }));
  601. return [...tagValues, ...releaseValues];
  602. },
  603. DEFAULT_DEBOUNCE_DURATION,
  604. {leading: true}
  605. );
  606. /**
  607. * Fetches latest releases from a organization/project. Returns an empty array
  608. * if an error is encountered.
  609. */
  610. fetchReleases = async (releaseVersion: string): Promise<any[]> => {
  611. const {api, location, organization} = this.props;
  612. const project = location && location.query ? location.query.projectId : undefined;
  613. const url = `/organizations/${organization.slug}/releases/`;
  614. const fetchQuery: {[key: string]: string | number} = {
  615. per_page: MAX_AUTOCOMPLETE_RELEASES,
  616. };
  617. if (releaseVersion) {
  618. fetchQuery.query = releaseVersion;
  619. }
  620. if (project) {
  621. fetchQuery.project = project;
  622. }
  623. try {
  624. return await api.requestPromise(url, {
  625. method: 'GET',
  626. query: fetchQuery,
  627. });
  628. } catch (e) {
  629. addErrorMessage(t('Unable to fetch releases'));
  630. Sentry.captureException(e);
  631. }
  632. return [];
  633. };
  634. updateAutoCompleteItems = async () => {
  635. if (this.blurTimeout) {
  636. clearTimeout(this.blurTimeout);
  637. this.blurTimeout = undefined;
  638. }
  639. const cursor = this.getCursorPosition();
  640. let query = this.state.query;
  641. // Don't continue if the query hasn't changed
  642. if (query === this.state.previousQuery) {
  643. return;
  644. }
  645. this.setState({previousQuery: query});
  646. const lastTermIndex = getLastTermIndex(query, cursor);
  647. const terms = getQueryTerms(query, lastTermIndex);
  648. if (
  649. !terms || // no terms
  650. terms.length === 0 || // no terms
  651. (terms.length === 1 && terms[0] === this.props.defaultQuery) || // default term
  652. /^\s+$/.test(query.slice(cursor - 1, cursor + 1))
  653. ) {
  654. const [defaultSearchItems, defaultRecentItems] = this.props.defaultSearchItems!;
  655. if (!defaultSearchItems.length) {
  656. // Update searchTerm, otherwise <SearchDropdown> will have wrong state
  657. // (e.g. if you delete a query, the last letter will be highlighted if `searchTerm`
  658. // does not get updated)
  659. this.setState({searchTerm: query});
  660. const tagKeys = this.getTagKeys('');
  661. const recentSearches = await this.getRecentSearches();
  662. this.updateAutoCompleteState(tagKeys, recentSearches ?? [], '', 'tag-key');
  663. return;
  664. }
  665. // cursor on whitespace show default "help" search terms
  666. this.setState({searchTerm: ''});
  667. this.updateAutoCompleteState(defaultSearchItems, defaultRecentItems, '', 'default');
  668. return;
  669. }
  670. const last = terms.pop() ?? '';
  671. let autoCompleteItems: SearchItem[];
  672. let matchValue: string;
  673. let tagName: string;
  674. const index = last.indexOf(':');
  675. if (index === -1) {
  676. // No colon present; must still be deciding key
  677. matchValue = last.replace(new RegExp(`^${NEGATION_OPERATOR}`), '');
  678. autoCompleteItems = this.getTagKeys(matchValue);
  679. const recentSearches = await this.getRecentSearches();
  680. this.setState({searchTerm: matchValue});
  681. this.updateAutoCompleteState(
  682. autoCompleteItems,
  683. recentSearches ?? [],
  684. matchValue,
  685. 'tag-key'
  686. );
  687. return;
  688. }
  689. const {prepareQuery, excludeEnvironment} = this.props;
  690. const supportedTags = this.props.supportedTags ?? {};
  691. // TODO(billy): Better parsing for these examples
  692. //
  693. // > sentry:release:
  694. // > url:"http://with/colon"
  695. tagName = last.slice(0, index);
  696. // e.g. given "!gpu" we want "gpu"
  697. tagName = tagName.replace(new RegExp(`^${NEGATION_OPERATOR}`), '');
  698. query = last.slice(index + 1);
  699. const preparedQuery =
  700. typeof prepareQuery === 'function' ? prepareQuery(query) : query;
  701. // filter existing items immediately, until API can return
  702. // with actual tag value results
  703. const filteredSearchGroups = !preparedQuery
  704. ? this.state.searchGroups
  705. : this.state.searchGroups.filter(
  706. item => item.value && item.value.indexOf(preparedQuery) !== -1
  707. );
  708. this.setState({
  709. searchTerm: query,
  710. searchGroups: filteredSearchGroups,
  711. });
  712. const tag = supportedTags[tagName];
  713. if (!tag) {
  714. this.updateAutoCompleteState([], [], tagName, 'invalid-tag');
  715. return;
  716. }
  717. // Ignore the environment tag if the feature is active and
  718. // excludeEnvironment = true
  719. if (excludeEnvironment && tagName === 'environment') {
  720. return;
  721. }
  722. const fetchTagValuesFn =
  723. tag.key === 'firstRelease'
  724. ? this.getReleases
  725. : tag.predefined
  726. ? this.getPredefinedTagValues
  727. : this.getTagValues;
  728. const [tagValues, recentSearches] = await Promise.all([
  729. fetchTagValuesFn(tag, preparedQuery),
  730. this.getRecentSearches(),
  731. ]);
  732. this.updateAutoCompleteState(
  733. tagValues ?? [],
  734. recentSearches ?? [],
  735. tag.key,
  736. 'tag-value'
  737. );
  738. return;
  739. };
  740. /**
  741. * Updates autocomplete dropdown items and autocomplete index state
  742. *
  743. * @param searchItems List of search item objects with keys: title, desc, value
  744. * @param recentSearchItems List of recent search items, same format as searchItem
  745. * @param tagName The current tag name in scope
  746. * @param type Defines the type/state of the dropdown menu items
  747. */
  748. updateAutoCompleteState(
  749. searchItems: SearchItem[],
  750. recentSearchItems: SearchItem[],
  751. tagName: string,
  752. type: ItemType
  753. ) {
  754. const {hasRecentSearches, maxSearchItems, maxQueryLength} = this.props;
  755. const query = this.state.query;
  756. const queryCharsLeft =
  757. maxQueryLength && query ? maxQueryLength - query.length : undefined;
  758. this.setState(
  759. createSearchGroups(
  760. searchItems,
  761. hasRecentSearches ? recentSearchItems : undefined,
  762. tagName,
  763. type,
  764. maxSearchItems,
  765. queryCharsLeft
  766. )
  767. );
  768. }
  769. onAutoComplete = (replaceText: string, item: SearchItem) => {
  770. if (item.type === 'recent-search') {
  771. trackAnalyticsEvent({
  772. eventKey: 'search.searched',
  773. eventName: 'Search: Performed search',
  774. organization_id: this.props.organization.id,
  775. query: replaceText,
  776. source: this.props.savedSearchType === 0 ? 'issues' : 'events',
  777. search_source: 'recent_search',
  778. });
  779. this.setState({query: replaceText}, () => {
  780. // Propagate onSearch and save to recent searches
  781. this.doSearch();
  782. });
  783. return;
  784. }
  785. const cursor = this.getCursorPosition();
  786. const query = this.state.query;
  787. const lastTermIndex = getLastTermIndex(query, cursor);
  788. const terms = getQueryTerms(query, lastTermIndex);
  789. let newQuery: string;
  790. // If not postfixed with : (tag value), add trailing space
  791. replaceText += item.type !== 'tag-value' || cursor < query.length ? '' : ' ';
  792. const isNewTerm = query.charAt(query.length - 1) === ' ' && item.type !== 'tag-value';
  793. if (!terms) {
  794. newQuery = replaceText;
  795. } else if (isNewTerm) {
  796. newQuery = `${query}${replaceText}`;
  797. } else {
  798. const last = terms.pop() ?? '';
  799. newQuery = query.slice(0, lastTermIndex); // get text preceding last term
  800. const prefix = last.startsWith(NEGATION_OPERATOR) ? NEGATION_OPERATOR : '';
  801. // newQuery is all the terms up to the current term: "... <term>:"
  802. // replaceText should be the selected value
  803. if (last.indexOf(':') > -1) {
  804. let replacement = `:${replaceText}`;
  805. // The user tag often contains : within its value and we need to quote it.
  806. if (last.startsWith('user:')) {
  807. const colonIndex = replaceText.indexOf(':');
  808. if (colonIndex > -1) {
  809. replacement = `:"${replaceText.trim()}"`;
  810. }
  811. }
  812. // tag key present: replace everything after colon with replaceText
  813. newQuery = newQuery.replace(/\:"[^"]*"?$|\:\S*$/, replacement);
  814. } else {
  815. // no tag key present: replace last token with replaceText
  816. newQuery = newQuery.replace(/\S+$/, `${prefix}${replaceText}`);
  817. }
  818. newQuery = newQuery.concat(query.slice(lastTermIndex));
  819. }
  820. this.setState({query: newQuery}, () => {
  821. // setting a new input value will lose focus; restore it
  822. if (this.searchInput.current) {
  823. this.searchInput.current.focus();
  824. }
  825. // then update the autocomplete box with new items
  826. this.updateAutoCompleteItems();
  827. this.props.onChange?.(newQuery, new MouseEvent('click') as any);
  828. });
  829. };
  830. render() {
  831. const {
  832. api,
  833. className,
  834. savedSearchType,
  835. dropdownClassName,
  836. actionBarItems,
  837. organization,
  838. placeholder,
  839. disabled,
  840. useFormWrapper,
  841. inlineLabel,
  842. maxQueryLength,
  843. } = this.props;
  844. const {query, searchGroups, searchTerm, dropdownVisible, numActionsVisible, loading} =
  845. this.state;
  846. const hasSyntaxHighlight = organization.features.includes('search-syntax-highlight');
  847. const input = (
  848. <SearchInput
  849. type="text"
  850. placeholder={placeholder}
  851. id="smart-search-input"
  852. name="query"
  853. ref={this.searchInput}
  854. autoComplete="off"
  855. value={query}
  856. onFocus={this.onQueryFocus}
  857. onBlur={this.onQueryBlur}
  858. onKeyUp={this.onKeyUp}
  859. onKeyDown={this.onKeyDown}
  860. onChange={this.onQueryChange}
  861. onClick={this.onInputClick}
  862. disabled={disabled}
  863. maxLength={maxQueryLength}
  864. spellCheck={false}
  865. hiddenText={hasSyntaxHighlight}
  866. />
  867. );
  868. // Segment actions into visible and overflowed groups
  869. const actionItems = actionBarItems ?? [];
  870. const actionProps = {
  871. api,
  872. organization,
  873. query,
  874. savedSearchType,
  875. };
  876. const visibleActions = actionItems
  877. .slice(0, numActionsVisible)
  878. .map(({key, Action}) => <Action key={key} {...actionProps} />);
  879. const overflowedActions = actionItems
  880. .slice(numActionsVisible)
  881. .map(({key, Action}) => <Action key={key} {...actionProps} menuItemVariant />);
  882. return (
  883. <Container ref={this.containerRef} className={className} isOpen={dropdownVisible}>
  884. <SearchLabel htmlFor="smart-search-input" aria-label={t('Search events')}>
  885. <IconSearch />
  886. {inlineLabel}
  887. </SearchLabel>
  888. <InputWrapper>
  889. {hasSyntaxHighlight && <Highlight>{renderQuery(query)}</Highlight>}
  890. {useFormWrapper ? <form onSubmit={this.onSubmit}>{input}</form> : input}
  891. </InputWrapper>
  892. <ActionsBar gap={0.5}>
  893. {query !== '' && (
  894. <ActionButton
  895. onClick={this.clearSearch}
  896. icon={<IconClose size="xs" />}
  897. title={t('Clear search')}
  898. aria-label={t('Clear search')}
  899. />
  900. )}
  901. {visibleActions}
  902. {overflowedActions.length > 0 && (
  903. <DropdownLink
  904. anchorRight
  905. caret={false}
  906. title={
  907. <ActionButton
  908. aria-label={t('Show more')}
  909. icon={<VerticalEllipsisIcon size="xs" />}
  910. />
  911. }
  912. >
  913. {overflowedActions}
  914. </DropdownLink>
  915. )}
  916. </ActionsBar>
  917. {(loading || searchGroups.length > 0) && (
  918. <SearchDropdown
  919. css={{display: dropdownVisible ? 'block' : 'none'}}
  920. className={dropdownClassName}
  921. items={searchGroups}
  922. onClick={this.onAutoComplete}
  923. loading={loading}
  924. searchSubstring={searchTerm}
  925. />
  926. )}
  927. </Container>
  928. );
  929. }
  930. }
  931. type ContainerState = {
  932. members: ReturnType<typeof MemberListStore.getAll>;
  933. };
  934. class SmartSearchBarContainer extends React.Component<Props, ContainerState> {
  935. state: ContainerState = {
  936. members: MemberListStore.getAll(),
  937. };
  938. componentWillUnmount() {
  939. this.unsubscribe();
  940. }
  941. unsubscribe = MemberListStore.listen(
  942. (members: ContainerState['members']) => this.setState({members}),
  943. undefined
  944. );
  945. render() {
  946. // SmartSearchBar doesn't use members, but we forward it to cause a re-render.
  947. return <SmartSearchBar {...this.props} members={this.state.members} />;
  948. }
  949. }
  950. export default withApi(withRouter(withOrganization(SmartSearchBarContainer)));
  951. export {SmartSearchBar};
  952. const Container = styled('div')<{isOpen: boolean}>`
  953. border: 1px solid ${p => p.theme.border};
  954. box-shadow: inset ${p => p.theme.dropShadowLight};
  955. background: ${p => p.theme.background};
  956. padding: 7px ${space(1)};
  957. position: relative;
  958. display: grid;
  959. grid-template-columns: max-content 1fr max-content;
  960. grid-gap: ${space(1)};
  961. align-items: start;
  962. border-radius: ${p =>
  963. p.isOpen
  964. ? `${p.theme.borderRadius} ${p.theme.borderRadius} 0 0`
  965. : p.theme.borderRadius};
  966. .show-sidebar & {
  967. background: ${p => p.theme.backgroundSecondary};
  968. }
  969. `;
  970. const SearchLabel = styled('label')`
  971. display: flex;
  972. padding: ${space(0.5)} 0;
  973. margin: 0;
  974. color: ${p => p.theme.gray300};
  975. `;
  976. const InputWrapper = styled('div')`
  977. position: relative;
  978. `;
  979. const Highlight = styled('div')`
  980. position: absolute;
  981. top: 0;
  982. left: 0;
  983. right: 0;
  984. bottom: 0;
  985. user-select: none;
  986. white-space: pre-wrap;
  987. line-height: 25px;
  988. font-size: ${p => p.theme.fontSizeSmall};
  989. font-family: ${p => p.theme.text.familyMono};
  990. `;
  991. const SearchInput = styled(TextareaAutosize, {
  992. shouldForwardProp: prop => typeof prop === 'string' && isPropValid(prop),
  993. })<{hiddenText: boolean}>`
  994. position: relative;
  995. display: flex;
  996. resize: none;
  997. outline: none;
  998. border: 0;
  999. width: 100%;
  1000. padding: 0;
  1001. line-height: 25px;
  1002. margin-bottom: -1px;
  1003. background: transparent;
  1004. font-size: ${p => p.theme.fontSizeSmall};
  1005. font-family: ${p => p.theme.text.familyMono};
  1006. caret-color: ${p => p.theme.subText};
  1007. ${p => p.hiddenText && 'color: transparent'};
  1008. &::selection {
  1009. background: rgba(0, 0, 0, 0.2);
  1010. }
  1011. &::placeholder {
  1012. color: ${p => p.theme.formPlaceholder};
  1013. }
  1014. [disabled] {
  1015. color: ${p => p.theme.disabled};
  1016. }
  1017. `;
  1018. const ActionsBar = styled(ButtonBar)`
  1019. height: ${space(2)};
  1020. margin: ${space(0.5)} 0;
  1021. `;
  1022. const VerticalEllipsisIcon = styled(IconEllipsis)`
  1023. transform: rotate(90deg);
  1024. `;