index.tsx 16 KB

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