index.tsx 17 KB

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