index.tsx 18 KB

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