searchDropdown.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. import {Fragment, PureComponent} from 'react';
  2. import styled from '@emotion/styled';
  3. import color from 'color';
  4. import LoadingIndicator from 'sentry/components/loadingIndicator';
  5. import {parseSearch} from 'sentry/components/searchSyntax/parser';
  6. import HighlightQuery from 'sentry/components/searchSyntax/renderer';
  7. import {t, tct} from 'sentry/locale';
  8. import space from 'sentry/styles/space';
  9. import {FieldValueKind} from 'sentry/views/eventsV2/table/types';
  10. import Button from '../button';
  11. import HotkeysLabel from '../hotkeysLabel';
  12. import Tag from '../tag';
  13. import {ItemType, SearchGroup, SearchItem, Shortcut} from './types';
  14. const getDropdownItemKey = (item: SearchItem) => item.value || item.desc || item.title;
  15. type Props = {
  16. items: SearchGroup[];
  17. loading: boolean;
  18. onClick: (value: string, item: SearchItem) => void;
  19. searchSubstring: string;
  20. className?: string;
  21. maxMenuHeight?: number;
  22. runShortcut?: (shortcut: Shortcut) => void;
  23. visibleShortcuts?: Shortcut[];
  24. };
  25. class SearchDropdown extends PureComponent<Props> {
  26. static defaultProps = {
  27. searchSubstring: '',
  28. onClick: function () {},
  29. };
  30. render() {
  31. const {
  32. className,
  33. loading,
  34. items,
  35. runShortcut,
  36. visibleShortcuts,
  37. maxMenuHeight,
  38. searchSubstring,
  39. onClick,
  40. } = this.props;
  41. return (
  42. <StyledSearchDropdown className={className}>
  43. {loading ? (
  44. <LoadingWrapper key="loading" data-test-id="search-autocomplete-loading">
  45. <LoadingIndicator mini />
  46. </LoadingWrapper>
  47. ) : (
  48. <SearchItemsList maxMenuHeight={maxMenuHeight}>
  49. {items.map(item => {
  50. const isEmpty = item.children && !item.children.length;
  51. // Hide header if `item.children` is defined, an array, and is empty
  52. return (
  53. <Fragment key={item.title}>
  54. {item.type === 'header' && <HeaderItem group={item} />}
  55. {item.children &&
  56. item.children.map(child => (
  57. <DropdownItem
  58. key={getDropdownItemKey(child)}
  59. item={child}
  60. searchSubstring={searchSubstring}
  61. onClick={onClick}
  62. />
  63. ))}
  64. {isEmpty && <Info>{t('No items found')}</Info>}
  65. </Fragment>
  66. );
  67. })}
  68. </SearchItemsList>
  69. )}
  70. <DropdownFooter>
  71. <ShortcutsRow>
  72. {runShortcut &&
  73. visibleShortcuts?.map(shortcut => {
  74. return (
  75. <ShortcutButtonContainer
  76. key={shortcut.text}
  77. onClick={() => runShortcut(shortcut)}
  78. >
  79. <HotkeyGlyphWrapper>
  80. <HotkeysLabel
  81. value={
  82. shortcut.hotkeys?.display ?? shortcut.hotkeys?.actual ?? []
  83. }
  84. />
  85. </HotkeyGlyphWrapper>
  86. <IconWrapper>{shortcut.icon}</IconWrapper>
  87. <HotkeyTitle>{shortcut.text}</HotkeyTitle>
  88. </ShortcutButtonContainer>
  89. );
  90. })}
  91. </ShortcutsRow>
  92. <Button size="xs" href="https://docs.sentry.io/product/sentry-basics/search/">
  93. Read the docs
  94. </Button>
  95. </DropdownFooter>
  96. </StyledSearchDropdown>
  97. );
  98. }
  99. }
  100. export default SearchDropdown;
  101. type HeaderItemProps = {
  102. group: SearchGroup;
  103. };
  104. const HeaderItem = ({group}: HeaderItemProps) => {
  105. return (
  106. <SearchDropdownGroup key={group.title}>
  107. <SearchDropdownGroupTitle>
  108. {group.icon}
  109. {group.title && group.title}
  110. {group.desc && <span>{group.desc}</span>}
  111. </SearchDropdownGroupTitle>
  112. </SearchDropdownGroup>
  113. );
  114. };
  115. type HighlightedRestOfWordsProps = {
  116. combinedRestWords: string;
  117. firstWord: string;
  118. searchSubstring: string;
  119. hasSplit?: boolean;
  120. isFirstWordHidden?: boolean;
  121. };
  122. const HighlightedRestOfWords = ({
  123. combinedRestWords,
  124. searchSubstring,
  125. firstWord,
  126. isFirstWordHidden,
  127. hasSplit,
  128. }: HighlightedRestOfWordsProps) => {
  129. const remainingSubstr =
  130. searchSubstring.indexOf(firstWord) === -1
  131. ? searchSubstring
  132. : searchSubstring.slice(firstWord.length + 1);
  133. const descIdx = combinedRestWords.indexOf(remainingSubstr);
  134. if (descIdx > -1) {
  135. return (
  136. <RestOfWordsContainer isFirstWordHidden={isFirstWordHidden} hasSplit={hasSplit}>
  137. .{combinedRestWords.slice(0, descIdx)}
  138. <strong>
  139. {combinedRestWords.slice(descIdx, descIdx + remainingSubstr.length)}
  140. </strong>
  141. {combinedRestWords.slice(descIdx + remainingSubstr.length)}
  142. </RestOfWordsContainer>
  143. );
  144. }
  145. return (
  146. <RestOfWordsContainer isFirstWordHidden={isFirstWordHidden} hasSplit={hasSplit}>
  147. .{combinedRestWords}
  148. </RestOfWordsContainer>
  149. );
  150. };
  151. type ItemTitleProps = {
  152. item: SearchItem;
  153. searchSubstring: string;
  154. isChild?: boolean;
  155. };
  156. const ItemTitle = ({item, searchSubstring, isChild}: ItemTitleProps) => {
  157. if (!item.title) {
  158. return null;
  159. }
  160. const fullWord = item.title;
  161. const words = item.kind !== FieldValueKind.FUNCTION ? fullWord.split('.') : [fullWord];
  162. const [firstWord, ...restWords] = words;
  163. const isFirstWordHidden = isChild;
  164. const combinedRestWords = restWords.length > 0 ? restWords.join('.') : null;
  165. if (searchSubstring) {
  166. const idx =
  167. restWords.length === 0
  168. ? fullWord.toLowerCase().indexOf(searchSubstring.split('.')[0])
  169. : fullWord.toLowerCase().indexOf(searchSubstring);
  170. // Below is the logic to make the current query bold inside the result.
  171. if (idx !== -1) {
  172. return (
  173. <SearchItemTitleWrapper>
  174. {!isFirstWordHidden && (
  175. <FirstWordWrapper>
  176. {firstWord.slice(0, idx)}
  177. <strong>{firstWord.slice(idx, idx + searchSubstring.length)}</strong>
  178. {firstWord.slice(idx + searchSubstring.length)}
  179. </FirstWordWrapper>
  180. )}
  181. {combinedRestWords && (
  182. <HighlightedRestOfWords
  183. firstWord={firstWord}
  184. isFirstWordHidden={isFirstWordHidden}
  185. searchSubstring={searchSubstring}
  186. combinedRestWords={combinedRestWords}
  187. hasSplit={words.length > 1}
  188. />
  189. )}
  190. </SearchItemTitleWrapper>
  191. );
  192. }
  193. }
  194. return (
  195. <SearchItemTitleWrapper>
  196. {!isFirstWordHidden && <FirstWordWrapper>{firstWord}</FirstWordWrapper>}
  197. {combinedRestWords && (
  198. <RestOfWordsContainer
  199. isFirstWordHidden={isFirstWordHidden}
  200. hasSplit={words.length > 1}
  201. >
  202. .{combinedRestWords}
  203. </RestOfWordsContainer>
  204. )}
  205. </SearchItemTitleWrapper>
  206. );
  207. };
  208. type KindTagProps = {kind: FieldValueKind};
  209. const KindTag = ({kind}: KindTagProps) => {
  210. let text, tagType;
  211. switch (kind) {
  212. case FieldValueKind.FUNCTION:
  213. text = 'f(x)';
  214. tagType = 'success';
  215. break;
  216. case FieldValueKind.MEASUREMENT:
  217. text = 'field';
  218. tagType = 'highlight';
  219. break;
  220. case FieldValueKind.BREAKDOWN:
  221. text = 'field';
  222. tagType = 'highlight';
  223. break;
  224. case FieldValueKind.TAG:
  225. text = kind;
  226. tagType = 'warning';
  227. break;
  228. case FieldValueKind.NUMERIC_METRICS:
  229. text = 'f(x)';
  230. tagType = 'success';
  231. break;
  232. case FieldValueKind.FIELD:
  233. default:
  234. text = kind;
  235. }
  236. return <Tag type={tagType}>{text}</Tag>;
  237. };
  238. type DropdownItemProps = {
  239. item: SearchItem;
  240. onClick: (value: string, item: SearchItem) => void;
  241. searchSubstring: string;
  242. isChild?: boolean;
  243. };
  244. const DropdownItem = ({item, isChild, searchSubstring, onClick}: DropdownItemProps) => {
  245. const isDisabled = item.value === null;
  246. let children: React.ReactNode;
  247. if (item.type === ItemType.RECENT_SEARCH) {
  248. children = <QueryItem item={item} />;
  249. } else if (item.type === ItemType.INVALID_TAG) {
  250. children = (
  251. <Invalid>
  252. {tct("The field [field] isn't supported here. ", {
  253. field: <strong>{item.desc}</strong>,
  254. })}
  255. {tct('[highlight:See all searchable properties in the docs.]', {
  256. highlight: <Highlight />,
  257. })}
  258. </Invalid>
  259. );
  260. } else {
  261. children = (
  262. <Fragment>
  263. <ItemTitle item={item} isChild={isChild} searchSubstring={searchSubstring} />
  264. {item.desc && <Value hasDocs={!!item.documentation}>{item.desc}</Value>}
  265. <Documentation>{item.documentation}</Documentation>
  266. <TagWrapper>{item.kind && !isChild && <KindTag kind={item.kind} />}</TagWrapper>
  267. </Fragment>
  268. );
  269. }
  270. return (
  271. <Fragment>
  272. <SearchListItem
  273. className={`${isChild ? 'group-child' : ''} ${item.active ? 'active' : ''}`}
  274. data-test-id="search-autocomplete-item"
  275. onClick={
  276. !isDisabled ? item.callback ?? onClick.bind(this, item.value, item) : undefined
  277. }
  278. ref={element => item.active && element?.scrollIntoView?.({block: 'nearest'})}
  279. isGrouped={isChild}
  280. isDisabled={isDisabled}
  281. >
  282. {children}
  283. </SearchListItem>
  284. {!isChild &&
  285. item.children?.map(child => (
  286. <DropdownItem
  287. key={getDropdownItemKey(child)}
  288. item={child}
  289. onClick={onClick}
  290. searchSubstring={searchSubstring}
  291. isChild
  292. />
  293. ))}
  294. </Fragment>
  295. );
  296. };
  297. type QueryItemProps = {item: SearchItem};
  298. const QueryItem = ({item}: QueryItemProps) => {
  299. if (!item.value) {
  300. return null;
  301. }
  302. const parsedQuery = parseSearch(item.value);
  303. if (!parsedQuery) {
  304. return null;
  305. }
  306. return (
  307. <QueryItemWrapper>
  308. <HighlightQuery parsedQuery={parsedQuery} />
  309. </QueryItemWrapper>
  310. );
  311. };
  312. const StyledSearchDropdown = styled('div')`
  313. /* Container has a border that we need to account for */
  314. position: absolute;
  315. top: 100%;
  316. left: -1px;
  317. right: -1px;
  318. z-index: ${p => p.theme.zIndex.dropdown};
  319. overflow: hidden;
  320. margin-top: ${space(1)};
  321. background: ${p => p.theme.background};
  322. box-shadow: ${p => p.theme.dropShadowHeavy};
  323. border: 1px solid ${p => p.theme.border};
  324. border-radius: ${p => p.theme.borderRadius};
  325. `;
  326. const LoadingWrapper = styled('div')`
  327. display: flex;
  328. justify-content: center;
  329. padding: ${space(1)};
  330. `;
  331. const Info = styled('div')`
  332. display: flex;
  333. padding: ${space(1)} ${space(2)};
  334. font-size: ${p => p.theme.fontSizeLarge};
  335. color: ${p => p.theme.gray300};
  336. &:not(:last-child) {
  337. border-bottom: 1px solid ${p => p.theme.innerBorder};
  338. }
  339. `;
  340. const ListItem = styled('li')`
  341. &:not(:first-child):not(.group-child) {
  342. border-top: 1px solid ${p => p.theme.innerBorder};
  343. }
  344. `;
  345. const SearchDropdownGroup = styled(ListItem)``;
  346. const SearchDropdownGroupTitle = styled('header')`
  347. display: flex;
  348. align-items: center;
  349. background-color: ${p => p.theme.backgroundSecondary};
  350. color: ${p => p.theme.gray300};
  351. font-weight: normal;
  352. font-size: ${p => p.theme.fontSizeMedium};
  353. margin: 0;
  354. padding: ${space(1)} ${space(2)};
  355. & > svg {
  356. margin-right: ${space(1)};
  357. }
  358. `;
  359. const SearchItemsList = styled('ul')<{maxMenuHeight?: number}>`
  360. padding-left: 0;
  361. list-style: none;
  362. margin-bottom: 0;
  363. ${p => {
  364. if (p.maxMenuHeight !== undefined) {
  365. return `
  366. max-height: ${p.maxMenuHeight}px;
  367. overflow-y: scroll;
  368. `;
  369. }
  370. return `
  371. height: auto;
  372. `;
  373. }}
  374. `;
  375. const SearchListItem = styled(ListItem)<{isDisabled?: boolean; isGrouped?: boolean}>`
  376. scroll-margin: 40px 0;
  377. font-size: ${p => p.theme.fontSizeLarge};
  378. padding: 4px ${space(2)};
  379. min-height: ${p => (p.isGrouped ? '30px' : '36px')};
  380. ${p => {
  381. if (!p.isDisabled) {
  382. return `
  383. cursor: pointer;
  384. &:hover,
  385. &.active {
  386. background: ${p.theme.hover};
  387. }
  388. `;
  389. }
  390. return '';
  391. }}
  392. display: flex;
  393. flex-direction: row;
  394. justify-content: space-between;
  395. align-items: center;
  396. width: 100%;
  397. `;
  398. const SearchItemTitleWrapper = styled('div')`
  399. display: flex;
  400. flex-grow: 1;
  401. flex-shrink: 0;
  402. max-width: min(280px, 50%);
  403. color: ${p => p.theme.textColor};
  404. font-weight: normal;
  405. font-size: ${p => p.theme.fontSizeMedium};
  406. margin: 0;
  407. line-height: ${p => p.theme.text.lineHeightHeading};
  408. ${p => p.theme.overflowEllipsis};
  409. `;
  410. const RestOfWordsContainer = styled('span')<{
  411. hasSplit?: boolean;
  412. isFirstWordHidden?: boolean;
  413. }>`
  414. color: ${p => (p.hasSplit ? p.theme.blue400 : p.theme.textColor)};
  415. margin-left: ${p => (p.isFirstWordHidden ? space(1) : '0px')};
  416. `;
  417. const FirstWordWrapper = styled('span')`
  418. font-weight: medium;
  419. `;
  420. const TagWrapper = styled('span')`
  421. width: 5%;
  422. display: flex;
  423. flex-direction: row;
  424. align-items: center;
  425. justify-content: flex-end;
  426. `;
  427. const Documentation = styled('span')`
  428. font-size: ${p => p.theme.fontSizeMedium};
  429. font-family: ${p => p.theme.text.family};
  430. color: ${p => p.theme.gray300};
  431. display: flex;
  432. flex: 2;
  433. padding: 0 ${space(1)};
  434. @media (max-width: ${p => p.theme.breakpoints.small}) {
  435. display: none;
  436. }
  437. `;
  438. const DropdownFooter = styled(`div`)`
  439. width: 100%;
  440. min-height: 45px;
  441. background-color: ${p => p.theme.backgroundSecondary};
  442. border-top: 1px solid ${p => p.theme.innerBorder};
  443. flex-direction: row;
  444. display: flex;
  445. align-items: center;
  446. justify-content: space-between;
  447. padding: ${space(1)};
  448. flex-wrap: wrap;
  449. gap: ${space(1)};
  450. `;
  451. const ShortcutsRow = styled('div')`
  452. flex-direction: row;
  453. display: flex;
  454. align-items: center;
  455. `;
  456. const ShortcutButtonContainer = styled('div')`
  457. display: flex;
  458. flex-direction: row;
  459. align-items: center;
  460. height: auto;
  461. padding: 0 ${space(1.5)};
  462. cursor: pointer;
  463. :hover {
  464. border-radius: ${p => p.theme.borderRadius};
  465. background-color: ${p => color(p.theme.hover).darken(0.02).string()};
  466. }
  467. `;
  468. const HotkeyGlyphWrapper = styled('span')`
  469. color: ${p => p.theme.gray300};
  470. margin-right: ${space(0.5)};
  471. @media (max-width: ${p => p.theme.breakpoints.small}) {
  472. display: none;
  473. }
  474. `;
  475. const IconWrapper = styled('span')`
  476. display: none;
  477. @media (max-width: ${p => p.theme.breakpoints.small}) {
  478. display: flex;
  479. margin-right: ${space(0.5)};
  480. align-items: center;
  481. justify-content: center;
  482. }
  483. `;
  484. const HotkeyTitle = styled(`span`)`
  485. font-size: ${p => p.theme.fontSizeSmall};
  486. `;
  487. const Invalid = styled(`span`)`
  488. font-size: ${p => p.theme.fontSizeSmall};
  489. font-family: ${p => p.theme.text.family};
  490. color: ${p => p.theme.gray400};
  491. display: flex;
  492. flex-direction: row;
  493. flex-wrap: wrap;
  494. span {
  495. white-space: pre;
  496. }
  497. `;
  498. const Highlight = styled(`strong`)`
  499. color: ${p => p.theme.linkColor};
  500. `;
  501. const QueryItemWrapper = styled('span')`
  502. font-size: ${p => p.theme.fontSizeSmall};
  503. width: 100%;
  504. gap: ${space(1)};
  505. display: flex;
  506. white-space: nowrap;
  507. word-break: normal;
  508. font-family: ${p => p.theme.text.familyMono};
  509. `;
  510. const Value = styled('span')<{hasDocs?: boolean}>`
  511. font-family: ${p => p.theme.text.familyMono};
  512. font-size: ${p => p.theme.fontSizeSmall};
  513. max-width: ${p => (p.hasDocs ? '280px' : 'none')};
  514. ${p => p.theme.overflowEllipsis};
  515. `;