index.tsx 18 KB

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