index.tsx 18 KB

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