index.tsx 19 KB

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