1
0

index.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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 { getUuidShort } from '@douyinfe/semi-foundation/utils/uuid';
  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. optionListId: string;
  189. private clickOutsideHandler: (e: Event) => void | null;
  190. constructor(props: AutoCompleteProps<T>) {
  191. super(props);
  192. this.foundation = new AutoCompleteFoundation(this.adapter);
  193. const initRePosKey = 1;
  194. this.state = {
  195. dropdownMinWidth: null,
  196. inputValue: '',
  197. // option list
  198. options: [],
  199. // popover visible
  200. visible: false,
  201. // current focus option index
  202. focusIndex: props.defaultActiveFirstOption ? 0 : -1,
  203. // current selected options
  204. selection: new Map(),
  205. rePosKey: initRePosKey,
  206. };
  207. this.triggerRef = React.createRef();
  208. this.optionsRef = React.createRef();
  209. this.clickOutsideHandler = null;
  210. this.optionListId = '';
  211. warning(
  212. 'triggerRender' in this.props && typeof this.props.triggerRender === 'function',
  213. `[Semi AutoComplete]
  214. - If you are using the following props: 'suffix', 'prefix', 'showClear', 'validateStatus', and 'size',
  215. please notice that they will be removed in the next major version.
  216. Please use 'componentProps' to retrieve these props instead.
  217. - If you are using 'onBlur', 'onFocus', please try to avoid using them and look for changes in the future.`
  218. );
  219. }
  220. get adapter(): AutoCompleteAdapter<AutoCompleteProps<T>, AutoCompleteState> {
  221. const keyboardAdapter = {
  222. registerKeyDown: (cb: any): void => {
  223. const keyboardEventSet = {
  224. onKeyDown: cb,
  225. };
  226. this.setState({ keyboardEventSet });
  227. },
  228. unregisterKeyDown: (cb: any): void => {
  229. this.setState({ keyboardEventSet: {} });
  230. },
  231. updateFocusIndex: (focusIndex: number): void => {
  232. this.setState({ focusIndex });
  233. },
  234. updateScrollTop: (index?: number) => {
  235. let optionClassName;
  236. /**
  237. * Unlike Select which needs to process renderOptionItem separately, when renderItem is enabled in autocomplete
  238. * the content passed by the user is still wrapped in the selector of .semi-autocomplete-option
  239. * so the selector does not need to be judged separately.
  240. */
  241. optionClassName = `.${prefixCls}-option-selected`;
  242. if (index !== undefined) {
  243. optionClassName = `.${prefixCls}-option:nth-child(${index + 1})`;
  244. }
  245. let destNode = document.querySelector(`#${prefixCls}-${this.optionListId} ${optionClassName}`) as HTMLDivElement;
  246. if (Array.isArray(destNode)) {
  247. destNode = destNode[0];
  248. }
  249. if (destNode) {
  250. const destParent = destNode.parentNode as HTMLDivElement;
  251. destParent.scrollTop = destNode.offsetTop -
  252. destParent.offsetTop -
  253. (destParent.clientHeight / 2) +
  254. (destNode.clientHeight / 2);
  255. }
  256. },
  257. };
  258. return {
  259. ...super.adapter,
  260. ...keyboardAdapter,
  261. getTriggerWidth: () => {
  262. const el = this.triggerRef.current;
  263. return el && el.getBoundingClientRect().width;
  264. },
  265. setOptionWrapperWidth: width => {
  266. this.setState({ dropdownMinWidth: width });
  267. },
  268. updateInputValue: inputValue => {
  269. this.setState({ inputValue });
  270. },
  271. toggleListVisible: isShow => {
  272. this.setState({ visible: isShow });
  273. },
  274. updateOptionList: optionList => {
  275. this.setState({ options: optionList });
  276. },
  277. updateSelection: selection => {
  278. this.setState({ selection });
  279. },
  280. notifySearch: inputValue => {
  281. this.props.onSearch(inputValue);
  282. },
  283. notifyChange: value => {
  284. this.props.onChange(value);
  285. },
  286. notifySelect: (option: StateOptionItem | string | number): void => {
  287. this.props.onSelect(option as T);
  288. },
  289. notifyDropdownVisibleChange: (isVisible: boolean): void => {
  290. this.props.onDropdownVisibleChange(isVisible);
  291. },
  292. notifyClear: () => {
  293. this.props.onClear();
  294. },
  295. notifyFocus: (event: React.FocusEvent) => {
  296. this.props.onFocus(event);
  297. },
  298. notifyBlur: (event: React.FocusEvent) => {
  299. this.props.onBlur(event);
  300. },
  301. notifyKeyDown: e => {
  302. this.props.onKeyDown(e);
  303. },
  304. rePositionDropdown: () => {
  305. let { rePosKey } = this.state;
  306. rePosKey = rePosKey + 1;
  307. this.setState({ rePosKey });
  308. },
  309. registerClickOutsideHandler: cb => {
  310. const clickOutsideHandler = (e: Event) => {
  311. const optionInstance = this.optionsRef && this.optionsRef.current;
  312. const triggerDom = this.triggerRef && this.triggerRef.current;
  313. const optionsDom = ReactDOM.findDOMNode(optionInstance);
  314. const target = e.target as Element;
  315. const path = e.composedPath && e.composedPath() || [target];
  316. if (
  317. optionsDom &&
  318. (!optionsDom.contains(target) || !optionsDom.contains(target.parentNode)) &&
  319. triggerDom &&
  320. !triggerDom.contains(target) &&
  321. !(path.includes(triggerDom) || path.includes(optionsDom))
  322. ) {
  323. cb(e);
  324. }
  325. };
  326. this.clickOutsideHandler = clickOutsideHandler;
  327. document.addEventListener('mousedown', clickOutsideHandler, false);
  328. },
  329. unregisterClickOutsideHandler: () => {
  330. if (this.clickOutsideHandler) {
  331. document.removeEventListener('mousedown', this.clickOutsideHandler, false);
  332. }
  333. },
  334. };
  335. }
  336. componentDidMount() {
  337. this.foundation.init();
  338. this.optionListId = getUuidShort();
  339. }
  340. componentWillUnmount() {
  341. this.foundation.destroy();
  342. }
  343. componentDidUpdate(prevProps: AutoCompleteProps<T>, prevState: AutoCompleteState) {
  344. if (!isEqual(this.props.data, prevProps.data)) {
  345. this.foundation.handleDataChange(this.props.data);
  346. }
  347. if (this.props.value !== prevProps.value) {
  348. this.foundation.handleValueChange(this.props.value);
  349. }
  350. }
  351. onSelect = (option: StateOptionItem, optionIndex: number, e: React.MouseEvent | React.KeyboardEvent): void => {
  352. this.foundation.handleSelect(option, optionIndex);
  353. };
  354. onSearch = (value: string): void => {
  355. this.foundation.handleSearch(value);
  356. };
  357. onBlur = (e: React.FocusEvent): void => this.foundation.handleBlur(e);
  358. onFocus = (e: React.FocusEvent): void => this.foundation.handleFocus(e);
  359. onInputClear = (): void => this.foundation.handleClear();
  360. handleInputClick = (e: React.MouseEvent): void => this.foundation.handleInputClick(e);
  361. renderInput(): React.ReactNode {
  362. const {
  363. size,
  364. prefix,
  365. insetLabel,
  366. insetLabelId,
  367. suffix,
  368. placeholder,
  369. style,
  370. className,
  371. showClear,
  372. disabled,
  373. triggerRender,
  374. validateStatus,
  375. autoFocus,
  376. value,
  377. id,
  378. clearIcon
  379. } = this.props;
  380. const { inputValue, keyboardEventSet, selection } = this.state;
  381. const useCustomTrigger = typeof triggerRender === 'function';
  382. const outerProps = {
  383. style,
  384. className: useCustomTrigger
  385. ? cls(className)
  386. : cls(
  387. {
  388. [prefixCls]: true,
  389. [`${prefixCls}-disabled`]: disabled,
  390. },
  391. className
  392. ),
  393. onClick: this.handleInputClick,
  394. ref: this.triggerRef,
  395. id,
  396. ...keyboardEventSet,
  397. // tooltip give tabindex 0 to children by default, autoComplete just need the input get focus, so outer div's tabindex set to -1
  398. tabIndex: -1,
  399. ...this.getDataAttr(this.props)
  400. };
  401. const innerProps = {
  402. disabled,
  403. placeholder,
  404. autoFocus: autoFocus,
  405. onChange: this.onSearch,
  406. onClear: this.onInputClear,
  407. 'aria-label': this.props['aria-label'],
  408. 'aria-labelledby': this.props['aria-labelledby'],
  409. 'aria-invalid': this.props['aria-invalid'],
  410. 'aria-errormessage': this.props['aria-errormessage'],
  411. 'aria-describedby': this.props['aria-describedby'],
  412. 'aria-required': this.props['aria-required'],
  413. // TODO: remove in next major version
  414. suffix,
  415. prefix: prefix || insetLabel,
  416. insetLabelId,
  417. showClear,
  418. validateStatus,
  419. size,
  420. onBlur: this.onBlur,
  421. onFocus: this.onFocus,
  422. clearIcon,
  423. };
  424. return (
  425. <div {...outerProps}>
  426. {typeof triggerRender === 'function' ? (
  427. <Trigger
  428. {...innerProps}
  429. inputValue={(typeof value !== 'undefined' ? value : inputValue) as string}
  430. value={Array.from(selection.values())}
  431. triggerRender={triggerRender}
  432. componentName="AutoComplete"
  433. componentProps={{ ...this.props }}
  434. />
  435. ) : (
  436. <Input {...innerProps} value={typeof value !== 'undefined' ? value : inputValue} />
  437. )}
  438. </div>
  439. );
  440. }
  441. renderLoading() {
  442. const loadingWrapperCls = `${prefixCls}-loading-wrapper`;
  443. return (
  444. <div className={loadingWrapperCls}>
  445. <Spin />
  446. </div>
  447. );
  448. }
  449. renderOption(option: StateOptionItem, optionIndex: number): React.ReactNode {
  450. const { focusIndex } = this.state;
  451. const isFocused = optionIndex === focusIndex;
  452. return (
  453. <Option
  454. showTick={false}
  455. onSelect={(v: StateOptionItem, e: React.MouseEvent | React.KeyboardEvent) => this.onSelect(v, optionIndex, e)}
  456. // selected={selection.has(option.label)}
  457. focused={isFocused}
  458. onMouseEnter={() => this.foundation.handleOptionMouseEnter(optionIndex)}
  459. key={option.key || option.label + option.value + optionIndex}
  460. {...option}
  461. >
  462. {option.label}
  463. </Option>
  464. );
  465. }
  466. renderOptionList(): React.ReactNode {
  467. const { maxHeight, dropdownStyle, dropdownClassName, loading, emptyContent } = this.props;
  468. const { options, dropdownMinWidth } = this.state;
  469. const listCls = cls(
  470. {
  471. [`${prefixCls}-option-list`]: true,
  472. },
  473. dropdownClassName
  474. );
  475. let optionsNode;
  476. if (options.length === 0) {
  477. optionsNode = emptyContent;
  478. } else {
  479. optionsNode = options.filter(option => option.show).map((option, i) => this.renderOption(option, i));
  480. }
  481. const style = {
  482. maxHeight: maxHeight,
  483. minWidth: dropdownMinWidth,
  484. ...dropdownStyle,
  485. };
  486. return (
  487. <div
  488. className={listCls}
  489. role="listbox"
  490. style={style}
  491. id={`${prefixCls}-${this.optionListId}`}
  492. >
  493. {!loading ? optionsNode : this.renderLoading()}
  494. </div>
  495. );
  496. }
  497. render(): React.ReactNode {
  498. const {
  499. position,
  500. motion,
  501. zIndex,
  502. mouseEnterDelay,
  503. mouseLeaveDelay,
  504. autoAdjustOverflow,
  505. stopPropagation,
  506. getPopupContainer,
  507. } = this.props;
  508. const { visible, rePosKey } = this.state;
  509. const input = this.renderInput();
  510. const optionList = this.renderOptionList();
  511. return (
  512. <Popover
  513. mouseEnterDelay={mouseEnterDelay}
  514. mouseLeaveDelay={mouseLeaveDelay}
  515. autoAdjustOverflow={autoAdjustOverflow}
  516. trigger="custom"
  517. motion={motion}
  518. visible={visible}
  519. content={optionList}
  520. position={position}
  521. ref={this.optionsRef as any}
  522. // TransformFromCenter TODO: need to confirm
  523. zIndex={zIndex}
  524. stopPropagation={stopPropagation}
  525. getPopupContainer={getPopupContainer}
  526. rePosKey={rePosKey}
  527. >
  528. {input}
  529. </Popover>
  530. );
  531. }
  532. }
  533. export default AutoComplete;