index.tsx 16 KB

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