index.tsx 59 KB

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