index.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. /* eslint-disable @typescript-eslint/ban-types, max-len */
  2. import React, { ReactNode } from 'react';
  3. import PropTypes from 'prop-types';
  4. import cls from 'classnames';
  5. import { isEqual, noop } from 'lodash';
  6. import { strings, cssClasses } from '@douyinfe/semi-foundation/autoComplete/constants';
  7. import AutoCompleteFoundation, { AutoCompleteAdapter, StateOptionItem, DataItem } from '@douyinfe/semi-foundation/autoComplete/foundation';
  8. import { numbers as popoverNumbers } from '@douyinfe/semi-foundation/popover/constants';
  9. import getDataAttr from '@douyinfe/semi-foundation/utils/getDataAttr';
  10. import BaseComponent, { ValidateStatus } from '../_base/baseComponent';
  11. import { Position } from '../tooltip';
  12. import Spin from '../spin';
  13. import Popover from '../popover';
  14. import Input from '../input';
  15. import Trigger from '../trigger';
  16. import Option from './option';
  17. import warning from '@douyinfe/semi-foundation/utils/warning';
  18. import '@douyinfe/semi-foundation/autoComplete/autoComplete.scss';
  19. import ReactDOM from 'react-dom';
  20. const prefixCls = cssClasses.PREFIX;
  21. const sizeSet = strings.SIZE;
  22. const positionSet = strings.POSITION;
  23. const statusSet = strings.STATUS;
  24. /**
  25. * AutoComplete is an enhanced Input (candidates suggest that users can choose or not),
  26. * and the Select positioning that supports Search is still a selector.
  27. * 1. When you click to expand, Select will clear all input values, but AutoComplete will not
  28. * 2. AutoComplete's renderSelectedItem only supports simple string returns, while Select's renderSelectedItem can return ReactNode
  29. * 3. Select props.value supports incoming object, but autoComplete only supports string (because the value needs to be displayed in Input)
  30. */
  31. export interface BaseDataItem extends DataItem {
  32. label?: React.ReactNode
  33. }
  34. export type AutoCompleteItems = BaseDataItem | string | number;
  35. export interface AutoCompleteProps<T extends AutoCompleteItems> {
  36. 'aria-describedby'?: React.AriaAttributes['aria-describedby'];
  37. 'aria-errormessage'?: React.AriaAttributes['aria-errormessage'];
  38. 'aria-invalid'?: React.AriaAttributes['aria-invalid'];
  39. 'aria-label'?: React.AriaAttributes['aria-label'];
  40. 'aria-labelledby'?: React.AriaAttributes['aria-labelledby'];
  41. 'aria-required'?: React.AriaAttributes['aria-required'];
  42. autoAdjustOverflow?: boolean;
  43. autoFocus?: boolean;
  44. className?: string;
  45. clearIcon?: ReactNode;
  46. children?: ReactNode;
  47. data?: T[];
  48. disabled?: boolean;
  49. defaultOpen?: boolean;
  50. defaultValue?: T;
  51. defaultActiveFirstOption?: boolean;
  52. dropdownMatchSelectWidth?: boolean;
  53. dropdownClassName?: string;
  54. dropdownStyle?: React.CSSProperties;
  55. emptyContent?: React.ReactNode;
  56. getPopupContainer?: () => HTMLElement;
  57. insetLabel?: React.ReactNode;
  58. insetLabelId?: string;
  59. id?: string;
  60. loading?: boolean;
  61. motion?: boolean;
  62. maxHeight?: string | number;
  63. mouseEnterDelay?: number;
  64. mouseLeaveDelay?: number;
  65. onFocus?: (e: React.FocusEvent) => void;
  66. onBlur?: (e: React.FocusEvent) => void;
  67. onChange?: (value: string | number) => void;
  68. onSearch?: (inputValue: string) => void;
  69. onSelect?: (value: T) => void;
  70. onClear?: () => void;
  71. onChangeWithObject?: boolean;
  72. onSelectWithObject?: boolean;
  73. onDropdownVisibleChange?: (visible: boolean) => void;
  74. onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  75. prefix?: React.ReactNode;
  76. placeholder?: string;
  77. position?: Position;
  78. renderItem?: (option: T) => React.ReactNode;
  79. renderSelectedItem?: (option: T) => string;
  80. size?: 'small' | 'default' | 'large';
  81. style?: React.CSSProperties;
  82. suffix?: React.ReactNode;
  83. showClear?: boolean;
  84. triggerRender?: (props?: any) => React.ReactNode;
  85. stopPropagation?: boolean | string;
  86. value?: string | number;
  87. validateStatus?: ValidateStatus;
  88. zIndex?: number
  89. }
  90. interface KeyboardEventType {
  91. onKeyDown?: React.KeyboardEventHandler
  92. }
  93. interface AutoCompleteState {
  94. dropdownMinWidth: null | number;
  95. inputValue: string | undefined | number;
  96. options: StateOptionItem[];
  97. visible: boolean;
  98. focusIndex: number;
  99. selection: Map<any, any>;
  100. rePosKey: number;
  101. keyboardEventSet?: KeyboardEventType
  102. }
  103. class AutoComplete<T extends AutoCompleteItems> extends BaseComponent<AutoCompleteProps<T>, AutoCompleteState> {
  104. static propTypes = {
  105. 'aria-label': PropTypes.string,
  106. 'aria-labelledby': PropTypes.string,
  107. 'aria-invalid': PropTypes.bool,
  108. 'aria-errormessage': PropTypes.string,
  109. 'aria-describedby': PropTypes.string,
  110. 'aria-required': PropTypes.bool,
  111. autoFocus: PropTypes.bool,
  112. autoAdjustOverflow: PropTypes.bool,
  113. className: PropTypes.string,
  114. clearIcon: PropTypes.node,
  115. children: PropTypes.node,
  116. data: PropTypes.array,
  117. defaultOpen: PropTypes.bool,
  118. defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  119. defaultActiveFirstOption: PropTypes.bool,
  120. disabled: PropTypes.bool,
  121. dropdownMatchSelectWidth: PropTypes.bool,
  122. dropdownClassName: PropTypes.string,
  123. dropdownStyle: PropTypes.object,
  124. emptyContent: PropTypes.node,
  125. id: PropTypes.string,
  126. insetLabel: PropTypes.node,
  127. insetLabelId: PropTypes.string,
  128. onSearch: PropTypes.func,
  129. onSelect: PropTypes.func,
  130. onClear: PropTypes.func,
  131. onBlur: PropTypes.func,
  132. onFocus: PropTypes.func,
  133. onChange: PropTypes.func,
  134. onKeyDown: PropTypes.func,
  135. position: PropTypes.oneOf(positionSet),
  136. placeholder: PropTypes.string,
  137. prefix: PropTypes.node,
  138. onChangeWithObject: PropTypes.bool,
  139. onSelectWithObject: PropTypes.bool,
  140. renderItem: PropTypes.func,
  141. renderSelectedItem: PropTypes.func,
  142. suffix: PropTypes.node,
  143. showClear: PropTypes.bool,
  144. size: PropTypes.oneOf(sizeSet),
  145. style: PropTypes.object,
  146. stopPropagation: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
  147. maxHeight: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  148. mouseEnterDelay: PropTypes.number,
  149. mouseLeaveDelay: PropTypes.number,
  150. motion: PropTypes.oneOfType([PropTypes.bool, PropTypes.func, PropTypes.object]),
  151. getPopupContainer: PropTypes.func,
  152. triggerRender: PropTypes.func,
  153. value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  154. validateStatus: PropTypes.oneOf(statusSet),
  155. zIndex: PropTypes.number,
  156. };
  157. static Option = Option;
  158. static defaultProps = {
  159. stopPropagation: true,
  160. motion: true,
  161. zIndex: popoverNumbers.DEFAULT_Z_INDEX,
  162. position: 'bottomLeft' as const,
  163. data: [] as [],
  164. showClear: false,
  165. size: 'default' as const,
  166. onFocus: noop,
  167. onSearch: noop,
  168. onClear: noop,
  169. onBlur: noop,
  170. onSelect: noop,
  171. onChange: noop,
  172. onSelectWithObject: false,
  173. onDropdownVisibleChange: noop,
  174. defaultActiveFirstOption: false,
  175. dropdownMatchSelectWidth: true,
  176. loading: false,
  177. maxHeight: 300,
  178. validateStatus: 'default' as const,
  179. autoFocus: false,
  180. emptyContent: null as null,
  181. onKeyDown: noop,
  182. // onPressEnter: () => undefined,
  183. // defaultOpen: false,
  184. };
  185. triggerRef: React.RefObject<HTMLDivElement> | null;
  186. optionsRef: React.RefObject<HTMLDivElement> | null;
  187. private clickOutsideHandler: (e: Event) => void | null;
  188. constructor(props: AutoCompleteProps<T>) {
  189. super(props);
  190. this.foundation = new AutoCompleteFoundation(this.adapter);
  191. const initRePosKey = 1;
  192. this.state = {
  193. dropdownMinWidth: null,
  194. inputValue: '',
  195. // option list
  196. options: [],
  197. // popover visible
  198. visible: false,
  199. // current focus option index
  200. focusIndex: props.defaultActiveFirstOption ? 0 : -1,
  201. // current selected options
  202. selection: new Map(),
  203. rePosKey: initRePosKey,
  204. };
  205. this.triggerRef = React.createRef();
  206. this.optionsRef = React.createRef();
  207. this.clickOutsideHandler = null;
  208. warning(
  209. 'triggerRender' in this.props && typeof this.props.triggerRender === 'function',
  210. `[Semi AutoComplete]
  211. - If you are using the following props: 'suffix', 'prefix', 'showClear', 'validateStatus', and 'size',
  212. please notice that they will be removed in the next major version.
  213. Please use 'componentProps' to retrieve these props instead.
  214. - If you are using 'onBlur', 'onFocus', please try to avoid using them and look for changes in the future.`
  215. );
  216. }
  217. get adapter(): AutoCompleteAdapter<AutoCompleteProps<T>, AutoCompleteState> {
  218. const keyboardAdapter = {
  219. registerKeyDown: (cb: any): void => {
  220. const keyboardEventSet = {
  221. onKeyDown: cb,
  222. };
  223. this.setState({ keyboardEventSet });
  224. },
  225. unregisterKeyDown: (cb: any): void => {
  226. this.setState({ keyboardEventSet: {} });
  227. },
  228. updateFocusIndex: (focusIndex: number): void => {
  229. this.setState({ focusIndex });
  230. },
  231. };
  232. return {
  233. ...super.adapter,
  234. ...keyboardAdapter,
  235. getTriggerWidth: () => {
  236. const el = this.triggerRef.current;
  237. return el && el.getBoundingClientRect().width;
  238. },
  239. setOptionWrapperWidth: width => {
  240. this.setState({ dropdownMinWidth: width });
  241. },
  242. updateInputValue: inputValue => {
  243. this.setState({ inputValue });
  244. },
  245. toggleListVisible: isShow => {
  246. this.setState({ visible: isShow });
  247. },
  248. updateOptionList: optionList => {
  249. this.setState({ options: optionList });
  250. },
  251. updateSelection: selection => {
  252. this.setState({ selection });
  253. },
  254. notifySearch: inputValue => {
  255. this.props.onSearch(inputValue);
  256. },
  257. notifyChange: value => {
  258. this.props.onChange(value);
  259. },
  260. notifySelect: (option: StateOptionItem | string | number): void => {
  261. this.props.onSelect(option as T);
  262. },
  263. notifyDropdownVisibleChange: (isVisible: boolean): void => {
  264. this.props.onDropdownVisibleChange(isVisible);
  265. },
  266. notifyClear: () => {
  267. this.props.onClear();
  268. },
  269. notifyFocus: (event: React.FocusEvent) => {
  270. this.props.onFocus(event);
  271. },
  272. notifyBlur: (event: React.FocusEvent) => {
  273. this.props.onBlur(event);
  274. },
  275. notifyKeyDown: e => {
  276. this.props.onKeyDown(e);
  277. },
  278. rePositionDropdown: () => {
  279. let { rePosKey } = this.state;
  280. rePosKey = rePosKey + 1;
  281. this.setState({ rePosKey });
  282. },
  283. registerClickOutsideHandler: cb => {
  284. const clickOutsideHandler = (e: Event) => {
  285. const optionInstance = this.optionsRef && this.optionsRef.current;
  286. const triggerDom = this.triggerRef && this.triggerRef.current;
  287. const optionsDom = ReactDOM.findDOMNode(optionInstance);
  288. const target = e.target as Element;
  289. if (
  290. optionsDom &&
  291. (!optionsDom.contains(target) || !optionsDom.contains(target.parentNode)) &&
  292. triggerDom &&
  293. !triggerDom.contains(target)
  294. ) {
  295. cb(e);
  296. }
  297. };
  298. this.clickOutsideHandler = clickOutsideHandler;
  299. document.addEventListener('mousedown', clickOutsideHandler, false);
  300. },
  301. unregisterClickOutsideHandler: () => {
  302. if (this.clickOutsideHandler) {
  303. document.removeEventListener('mousedown', this.clickOutsideHandler, false);
  304. }
  305. },
  306. };
  307. }
  308. componentDidMount() {
  309. this.foundation.init();
  310. }
  311. componentWillUnmount() {
  312. this.foundation.destroy();
  313. }
  314. componentDidUpdate(prevProps: AutoCompleteProps<T>, prevState: AutoCompleteState) {
  315. if (!isEqual(this.props.data, prevProps.data)) {
  316. this.foundation.handleDataChange(this.props.data);
  317. }
  318. if (this.props.value !== prevProps.value) {
  319. this.foundation.handleValueChange(this.props.value);
  320. }
  321. }
  322. onSelect = (option: StateOptionItem, optionIndex: number, e: React.MouseEvent | React.KeyboardEvent): void => {
  323. this.foundation.handleSelect(option, optionIndex);
  324. };
  325. onSearch = (value: string): void => {
  326. this.foundation.handleSearch(value);
  327. };
  328. onBlur = (e: React.FocusEvent): void => this.foundation.handleBlur(e);
  329. onFocus = (e: React.FocusEvent): void => this.foundation.handleFocus(e);
  330. onInputClear = (): void => this.foundation.handleClear();
  331. handleInputClick = (e: React.MouseEvent): void => this.foundation.handleInputClick(e);
  332. renderInput(): React.ReactNode {
  333. const {
  334. size,
  335. prefix,
  336. insetLabel,
  337. insetLabelId,
  338. suffix,
  339. placeholder,
  340. style,
  341. className,
  342. showClear,
  343. disabled,
  344. triggerRender,
  345. validateStatus,
  346. autoFocus,
  347. value,
  348. id,
  349. clearIcon
  350. } = this.props;
  351. const { inputValue, keyboardEventSet, selection } = this.state;
  352. const useCustomTrigger = typeof triggerRender === 'function';
  353. const outerProps = {
  354. style,
  355. className: useCustomTrigger
  356. ? cls(className)
  357. : cls(
  358. {
  359. [prefixCls]: true,
  360. [`${prefixCls}-disabled`]: disabled,
  361. },
  362. className
  363. ),
  364. onClick: this.handleInputClick,
  365. ref: this.triggerRef,
  366. id,
  367. ...keyboardEventSet,
  368. // tooltip give tabindex 0 to children by default, autoComplete just need the input get focus, so outer div's tabindex set to -1
  369. tabIndex: -1,
  370. ...this.getDataAttr(this.props)
  371. };
  372. const innerProps = {
  373. disabled,
  374. placeholder,
  375. autofocus: autoFocus,
  376. onChange: this.onSearch,
  377. onClear: this.onInputClear,
  378. 'aria-label': this.props['aria-label'],
  379. 'aria-labelledby': this.props['aria-labelledby'],
  380. 'aria-invalid': this.props['aria-invalid'],
  381. 'aria-errormessage': this.props['aria-errormessage'],
  382. 'aria-describedby': this.props['aria-describedby'],
  383. 'aria-required': this.props['aria-required'],
  384. // TODO: remove in next major version
  385. suffix,
  386. prefix: prefix || insetLabel,
  387. insetLabelId,
  388. showClear,
  389. validateStatus,
  390. size,
  391. onBlur: this.onBlur,
  392. onFocus: this.onFocus,
  393. clearIcon,
  394. };
  395. return (
  396. <div {...outerProps}>
  397. {typeof triggerRender === 'function' ? (
  398. <Trigger
  399. {...innerProps}
  400. inputValue={(typeof value !== 'undefined' ? value : inputValue) as string}
  401. value={Array.from(selection.values())}
  402. triggerRender={triggerRender}
  403. componentName="AutoComplete"
  404. componentProps={{ ...this.props }}
  405. />
  406. ) : (
  407. <Input {...innerProps} value={typeof value !== 'undefined' ? value : inputValue} />
  408. )}
  409. </div>
  410. );
  411. }
  412. renderLoading() {
  413. const loadingWrapperCls = `${prefixCls}-loading-wrapper`;
  414. return (
  415. <div className={loadingWrapperCls}>
  416. <Spin />
  417. </div>
  418. );
  419. }
  420. renderOption(option: StateOptionItem, optionIndex: number): React.ReactNode {
  421. const { focusIndex } = this.state;
  422. const isFocused = optionIndex === focusIndex;
  423. return (
  424. <Option
  425. showTick={false}
  426. onSelect={(v: StateOptionItem, e: React.MouseEvent | React.KeyboardEvent) => this.onSelect(v, optionIndex, e)}
  427. // selected={selection.has(option.label)}
  428. focused={isFocused}
  429. onMouseEnter={() => this.foundation.handleOptionMouseEnter(optionIndex)}
  430. key={option.key || option.label + option.value + optionIndex}
  431. {...option}
  432. >
  433. {option.label}
  434. </Option>
  435. );
  436. }
  437. renderOptionList(): React.ReactNode {
  438. const { maxHeight, dropdownStyle, dropdownClassName, loading, emptyContent } = this.props;
  439. const { options, dropdownMinWidth } = this.state;
  440. const listCls = cls(
  441. {
  442. [`${prefixCls}-option-list`]: true,
  443. },
  444. dropdownClassName
  445. );
  446. let optionsNode;
  447. if (options.length === 0) {
  448. optionsNode = emptyContent;
  449. } else {
  450. optionsNode = options.filter(option => option.show).map((option, i) => this.renderOption(option, i));
  451. }
  452. const style = {
  453. maxHeight: maxHeight,
  454. minWidth: dropdownMinWidth,
  455. ...dropdownStyle,
  456. };
  457. return (
  458. <div className={listCls} role="listbox" style={style}>
  459. {!loading ? optionsNode : this.renderLoading()}
  460. </div>
  461. );
  462. }
  463. render(): React.ReactNode {
  464. const {
  465. position,
  466. motion,
  467. zIndex,
  468. mouseEnterDelay,
  469. mouseLeaveDelay,
  470. autoAdjustOverflow,
  471. stopPropagation,
  472. getPopupContainer,
  473. } = this.props;
  474. const { visible, rePosKey } = this.state;
  475. const input = this.renderInput();
  476. const optionList = this.renderOptionList();
  477. return (
  478. <Popover
  479. mouseEnterDelay={mouseEnterDelay}
  480. mouseLeaveDelay={mouseLeaveDelay}
  481. autoAdjustOverflow={autoAdjustOverflow}
  482. trigger="custom"
  483. motion={motion}
  484. visible={visible}
  485. content={optionList}
  486. position={position}
  487. ref={this.optionsRef as any}
  488. // TransformFromCenter TODO: need to confirm
  489. zIndex={zIndex}
  490. stopPropagation={stopPropagation}
  491. getPopupContainer={getPopupContainer}
  492. rePosKey={rePosKey}
  493. >
  494. {input}
  495. </Popover>
  496. );
  497. }
  498. }
  499. export default AutoComplete;