index.tsx 18 KB

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