index.tsx 18 KB

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