menu.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. import {useCallback} from 'react';
  2. import styled from '@emotion/styled';
  3. import memoize from 'lodash/memoize';
  4. import AutoComplete from 'sentry/components/autoComplete';
  5. import DropdownBubble from 'sentry/components/dropdownBubble';
  6. import Input from 'sentry/components/forms/controls/input';
  7. import LoadingIndicator from 'sentry/components/loadingIndicator';
  8. import {t} from 'sentry/locale';
  9. import space from 'sentry/styles/space';
  10. import autoCompleteFilter from './autoCompleteFilter';
  11. import List from './list';
  12. import {Item, ItemsBeforeFilter} from './types';
  13. type AutoCompleteChildrenArgs = Parameters<AutoComplete<Item>['props']['children']>[0];
  14. type Actions = AutoCompleteChildrenArgs['actions'];
  15. export type MenuFooterChildProps = {
  16. actions: Actions;
  17. };
  18. type ListProps = React.ComponentProps<typeof List>;
  19. type Props = {
  20. children: (
  21. args: Pick<
  22. AutoCompleteChildrenArgs,
  23. 'getInputProps' | 'getActorProps' | 'actions' | 'isOpen' | 'selectedItem'
  24. >
  25. ) => React.ReactNode;
  26. /** null items indicates loading */
  27. items: ItemsBeforeFilter | null;
  28. /**
  29. * Dropdown menu alignment.
  30. */
  31. alignMenu?: 'left' | 'right';
  32. /**
  33. * Should menu visually lock to a direction (so we don't display a rounded corner)
  34. */
  35. blendCorner?: boolean;
  36. /**
  37. * Show loading indicator next to input and "Searching..." text in the list
  38. */
  39. busy?: boolean;
  40. /**
  41. * Show loading indicator next to input but don't hide list items
  42. */
  43. busyItemsStillVisible?: boolean;
  44. /**
  45. * for passing styles to the DropdownBubble
  46. */
  47. className?: string;
  48. /**
  49. * AutoComplete prop
  50. */
  51. closeOnSelect?: boolean;
  52. css?: any;
  53. 'data-test-id'?: string;
  54. /**
  55. * If true, the menu will be visually detached from actor.
  56. */
  57. detached?: boolean;
  58. /**
  59. * Disables padding for the label.
  60. */
  61. disableLabelPadding?: boolean;
  62. /**
  63. * passed down to the AutoComplete Component
  64. */
  65. disabled?: boolean;
  66. /**
  67. * Hide's the input when there are no items. Avoid using this when querying
  68. * results in an async fashion.
  69. */
  70. emptyHidesInput?: boolean;
  71. /**
  72. * Message to display when there are no items initially
  73. */
  74. emptyMessage?: React.ReactNode;
  75. /**
  76. * If this is undefined, autocomplete filter will use this value instead of the
  77. * current value in the filter input element.
  78. *
  79. * This is useful if you need to strip characters out of the search
  80. */
  81. filterValue?: string;
  82. /**
  83. * Hides the default filter input
  84. */
  85. hideInput?: boolean;
  86. /**
  87. * renderProp for the end (right side) of the search input
  88. */
  89. inputActions?: React.ReactElement;
  90. /**
  91. * Props to pass to input/filter component
  92. */
  93. inputProps?: {style: React.CSSProperties};
  94. /**
  95. * Used to control dropdown state (optional)
  96. */
  97. isOpen?: boolean;
  98. /**
  99. * Max height of dropdown menu. Units are assumed as `px`
  100. */
  101. maxHeight?: ListProps['maxHeight'];
  102. menuFooter?:
  103. | React.ReactElement
  104. | ((props: MenuFooterChildProps) => React.ReactElement | null);
  105. menuHeader?: React.ReactElement;
  106. /**
  107. * Props to pass to menu component
  108. */
  109. menuProps?: Parameters<AutoCompleteChildrenArgs['getMenuProps']>[0];
  110. /**
  111. * Minimum menu width, defaults to 250
  112. */
  113. minWidth?: number;
  114. /**
  115. * Message to display when there are no items that match the search
  116. */
  117. noResultsMessage?: React.ReactNode;
  118. /**
  119. * When AutoComplete input changes
  120. */
  121. onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
  122. /**
  123. * Callback for when dropdown menu closes
  124. */
  125. onClose?: () => void;
  126. /**
  127. * Callback for when dropdown menu opens
  128. */
  129. onOpen?: (event?: React.MouseEvent) => void;
  130. /**
  131. * When an item is selected (via clicking dropdown, or keyboard navigation)
  132. */
  133. onSelect?: (
  134. item: Item,
  135. state?: AutoComplete<Item>['state'],
  136. e?: React.MouseEvent | React.KeyboardEvent
  137. ) => void;
  138. /**
  139. * for passing simple styles to the root container
  140. */
  141. rootClassName?: string;
  142. /**
  143. * Search input's placeholder text
  144. */
  145. searchPlaceholder?: string;
  146. /**
  147. * the styles are forward to the Autocomplete's getMenuProps func
  148. */
  149. style?: React.CSSProperties;
  150. /**
  151. * Optional element to be rendered on the right side of the dropdown menu
  152. */
  153. subPanel?: React.ReactNode;
  154. } & Pick<
  155. ListProps,
  156. 'virtualizedHeight' | 'virtualizedLabelHeight' | 'itemSize' | 'onScroll'
  157. >;
  158. function Menu({
  159. maxHeight = 300,
  160. emptyMessage = t('No items'),
  161. searchPlaceholder = t('Filter search'),
  162. blendCorner = true,
  163. detached = false,
  164. alignMenu = 'left',
  165. minWidth = 250,
  166. hideInput = false,
  167. disableLabelPadding = false,
  168. busy = false,
  169. busyItemsStillVisible = false,
  170. disabled = false,
  171. subPanel = null,
  172. itemSize,
  173. virtualizedHeight,
  174. virtualizedLabelHeight,
  175. menuProps,
  176. noResultsMessage,
  177. inputProps,
  178. children,
  179. rootClassName,
  180. className,
  181. emptyHidesInput,
  182. menuHeader,
  183. filterValue,
  184. items,
  185. menuFooter,
  186. style,
  187. onScroll,
  188. inputActions,
  189. onChange,
  190. onSelect,
  191. onOpen,
  192. onClose,
  193. css,
  194. closeOnSelect,
  195. 'data-test-id': dataTestId,
  196. ...props
  197. }: Props) {
  198. // Can't search if there are no items
  199. const hasItems = !!items?.length;
  200. // Items are loading if null
  201. const itemsLoading = items === null;
  202. // Hide the input when we have no items to filter, only if
  203. // emptyHidesInput is set to true.
  204. const showInput = !hideInput && (hasItems || !emptyHidesInput);
  205. // Only redefine the autocomplete function if our items list has changed.
  206. // This avoids producing a new array on every call.
  207. const stableItemFilter = useCallback(
  208. (filterValueOrInput: string) => autoCompleteFilter(items, filterValueOrInput),
  209. [items]
  210. );
  211. // Memoize the filterValueOrInput to the stableItemFilter so that we get the
  212. // same list every time when the filter value doesn't change.
  213. const getFilteredItems = memoize(stableItemFilter);
  214. return (
  215. <AutoComplete
  216. onSelect={onSelect}
  217. inputIsActor={false}
  218. onOpen={onOpen}
  219. onClose={onClose}
  220. disabled={disabled}
  221. closeOnSelect={closeOnSelect}
  222. resetInputOnClose
  223. {...props}
  224. >
  225. {({
  226. getActorProps,
  227. getRootProps,
  228. getInputProps,
  229. getMenuProps,
  230. getItemProps,
  231. registerItemCount,
  232. registerVisibleItem,
  233. inputValue,
  234. selectedItem,
  235. highlightedIndex,
  236. isOpen,
  237. actions,
  238. }) => {
  239. // This is the value to use to filter (default to value in filter input)
  240. const filterValueOrInput = filterValue ?? inputValue;
  241. // Only filter results if menu is open and there are items. Uses
  242. // `getFilteredItems` to ensure we get a stable items list back.
  243. const autoCompleteResults =
  244. isOpen && hasItems ? getFilteredItems(filterValueOrInput) : [];
  245. // Has filtered results
  246. const hasResults = !!autoCompleteResults.length;
  247. // No items to display
  248. const showNoItems = !busy && !filterValueOrInput && !hasItems;
  249. // Results mean there was an attempt to search
  250. const showNoResultsMessage =
  251. !busy && !busyItemsStillVisible && filterValueOrInput && !hasResults;
  252. // When virtualization is turned on, we need to pass in the number of
  253. // selectable items for arrow-key limits
  254. const itemCount = virtualizedHeight
  255. ? autoCompleteResults.filter(i => !i.groupLabel).length
  256. : undefined;
  257. const renderedFooter =
  258. typeof menuFooter === 'function' ? menuFooter({actions}) : menuFooter;
  259. // XXX(epurkhiser): Would be better if this happened in a useEffect,
  260. // but hooks do not work inside render-prop callbacks.
  261. registerItemCount(itemCount);
  262. return (
  263. <AutoCompleteRoot
  264. {...getRootProps()}
  265. className={rootClassName}
  266. disabled={disabled}
  267. data-is-open={isOpen}
  268. data-test-id={dataTestId}
  269. >
  270. {children({
  271. getInputProps,
  272. getActorProps,
  273. actions,
  274. isOpen,
  275. selectedItem,
  276. })}
  277. {isOpen && (
  278. <StyledDropdownBubble
  279. className={className}
  280. {...getMenuProps(menuProps)}
  281. {...{style, css, blendCorner, detached, alignMenu, minWidth}}
  282. >
  283. <DropdownMainContent minWidth={minWidth}>
  284. {itemsLoading && <LoadingIndicator mini />}
  285. {showInput && (
  286. <InputWrapper>
  287. <StyledInput
  288. autoFocus
  289. placeholder={searchPlaceholder}
  290. {...getInputProps({...inputProps, onChange})}
  291. />
  292. <InputLoadingWrapper>
  293. {(busy || busyItemsStillVisible) && (
  294. <LoadingIndicator size={16} mini />
  295. )}
  296. </InputLoadingWrapper>
  297. {inputActions}
  298. </InputWrapper>
  299. )}
  300. <div>
  301. {menuHeader && (
  302. <LabelWithPadding disableLabelPadding={disableLabelPadding}>
  303. {menuHeader}
  304. </LabelWithPadding>
  305. )}
  306. <ItemList data-test-id="autocomplete-list" maxHeight={maxHeight}>
  307. {showNoItems && <EmptyMessage>{emptyMessage}</EmptyMessage>}
  308. {showNoResultsMessage && (
  309. <EmptyMessage>
  310. {noResultsMessage ?? `${emptyMessage} ${t('found')}`}
  311. </EmptyMessage>
  312. )}
  313. {busy && (
  314. <BusyMessage>
  315. <EmptyMessage>{t('Searching\u2026')}</EmptyMessage>
  316. </BusyMessage>
  317. )}
  318. {!busy && (
  319. <List
  320. items={autoCompleteResults}
  321. {...{
  322. maxHeight,
  323. highlightedIndex,
  324. inputValue,
  325. onScroll,
  326. getItemProps,
  327. registerVisibleItem,
  328. virtualizedLabelHeight,
  329. virtualizedHeight,
  330. itemSize,
  331. }}
  332. />
  333. )}
  334. </ItemList>
  335. {renderedFooter && (
  336. <LabelWithPadding disableLabelPadding={disableLabelPadding}>
  337. {renderedFooter}
  338. </LabelWithPadding>
  339. )}
  340. </div>
  341. </DropdownMainContent>
  342. {subPanel}
  343. </StyledDropdownBubble>
  344. )}
  345. </AutoCompleteRoot>
  346. );
  347. }}
  348. </AutoComplete>
  349. );
  350. }
  351. export default Menu;
  352. const StyledInput = styled(Input)`
  353. flex: 1;
  354. border: 1px solid transparent;
  355. &,
  356. &:focus,
  357. &:active,
  358. &:hover {
  359. border: 0;
  360. box-shadow: none;
  361. font-size: 13px;
  362. padding: ${space(1)};
  363. font-weight: normal;
  364. color: ${p => p.theme.gray300};
  365. }
  366. `;
  367. const InputLoadingWrapper = styled('div')`
  368. display: flex;
  369. background: ${p => p.theme.background};
  370. align-items: center;
  371. flex-shrink: 0;
  372. width: 30px;
  373. .loading.mini {
  374. height: 16px;
  375. margin: 0;
  376. }
  377. `;
  378. const EmptyMessage = styled('div')`
  379. color: ${p => p.theme.gray200};
  380. padding: ${space(2)};
  381. text-align: center;
  382. text-transform: none;
  383. `;
  384. export const AutoCompleteRoot = styled('div')<{disabled?: boolean}>`
  385. position: relative;
  386. display: inline-block;
  387. ${p => p.disabled && 'pointer-events: none;'}
  388. `;
  389. const StyledDropdownBubble = styled(DropdownBubble)<{minWidth: number}>`
  390. display: flex;
  391. min-width: ${p => p.minWidth}px;
  392. ${p => p.detached && p.alignMenu === 'left' && 'right: auto;'}
  393. ${p => p.detached && p.alignMenu === 'right' && 'left: auto;'}
  394. `;
  395. const DropdownMainContent = styled('div')<{minWidth: number}>`
  396. width: 100%;
  397. min-width: ${p => p.minWidth}px;
  398. `;
  399. const InputWrapper = styled('div')`
  400. display: flex;
  401. border-bottom: 1px solid ${p => p.theme.innerBorder};
  402. border-radius: ${p => `${p.theme.borderRadius} ${p.theme.borderRadius} 0 0`};
  403. align-items: center;
  404. `;
  405. const LabelWithPadding = styled('div')<{disableLabelPadding: boolean}>`
  406. background-color: ${p => p.theme.backgroundSecondary};
  407. border-bottom: 1px solid ${p => p.theme.innerBorder};
  408. border-width: 1px 0;
  409. color: ${p => p.theme.subText};
  410. font-size: ${p => p.theme.fontSizeMedium};
  411. &:first-child {
  412. border-top: none;
  413. }
  414. &:last-child {
  415. border-bottom: none;
  416. }
  417. padding: ${p => !p.disableLabelPadding && `${space(0.25)} ${space(1)}`};
  418. `;
  419. const ItemList = styled('div')<{maxHeight: NonNullable<Props['maxHeight']>}>`
  420. max-height: ${p => `${p.maxHeight}px`};
  421. overflow-y: auto;
  422. `;
  423. const BusyMessage = styled('div')`
  424. display: flex;
  425. justify-content: center;
  426. padding: ${space(1)};
  427. `;