autoComplete.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. /**
  2. * Inspired by [Downshift](https://github.com/paypal/downshift)
  3. *
  4. * Implemented with a stripped-down, compatible API for our use case.
  5. * May be worthwhile to switch if we find we need more features
  6. *
  7. * Basic idea is that we call `children` with props necessary to render with any sort of component structure.
  8. * This component handles logic like when the dropdown menu should be displayed, as well as handling keyboard input, how
  9. * it is rendered should be left to the child.
  10. */
  11. import {Component} from 'react';
  12. import DropdownMenu, {GetActorArgs, GetMenuArgs} from 'sentry/components/dropdownMenu';
  13. const defaultProps = {
  14. itemToString: () => '',
  15. /**
  16. * If input should be considered an "actor". If there is another parent actor, then this should be `false`.
  17. * e.g. You have a button that opens this <AutoComplete> in a dropdown.
  18. */
  19. inputIsActor: true,
  20. disabled: false,
  21. closeOnSelect: true,
  22. /**
  23. * Can select autocomplete item with "Enter" key
  24. */
  25. shouldSelectWithEnter: true,
  26. /**
  27. * Can select autocomplete item with "Tab" key
  28. */
  29. shouldSelectWithTab: false,
  30. };
  31. type Item = {
  32. 'data-test-id'?: string;
  33. disabled?: boolean;
  34. };
  35. type GetInputArgs<E extends HTMLInputElement> = {
  36. onBlur?: (event: React.FocusEvent<E>) => void;
  37. onChange?: (event: React.ChangeEvent<E>) => void;
  38. onFocus?: (event: React.FocusEvent<E>) => void;
  39. onKeyDown?: (event: React.KeyboardEvent<E>) => void;
  40. placeholder?: string;
  41. style?: React.CSSProperties;
  42. type?: string;
  43. };
  44. type GetInputOutput<E extends HTMLInputElement> = GetInputArgs<E> &
  45. GetActorArgs<E> & {
  46. value?: string;
  47. };
  48. type GetItemArgs<T> = {
  49. index: number;
  50. item: T;
  51. onClick?: (item: T) => (e: React.MouseEvent) => void;
  52. };
  53. type ChildrenProps<T> = Parameters<DropdownMenu['props']['children']>[0] & {
  54. /**
  55. * Returns props for the input element that handles searching the items
  56. */
  57. getInputProps: <E extends HTMLInputElement = HTMLInputElement>(
  58. args: GetInputArgs<E>
  59. ) => GetInputOutput<E>;
  60. /**
  61. * Returns props for an individual item
  62. */
  63. getItemProps: (args: GetItemArgs<T>) => {
  64. onClick: (e: React.MouseEvent) => void;
  65. };
  66. /**
  67. * The actively highlighted item index
  68. */
  69. highlightedIndex: number;
  70. /**
  71. * The current value of the input box
  72. */
  73. inputValue: string;
  74. /**
  75. * Registers the total number of items in the dropdown menu.
  76. *
  77. * This must be called for keyboard navigation to work.
  78. */
  79. registerItemCount: (count?: number) => void;
  80. /**
  81. * Registers an item as being visible in the autocomplete menu. Returns an
  82. * cleanup function that unregisters the item as visible.
  83. *
  84. * This is needed for managing keyboard navigation when using react virtualized.
  85. *
  86. * NOTE: Even when NOT using a virtualized list, this must still be called for
  87. * keyboard navigation to work!
  88. */
  89. registerVisibleItem: (index: number, item: T) => () => void;
  90. /**
  91. * The current selected item
  92. */
  93. selectedItem?: T;
  94. };
  95. type State<T> = {
  96. highlightedIndex: number;
  97. inputValue: string;
  98. isOpen: boolean;
  99. selectedItem?: T;
  100. };
  101. type Props<T> = typeof defaultProps & {
  102. /**
  103. * Must be a function that returns a component
  104. */
  105. children: (props: ChildrenProps<T>) => React.ReactElement | null;
  106. disabled: boolean;
  107. defaultHighlightedIndex?: number;
  108. defaultInputValue?: string;
  109. /**
  110. * Currently, this does not act as a "controlled" prop, only for initial state of dropdown
  111. */
  112. isOpen?: boolean;
  113. itemToString?: (item?: T) => string;
  114. onClose?: (...args: Array<any>) => void;
  115. onMenuOpen?: () => void;
  116. onOpen?: (...args: Array<any>) => void;
  117. onSelect?: (
  118. item: T,
  119. state?: State<T>,
  120. e?: React.MouseEvent | React.KeyboardEvent
  121. ) => void;
  122. /**
  123. * Resets autocomplete input when menu closes
  124. */
  125. resetInputOnClose?: boolean;
  126. };
  127. class AutoComplete<T extends Item> extends Component<Props<T>, State<T>> {
  128. static defaultProps = defaultProps;
  129. state: State<T> = this.getInitialState();
  130. getInitialState() {
  131. const {defaultHighlightedIndex, isOpen, defaultInputValue} = this.props;
  132. return {
  133. isOpen: !!isOpen,
  134. highlightedIndex: defaultHighlightedIndex || 0,
  135. inputValue: defaultInputValue || '',
  136. selectedItem: undefined,
  137. };
  138. }
  139. componentDidMount() {
  140. this._mounted = true;
  141. }
  142. componentDidUpdate(_prevProps: Props<T>, prevState: State<T>) {
  143. // If we do NOT want to close on select, then we should not reset highlight state
  144. // when we select an item (when we select an item, `this.state.selectedItem` changes)
  145. if (this.props.closeOnSelect && this.state.selectedItem !== prevState.selectedItem) {
  146. this.resetHighlightState();
  147. }
  148. }
  149. componentWillUnmount() {
  150. this._mounted = false;
  151. window.clearTimeout(this.blurTimeout);
  152. window.clearTimeout(this.cancelCloseTimeout);
  153. }
  154. private _mounted: boolean = false;
  155. /**
  156. * Used to track keyboard navigation of items.
  157. */
  158. items = new Map<number, T>();
  159. /**
  160. * When using a virtualized list the length of the items mapping will not match
  161. * the actual item count. This stores the _real_ item count.
  162. */
  163. itemCount?: number;
  164. blurTimeout: number | undefined = undefined;
  165. cancelCloseTimeout: number | undefined = undefined;
  166. get isControlled() {
  167. return typeof this.props.isOpen !== 'undefined';
  168. }
  169. get isOpen() {
  170. return this.isControlled ? this.props.isOpen : this.state.isOpen;
  171. }
  172. /**
  173. * Resets `this.items` and `this.state.highlightedIndex`.
  174. * Should be called whenever `inputValue` changes.
  175. */
  176. resetHighlightState() {
  177. // reset items and expect `getInputProps` in child to give us a list of new items
  178. this.setState({highlightedIndex: this.props.defaultHighlightedIndex ?? 0});
  179. }
  180. makeHandleInputChange<E extends HTMLInputElement>(
  181. onChange: GetInputArgs<E>['onChange']
  182. ) {
  183. // Some inputs (e.g. input) pass in only the event to the onChange listener and
  184. // others (e.g. TextField) pass in both the value and the event to the onChange listener.
  185. // This returned function is to accomodate both kinds of input components.
  186. return (
  187. valueOrEvent: string | React.ChangeEvent<E>,
  188. event?: React.ChangeEvent<E>
  189. ) => {
  190. const value: string =
  191. event === undefined
  192. ? (valueOrEvent as React.ChangeEvent<E>).target.value
  193. : (valueOrEvent as string);
  194. const changeEvent: React.ChangeEvent<E> =
  195. event === undefined ? (valueOrEvent as React.ChangeEvent<E>) : event;
  196. // We force `isOpen: true` here because:
  197. // 1) it's possible to have menu closed but input with focus (i.e. hitting "Esc")
  198. // 2) you select an item, input still has focus, and then change input
  199. this.openMenu();
  200. this.setState({
  201. inputValue: value,
  202. });
  203. onChange?.(changeEvent);
  204. };
  205. }
  206. makeHandleInputFocus<E extends HTMLInputElement>(onFocus: GetInputArgs<E>['onFocus']) {
  207. return (e: React.FocusEvent<E>) => {
  208. this.openMenu();
  209. onFocus?.(e);
  210. };
  211. }
  212. /**
  213. * We need this delay because we want to close the menu when input
  214. * is blurred (i.e. clicking or via keyboard). However we have to handle the
  215. * case when we want to click on the dropdown and causes focus.
  216. *
  217. * Clicks outside should close the dropdown immediately via <DropdownMenu />,
  218. * however blur via keyboard will have a 200ms delay
  219. */
  220. makehandleInputBlur<E extends HTMLInputElement>(onBlur: GetInputArgs<E>['onBlur']) {
  221. return (e: React.FocusEvent<E>) => {
  222. window.clearTimeout(this.blurTimeout);
  223. this.blurTimeout = window.setTimeout(() => {
  224. this.closeMenu();
  225. onBlur?.(e);
  226. }, 200);
  227. };
  228. }
  229. // Dropdown detected click outside, we should close
  230. handleClickOutside = async () => {
  231. // Otherwise, it's possible that this gets fired multiple times
  232. // e.g. click outside triggers closeMenu and at the same time input gets blurred, so
  233. // a timer is set to close the menu
  234. window.clearTimeout(this.blurTimeout);
  235. // Wait until the current macrotask completes, in the case that the click
  236. // happened on a hovercard or some other element rendered outside of the
  237. // autocomplete, but controlled by the existence of the autocomplete, we
  238. // need to ensure any click handlers are run.
  239. await new Promise(resolve => window.setTimeout(resolve));
  240. this.closeMenu();
  241. };
  242. makeHandleInputKeydown<E extends HTMLInputElement>(
  243. onKeyDown: GetInputArgs<E>['onKeyDown']
  244. ) {
  245. return (e: React.KeyboardEvent<E>) => {
  246. const item = this.items.get(this.state.highlightedIndex);
  247. const isEnter = this.props.shouldSelectWithEnter && e.key === 'Enter';
  248. const isTab = this.props.shouldSelectWithTab && e.key === 'Tab';
  249. if (item !== undefined && (isEnter || isTab)) {
  250. if (!item.disabled) {
  251. this.handleSelect(item, e);
  252. }
  253. e.preventDefault();
  254. }
  255. if (e.key === 'ArrowUp') {
  256. this.moveHighlightedIndex(-1);
  257. e.preventDefault();
  258. }
  259. if (e.key === 'ArrowDown') {
  260. this.moveHighlightedIndex(1);
  261. e.preventDefault();
  262. }
  263. if (e.key === 'Escape') {
  264. this.closeMenu();
  265. }
  266. onKeyDown?.(e);
  267. };
  268. }
  269. makeHandleItemClick({item, index}: GetItemArgs<T>) {
  270. return (e: React.MouseEvent) => {
  271. if (item.disabled) {
  272. return;
  273. }
  274. window.clearTimeout(this.blurTimeout);
  275. this.setState({highlightedIndex: index});
  276. this.handleSelect(item, e);
  277. };
  278. }
  279. makeHandleMouseEnter({item, index}: GetItemArgs<T>) {
  280. return (_e: React.MouseEvent) => {
  281. if (item.disabled) {
  282. return;
  283. }
  284. this.setState({highlightedIndex: index});
  285. };
  286. }
  287. handleMenuMouseDown = () => {
  288. window.clearTimeout(this.cancelCloseTimeout);
  289. // Cancel close menu from input blur (mouseDown event can occur before input blur :()
  290. this.cancelCloseTimeout = window.setTimeout(() => {
  291. window.clearTimeout(this.blurTimeout);
  292. });
  293. };
  294. /**
  295. * When an item is selected via clicking or using the keyboard (e.g. pressing "Enter")
  296. */
  297. handleSelect(item: T, e: React.MouseEvent | React.KeyboardEvent) {
  298. const {onSelect, itemToString, closeOnSelect} = this.props;
  299. onSelect?.(item, this.state, e);
  300. if (closeOnSelect) {
  301. this.closeMenu();
  302. this.setState({
  303. inputValue: itemToString(item),
  304. selectedItem: item,
  305. });
  306. return;
  307. }
  308. this.setState({selectedItem: item});
  309. }
  310. moveHighlightedIndex(step: number) {
  311. let newIndex = this.state.highlightedIndex + step;
  312. // when this component is in virtualized mode, only a subset of items will
  313. // be passed down, making the map size inaccurate. instead we manually pass
  314. // the length as itemCount
  315. const listSize = this.itemCount ?? this.items.size;
  316. // Make sure new index is within bounds
  317. newIndex = Math.max(0, Math.min(newIndex, listSize - 1));
  318. this.setState({highlightedIndex: newIndex});
  319. }
  320. /**
  321. * Open dropdown menu
  322. *
  323. * This is exposed to render function
  324. */
  325. openMenu = (...args: Array<any>) => {
  326. const {onOpen, disabled} = this.props;
  327. onOpen?.(...args);
  328. if (disabled || this.isControlled) {
  329. return;
  330. }
  331. this.resetHighlightState();
  332. this.setState({
  333. isOpen: true,
  334. });
  335. };
  336. /**
  337. * Close dropdown menu
  338. *
  339. * This is exposed to render function
  340. */
  341. closeMenu = (...args: Array<any>) => {
  342. const {onClose, resetInputOnClose} = this.props;
  343. onClose?.(...args);
  344. if (this.isControlled || !this._mounted) {
  345. return;
  346. }
  347. this.setState(state => ({
  348. isOpen: false,
  349. inputValue: resetInputOnClose ? '' : state.inputValue,
  350. }));
  351. };
  352. getInputProps<E extends HTMLInputElement>(
  353. inputProps?: GetInputArgs<E>
  354. ): GetInputOutput<E> {
  355. const {onChange, onKeyDown, onFocus, onBlur, ...rest} = inputProps ?? {};
  356. return {
  357. ...rest,
  358. value: this.state.inputValue,
  359. onChange: this.makeHandleInputChange<E>(onChange),
  360. onKeyDown: this.makeHandleInputKeydown<E>(onKeyDown),
  361. onFocus: this.makeHandleInputFocus<E>(onFocus),
  362. onBlur: this.makehandleInputBlur<E>(onBlur),
  363. };
  364. }
  365. getItemProps = (itemProps: GetItemArgs<T>) => {
  366. const {item, index: _index, ...props} = itemProps ?? {};
  367. return {
  368. ...props,
  369. 'data-test-id': item['data-test-id'],
  370. onClick: this.makeHandleItemClick(itemProps),
  371. onMouseEnter: this.makeHandleMouseEnter(itemProps),
  372. };
  373. };
  374. registerVisibleItem = (index: number, item: T) => {
  375. this.items.set(index, item);
  376. return () => this.items.delete(index);
  377. };
  378. registerItemCount = (count?: number) => {
  379. this.itemCount = count;
  380. };
  381. render() {
  382. const {children, onMenuOpen, inputIsActor} = this.props;
  383. const {selectedItem, inputValue, highlightedIndex} = this.state;
  384. const isOpen = this.isOpen;
  385. return (
  386. <DropdownMenu
  387. isOpen={isOpen}
  388. onClickOutside={this.handleClickOutside}
  389. onOpen={onMenuOpen}
  390. >
  391. {dropdownMenuProps =>
  392. children({
  393. ...dropdownMenuProps,
  394. getMenuProps: <E extends Element = Element>(props?: GetMenuArgs<E>) =>
  395. dropdownMenuProps.getMenuProps({
  396. ...props,
  397. onMouseDown: this.handleMenuMouseDown,
  398. }),
  399. getInputProps: <E extends HTMLInputElement = HTMLInputElement>(
  400. props?: GetInputArgs<E>
  401. ): GetInputOutput<E> => {
  402. const inputProps = this.getInputProps<E>(props);
  403. return inputIsActor
  404. ? dropdownMenuProps.getActorProps<E>(inputProps as GetActorArgs<E>)
  405. : inputProps;
  406. },
  407. getItemProps: this.getItemProps,
  408. registerVisibleItem: this.registerVisibleItem,
  409. registerItemCount: this.registerItemCount,
  410. inputValue,
  411. selectedItem,
  412. highlightedIndex,
  413. actions: {
  414. open: this.openMenu,
  415. close: this.closeMenu,
  416. },
  417. })
  418. }
  419. </DropdownMenu>
  420. );
  421. }
  422. }
  423. export default AutoComplete;