index.tsx 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. /* eslint-disable max-len */
  2. /* eslint-disable max-lines-per-function */
  3. import React, { Fragment, MouseEvent, ReactInstance } from 'react';
  4. import ReactDOM from 'react-dom';
  5. import cls from 'classnames';
  6. import PropTypes from 'prop-types';
  7. import ConfigContext from '../configProvider/context';
  8. import SelectFoundation, { SelectAdapter } from '@douyinfe/semi-foundation/select/foundation';
  9. import { cssClasses, strings, numbers } from '@douyinfe/semi-foundation/select/constants';
  10. import BaseComponent, { ValidateStatus } from '../_base/baseComponent';
  11. import { isEqual, isString, noop } from 'lodash-es';
  12. import Tag from '../tag/index';
  13. import TagGroup from '../tag/group';
  14. import LocaleCosumer from '../locale/localeConsumer';
  15. import Popover from '../popover/index';
  16. import { numbers as popoverNumbers } from '@douyinfe/semi-foundation/popover/constants';
  17. import { FixedSizeList as List } from 'react-window';
  18. import { getOptionsFromGroup } from './utils';
  19. import VirtualRow from './virtualRow';
  20. import Input from '../input/index';
  21. import Option, { OptionProps } from './option';
  22. import OptionGroup from './optionGroup';
  23. import Spin from '../spin';
  24. import Trigger from '../trigger';
  25. import { IconChevronDown, IconClear } from '@douyinfe/semi-icons';
  26. import { isSemiIcon } from '../_utils';
  27. import warning from '@douyinfe/semi-foundation/utils/warning';
  28. import '@douyinfe/semi-foundation/select/select.scss';
  29. import '@douyinfe/semi-foundation/select/option.scss';
  30. import { Locale } from '../locale/interface';
  31. import { Position, TooltipProps } from '../tooltip';
  32. export { OptionProps } from './option';
  33. export { OptionGroupProps } from './optionGroup';
  34. export { VirtualRowProps } from './virtualRow';
  35. const prefixcls = cssClasses.PREFIX;
  36. const key = 0;
  37. type OnChangeValueType = string | number | Record<string, any>;
  38. export interface optionRenderProps {
  39. key?: any;
  40. label?: string | React.ReactNode | number;
  41. value?: string | number;
  42. style?: React.CSSProperties;
  43. className?: string;
  44. selected?: boolean;
  45. focused?: boolean;
  46. show?: boolean;
  47. disabled?: boolean;
  48. onMouseEnter?: (e: React.MouseEvent) => any;
  49. onClick?: (e: React.MouseEvent) => any;
  50. [x: string]: any;
  51. }
  52. export interface selectMethod {
  53. clearInput?: () => void;
  54. selectAll?: () => void;
  55. deselectAll?: () => void;
  56. focus?: () => void;
  57. close?: () => void;
  58. open?: () => void;
  59. }
  60. export type SelectSize = 'small' | 'large' | 'default';
  61. export interface virtualListProps {
  62. itemSize?: number;
  63. height?: number;
  64. width?: string | number;
  65. }
  66. export type RenderSingleSelectedItemFn = (optionNode: Record<string, any>) => React.ReactNode;
  67. export type RenderMultipleSelectedItemFn = (optionNode: Record<string, any>, multipleProps: { index: number; disabled: boolean; onClose: (tagContent: React.ReactNode, e: MouseEvent) => void }) => { isRenderInTag: boolean; content: React.ReactNode };
  68. export type RenderSelectedItemFn = RenderSingleSelectedItemFn | RenderMultipleSelectedItemFn;
  69. export type SelectProps = {
  70. autoFocus?: boolean;
  71. arrowIcon?: React.ReactNode;
  72. defaultValue?: string | number | any[] | Record<string, any>;
  73. value?: string | number | any[] | Record<string, any>;
  74. placeholder?: React.ReactNode;
  75. onChange?: (value: SelectProps['value']) => void;
  76. multiple?: boolean;
  77. filter?: boolean | ((inpueValue: string, option: OptionProps) => boolean);
  78. max?: number;
  79. maxTagCount?: number;
  80. maxHeight?: string | number;
  81. style?: React.CSSProperties;
  82. className?: string;
  83. size?: SelectSize;
  84. disabled?: boolean;
  85. emptyContent?: React.ReactNode;
  86. onDropdownVisibleChange?: (visible: boolean) => void;
  87. zIndex?: number;
  88. position?: Position;
  89. onSearch?: (value: string) => void;
  90. dropdownClassName?: string;
  91. dropdownStyle?: React.CSSProperties;
  92. outerTopSlot?: React.ReactNode;
  93. innerTopSlot?: React.ReactNode;
  94. outerBottomSlot?: React.ReactNode;
  95. innerBottomSlot?: React.ReactNode;
  96. optionList?: OptionProps[];
  97. dropdownMatchSelectWidth?: boolean;
  98. loading?: boolean;
  99. defaultOpen?: boolean;
  100. validateStatus?: ValidateStatus;
  101. defaultActiveFirstOption?: boolean;
  102. onChangeWithObject?: boolean;
  103. suffix?: React.ReactNode;
  104. prefix?: React.ReactNode;
  105. insetLabel?: React.ReactNode;
  106. showClear?: boolean;
  107. showArrow?: boolean;
  108. renderSelectedItem?: RenderSelectedItemFn;
  109. renderCreateItem?: (inputValue: OptionProps['value'], focus: boolean) => React.ReactNode;
  110. renderOptionItem?: (props: optionRenderProps) => React.ReactNode;
  111. onMouseEnter?: (e: React.MouseEvent) => any;
  112. onMouseLeave?: (e: React.MouseEvent) => any;
  113. clickToHide?: boolean;
  114. onExceed?: (option: OptionProps) => void;
  115. onCreate?: (option: OptionProps) => void;
  116. remote?: boolean;
  117. onDeselect?: (value: SelectProps['value'], option: Record<string, any>) => void;
  118. onSelect?: (value: SelectProps['value'], option: Record<string, any>) => void;
  119. allowCreate?: boolean;
  120. triggerRender?: (props?: any) => React.ReactNode;
  121. onClear?: () => void;
  122. virtualize?: virtualListProps;
  123. onFocus?: (e: React.FocusEvent) => void;
  124. onBlur?: (e: React.FocusEvent) => void;
  125. onListScroll?: (e: React.UIEvent<HTMLDivElement>) => void;
  126. children?: React.ReactNode;
  127. } & Pick<
  128. TooltipProps,
  129. | 'spacing'
  130. | 'getPopupContainer'
  131. | 'motion'
  132. | 'autoAdjustOverflow'
  133. | 'mouseLeaveDelay'
  134. | 'mouseEnterDelay'
  135. | 'stopPropagation'
  136. > & React.RefAttributes<any>;
  137. export interface SelectState {
  138. isOpen: boolean;
  139. isFocus: boolean;
  140. options: Array<OptionProps>;
  141. selections: Map<OptionProps['label'], any>; // A collection of all currently selected items, k: label, v: {value,... otherProps}
  142. dropdownMinWidth: number;
  143. optionKey: number;
  144. inputValue: string;
  145. showInput: boolean;
  146. focusIndex: number;
  147. keyboardEventSet: any; // {}
  148. optionGroups: Array<any>;
  149. isHovering: boolean;
  150. }
  151. // Notes: Use the label of the option as the identifier, that is, the option in Select, the value is allowed to be the same, but the label must be unique
  152. class Select extends BaseComponent<SelectProps, SelectState> {
  153. static contextType = ConfigContext;
  154. static Option = Option;
  155. static OptGroup = OptionGroup;
  156. static propTypes = {
  157. autoFocus: PropTypes.bool,
  158. children: PropTypes.node,
  159. defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.array, PropTypes.object]),
  160. value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.array, PropTypes.object]),
  161. placeholder: PropTypes.node,
  162. onChange: PropTypes.func,
  163. multiple: PropTypes.bool,
  164. // Whether to turn on the input box filtering function, when it is a function, it represents a custom filtering function
  165. filter: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
  166. // How many tags can you choose?
  167. max: PropTypes.number,
  168. // How many tabs are displayed at most, and the rest are displayed in + N
  169. maxTagCount: PropTypes.number,
  170. maxHeight: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  171. style: PropTypes.object,
  172. className: PropTypes.string,
  173. size: PropTypes.oneOf<SelectProps['size']>(strings.SIZE_SET),
  174. disabled: PropTypes.bool,
  175. emptyContent: PropTypes.node,
  176. onDropdownVisibleChange: PropTypes.func,
  177. zIndex: PropTypes.number,
  178. position: PropTypes.oneOf(strings.POSITION_SET),
  179. onSearch: PropTypes.func,
  180. getPopupContainer: PropTypes.func,
  181. dropdownClassName: PropTypes.string,
  182. dropdownStyle: PropTypes.object,
  183. outerTopSlot: PropTypes.node,
  184. innerTopSlot: PropTypes.node,
  185. outerBottomSlot: PropTypes.node,
  186. innerBottomSlot: PropTypes.node, // Options slot
  187. optionList: PropTypes.array,
  188. dropdownMatchSelectWidth: PropTypes.bool,
  189. loading: PropTypes.bool,
  190. defaultOpen: PropTypes.bool,
  191. validateStatus: PropTypes.oneOf(strings.STATUS),
  192. defaultActiveFirstOption: PropTypes.bool,
  193. triggerRender: PropTypes.func,
  194. stopPropagation: PropTypes.bool,
  195. // motion doesn't need to be exposed
  196. motion: PropTypes.oneOfType([PropTypes.func, PropTypes.bool, PropTypes.object]),
  197. onChangeWithObject: PropTypes.bool,
  198. suffix: PropTypes.node,
  199. prefix: PropTypes.node,
  200. insetLabel: PropTypes.node,
  201. showClear: PropTypes.bool,
  202. showArrow: PropTypes.bool,
  203. renderSelectedItem: PropTypes.func,
  204. allowCreate: PropTypes.bool,
  205. renderCreateItem: PropTypes.func,
  206. onMouseEnter: PropTypes.func,
  207. onMouseLeave: PropTypes.func,
  208. clickToHide: PropTypes.bool,
  209. onExceed: PropTypes.func,
  210. onCreate: PropTypes.func,
  211. remote: PropTypes.bool,
  212. onDeselect: PropTypes.func,
  213. // The main difference between onSelect and onChange is that when multiple selections are selected, onChange contains all options, while onSelect only contains items for the current operation
  214. onSelect: PropTypes.func,
  215. autoAdjustOverflow: PropTypes.bool,
  216. mouseEnterDelay: PropTypes.number,
  217. mouseLeaveDelay: PropTypes.number,
  218. spacing: PropTypes.number,
  219. onBlur: PropTypes.func,
  220. onFocus: PropTypes.func,
  221. onClear: PropTypes.func,
  222. virtualize: PropTypes.object,
  223. renderOptionItem: PropTypes.func,
  224. onListScroll: PropTypes.func,
  225. arrowIcon: PropTypes.node,
  226. // open: PropTypes.bool,
  227. // tagClosable: PropTypes.bool,
  228. };
  229. static defaultProps: Partial<SelectProps> = {
  230. stopPropagation: true,
  231. motion: true,
  232. zIndex: popoverNumbers.DEFAULT_Z_INDEX,
  233. // position: 'bottomLeft',
  234. filter: false,
  235. multiple: false,
  236. disabled: false,
  237. defaultOpen: false,
  238. allowCreate: false,
  239. placeholder: '',
  240. onDropdownVisibleChange: noop,
  241. onChangeWithObject: false,
  242. onChange: noop,
  243. onSearch: noop,
  244. onMouseEnter: noop,
  245. onMouseLeave: noop,
  246. onDeselect: noop,
  247. onSelect: noop,
  248. onCreate: noop,
  249. onExceed: noop,
  250. onFocus: noop,
  251. onBlur: noop,
  252. onClear: noop,
  253. onListScroll: noop,
  254. maxHeight: 300,
  255. dropdownMatchSelectWidth: true,
  256. defaultActiveFirstOption: false,
  257. showArrow: true,
  258. showClear: false,
  259. remote: false,
  260. autoAdjustOverflow: true,
  261. arrowIcon: <IconChevronDown />
  262. // Radio selection is different from the default renderSelectedItem for multiple selection, so it is not declared here
  263. // renderSelectedItem: (optionNode) => optionNode.label,
  264. // The default creator rendering is related to i18, so it is not declared here
  265. // renderCreateItem: (input) => input
  266. };
  267. inputRef: React.RefObject<HTMLInputElement>;
  268. triggerRef: React.RefObject<HTMLDivElement>;
  269. optionsRef: React.RefObject<any>;
  270. clickOutsideHandler: (e: MouseEvent) => void;
  271. foundation: SelectFoundation;
  272. constructor(props: SelectProps) {
  273. super(props);
  274. this.state = {
  275. isOpen: false,
  276. isFocus: false,
  277. options: [], // All options
  278. selections: new Map(), // A collection of all currently selected items, k: label, v: {value,... otherProps}
  279. dropdownMinWidth: null,
  280. optionKey: key,
  281. inputValue: '',
  282. showInput: false,
  283. focusIndex: props.defaultActiveFirstOption ? 0 : -1,
  284. keyboardEventSet: {},
  285. optionGroups: [],
  286. isHovering: false,
  287. };
  288. this.inputRef = React.createRef();
  289. this.triggerRef = React.createRef();
  290. this.optionsRef = React.createRef();
  291. this.clickOutsideHandler = null;
  292. this.onSelect = this.onSelect.bind(this);
  293. this.onClear = this.onClear.bind(this);
  294. this.onMouseEnter = this.onMouseEnter.bind(this);
  295. this.onMouseLeave = this.onMouseLeave.bind(this);
  296. this.renderOption = this.renderOption.bind(this);
  297. this.foundation = new SelectFoundation(this.adapter);
  298. warning(
  299. 'optionLabelProp' in this.props,
  300. '[Semi Select] \'optionLabelProp\' has already been deprecated, please use \'renderSelectedItem\' instead.'
  301. );
  302. warning(
  303. 'labelInValue' in this.props,
  304. '[Semi Select] \'labelInValue\' has already been deprecated, please use \'onChangeWithObject\' instead.'
  305. );
  306. }
  307. get adapter(): SelectAdapter<SelectProps, SelectState> {
  308. const keyboardAdapter = {
  309. registerKeyDown: (cb: () => void) => {
  310. const keyboardEventSet = {
  311. onKeyDown: cb,
  312. };
  313. this.setState({ keyboardEventSet });
  314. },
  315. unregisterKeyDown: () => {
  316. this.setState({ keyboardEventSet: {} });
  317. },
  318. updateFocusIndex: (focusIndex: number) => {
  319. this.setState({ focusIndex });
  320. },
  321. // eslint-disable-next-line @typescript-eslint/no-empty-function
  322. scrollToFocusOption: () => {},
  323. };
  324. const filterAdapter = {
  325. updateInputValue: (value: string) => {
  326. this.setState({ inputValue: value });
  327. },
  328. toggleInputShow: (showInput: boolean, cb: (...args: any) => void) => {
  329. this.setState({ showInput }, () => {
  330. cb();
  331. });
  332. },
  333. focusInput: () => {
  334. if (this.inputRef && this.inputRef.current) {
  335. this.inputRef.current.focus();
  336. }
  337. },
  338. };
  339. const multipleAdapter = {
  340. notifyMaxLimit: (option: OptionProps) => this.props.onExceed(option),
  341. getMaxLimit: () => this.props.max,
  342. registerClickOutsideHandler: (cb: (e: MouseEvent) => void) => {
  343. const clickOutsideHandler: (e: MouseEvent) => void = e => {
  344. const optionInstance = this.optionsRef && this.optionsRef.current;
  345. const triggerDom = (this.triggerRef && this.triggerRef.current) as Element;
  346. // eslint-disable-next-line react/no-find-dom-node
  347. const optionsDom = ReactDOM.findDOMNode(optionInstance as ReactInstance);
  348. // let isInPanel = optionsDom && optionsDom.contains(e.target);
  349. // let isInTrigger = triggerDom && triggerDom.contains(e.target);
  350. if (optionsDom && !optionsDom.contains(e.target as Node) &&
  351. triggerDom && !triggerDom.contains(e.target as Node)) {
  352. cb(e);
  353. }
  354. };
  355. this.clickOutsideHandler = clickOutsideHandler;
  356. document.addEventListener('mousedown', clickOutsideHandler as any, false);
  357. },
  358. unregisterClickOutsideHandler: () => {
  359. if (this.clickOutsideHandler) {
  360. document.removeEventListener('mousedown', this.clickOutsideHandler as any, false);
  361. this.clickOutsideHandler = null;
  362. }
  363. },
  364. rePositionDropdown: () => {
  365. let { optionKey } = this.state;
  366. optionKey = optionKey + 1;
  367. this.setState({ optionKey });
  368. },
  369. notifyDeselect: (value: OptionProps['value'], option: OptionProps) => {
  370. delete option._parentGroup;
  371. this.props.onDeselect(value, option);
  372. },
  373. };
  374. return {
  375. ...super.adapter,
  376. ...keyboardAdapter,
  377. ...filterAdapter,
  378. ...multipleAdapter,
  379. // Collect all subitems, each item is visible by default when collected, and is not selected
  380. getOptionsFromChildren: (children = this.props.children) => {
  381. let optionGroups = [];
  382. let options = [];
  383. const { optionList } = this.props;
  384. if (optionList && optionList.length) {
  385. options = optionList.map(itemOpt => ({ _show: true, _selected: false, ...itemOpt }));
  386. optionGroups[0] = { children: options, label: '' };
  387. } else {
  388. const result = getOptionsFromGroup(children);
  389. optionGroups = result.optionGroups;
  390. options = result.options;
  391. }
  392. this.setState({ optionGroups });
  393. return options;
  394. },
  395. updateOptions: (options: OptionProps[]) => {
  396. this.setState({ options });
  397. },
  398. openMenu: () => {
  399. this.setState({ isOpen: true });
  400. },
  401. closeMenu: () => {
  402. this.setState({ isOpen: false });
  403. },
  404. getTriggerWidth: () => {
  405. const el = this.triggerRef.current;
  406. return el && el.getBoundingClientRect().width;
  407. },
  408. setOptionWrapperWidth: (width: number) => {
  409. this.setState({ dropdownMinWidth: width });
  410. },
  411. updateSelection: (selections: Map<OptionProps['label'], any>) => {
  412. this.setState({ selections });
  413. },
  414. // clone Map, important!!!, prevent unexpected modify on state
  415. getSelections: () => new Map(this.state.selections),
  416. notifyChange: (value: OnChangeValueType | OnChangeValueType[]) => {
  417. this.props.onChange(value);
  418. },
  419. notifySelect: (value: OptionProps['value'], option: OptionProps) => {
  420. delete option._parentGroup;
  421. this.props.onSelect(value, option);
  422. },
  423. notifyDropdownVisibleChange: (visible: boolean) => {
  424. this.props.onDropdownVisibleChange(visible);
  425. },
  426. notifySearch: (input: string) => {
  427. this.props.onSearch(input);
  428. },
  429. notifyCreate: (input: OptionProps) => {
  430. this.props.onCreate(input);
  431. },
  432. notifyMouseEnter: (e: React.MouseEvent<HTMLDivElement>) => {
  433. this.props.onMouseEnter(e);
  434. },
  435. notifyMouseLeave: (e: React.MouseEvent<HTMLDivElement>) => {
  436. this.props.onMouseLeave(e);
  437. },
  438. notifyFocus: (event: React.FocusEvent) => {
  439. this.props.onFocus(event);
  440. },
  441. notifyBlur: (event: React.FocusEvent) => {
  442. this.props.onBlur(event);
  443. },
  444. notifyClear: () => {
  445. this.props.onClear();
  446. },
  447. notifyListScroll: (e: React.UIEvent<HTMLDivElement>) => {
  448. this.props.onListScroll(e);
  449. },
  450. updateHovering: (isHovering: boolean) => {
  451. this.setState({ isHovering });
  452. },
  453. updateFocusState: (isFocus: boolean) => {
  454. this.setState({ isFocus });
  455. },
  456. focusTrigger: () => {
  457. try {
  458. const el = (this.triggerRef.current) as any;
  459. el.focus();
  460. } catch (error) {
  461. }
  462. }
  463. };
  464. }
  465. componentDidMount() {
  466. this.foundation.init();
  467. }
  468. componentWillUnmount() {
  469. this.foundation.destroy();
  470. }
  471. componentDidUpdate(prevProps: SelectProps, prevState: SelectState) {
  472. const prevChildrenKeys = React.Children.toArray(prevProps.children).map((child: any) => child.key);
  473. const nowChildrenKeys = React.Children.toArray(this.props.children).map((child: any) => child.key);
  474. let isOptionsChanged = false;
  475. if (!isEqual(prevChildrenKeys, nowChildrenKeys) || !isEqual(prevProps.optionList, this.props.optionList)) {
  476. isOptionsChanged = true;
  477. this.foundation.handleOptionListChange();
  478. }
  479. // Add isOptionChanged: There may be cases where the value is unchanged, but the optionList is updated. At this time, the label corresponding to the value may change, and the selected item needs to be updated
  480. if (prevProps.value !== this.props.value || isOptionsChanged) {
  481. if ('value' in this.props) {
  482. this.foundation.handleValueChange(this.props.value as any);
  483. } else {
  484. this.foundation.handleOptionListChangeHadDefaultValue();
  485. }
  486. }
  487. }
  488. handleInputChange = (value: string) => this.foundation.handleInputChange(value);
  489. renderInput() {
  490. const { size, multiple, disabled } = this.props;
  491. const inputcls = cls(`${prefixcls}-input`, {
  492. [`${prefixcls}-input-single`]: !multiple,
  493. [`${prefixcls}-input-multiple`]: multiple,
  494. });
  495. const { inputValue } = this.state;
  496. const inputProps: Record<string, any> = {
  497. value: inputValue,
  498. disabled,
  499. className: inputcls,
  500. onChange: this.handleInputChange,
  501. };
  502. let style = {};
  503. // Multiple choice mode
  504. if (multiple) {
  505. style = {
  506. width: inputValue ? `${inputValue.length * 16}px` : '2px',
  507. };
  508. inputProps.style = style;
  509. }
  510. return (
  511. <Input
  512. ref={this.inputRef as any}
  513. size={size}
  514. {...inputProps}
  515. onFocus={(e: React.FocusEvent<HTMLInputElement>) => {
  516. // prevent event bubbling which will fire trigger onFocus event
  517. e.stopPropagation();
  518. // e.nativeEvent.stopImmediatePropagation();
  519. }}
  520. />
  521. );
  522. }
  523. close() {
  524. this.foundation.close();
  525. }
  526. open() {
  527. this.foundation.open();
  528. }
  529. clearInput() {
  530. this.foundation.clearInput();
  531. }
  532. selectAll() {
  533. this.foundation.selectAll();
  534. }
  535. deselectAll() {
  536. this.foundation.clearSelected();
  537. }
  538. focus() {
  539. this.foundation.focus();
  540. }
  541. onSelect(option: OptionProps, optionIndex: number, e: any) {
  542. this.foundation.onSelect(option, optionIndex, e);
  543. }
  544. onClear(e: React.MouseEvent) {
  545. e.nativeEvent.stopImmediatePropagation();
  546. this.foundation.handleClearClick(e as any);
  547. }
  548. renderEmpty() {
  549. return <Option empty={true} emptyContent={this.props.emptyContent} />;
  550. }
  551. renderLoading() {
  552. const loadingWrapperCls = `${prefixcls}-loading-wrapper`;
  553. return (
  554. <div className={loadingWrapperCls}>
  555. <Spin />
  556. </div>
  557. );
  558. }
  559. renderOption(option: OptionProps, optionIndex: number, style?: React.CSSProperties) {
  560. const { focusIndex, inputValue } = this.state;
  561. const { renderOptionItem } = this.props;
  562. let optionContent;
  563. const isFocused = optionIndex === focusIndex;
  564. let optionStyle = style || {};
  565. if (option.style) {
  566. optionStyle = { ...optionStyle, ...option.style };
  567. }
  568. if (option._inputCreateOnly) {
  569. optionContent = this.renderCreateOption(option, isFocused, optionIndex, style);
  570. } else {
  571. // use another name to make sure that 'key' in optionList still exist when we call onChange
  572. if ('key' in option) {
  573. option._keyInOptionList = option.key;
  574. }
  575. optionContent = (
  576. <Option
  577. showTick
  578. {...option}
  579. selected={option._selected}
  580. onSelect={(v: OptionProps, e: MouseEvent) => this.onSelect(v, optionIndex, e)}
  581. focused={isFocused}
  582. onMouseEnter={() => this.onOptionHover(optionIndex)}
  583. style={optionStyle}
  584. key={option.key || option.label as string + option.value as string + optionIndex}
  585. renderOptionItem={renderOptionItem}
  586. inputValue={inputValue}
  587. >
  588. {option.label}
  589. </Option>
  590. );
  591. }
  592. return optionContent;
  593. }
  594. renderCreateOption(option: OptionProps, isFocused: boolean, optionIndex: number, style: React.CSSProperties) {
  595. const { renderCreateItem } = this.props;
  596. // default render method
  597. if (typeof renderCreateItem === 'undefined') {
  598. const defaultCreateItem = (
  599. <Option
  600. key={option.key || option.label as string + option.value as string}
  601. onSelect={(v: OptionProps, e: MouseEvent) => this.onSelect(v, optionIndex, e)}
  602. onMouseEnter={() => this.onOptionHover(optionIndex)}
  603. showTick
  604. {...option}
  605. focused={isFocused}
  606. style={style}
  607. >
  608. <LocaleCosumer componentName="Select">
  609. {(locale: Locale['Select']) => (
  610. <>
  611. <span className={`${prefixcls}-create-tips`}>{locale.createText}</span>
  612. {option.value}
  613. </>
  614. )}
  615. </LocaleCosumer>
  616. </Option>
  617. );
  618. return defaultCreateItem;
  619. }
  620. const customCreateItem = renderCreateItem(option.value, isFocused);
  621. return (
  622. <div onClick={e => this.onSelect(option, optionIndex, e)} key={new Date().valueOf()}>
  623. {customCreateItem}
  624. </div>
  625. );
  626. }
  627. onOptionHover(optionIndex: number) {
  628. this.foundation.handleOptionMouseEnter(optionIndex);
  629. }
  630. renderWithGroup(visibileOptions: OptionProps[]) {
  631. const content: JSX.Element[] = [];
  632. const groupStatus = new Map();
  633. visibileOptions.forEach((option, optionIndex) => {
  634. const parentGroup = option._parentGroup;
  635. const optionContent = this.renderOption(option, optionIndex);
  636. if (parentGroup && groupStatus.has(parentGroup.label)) {
  637. // group content already insert
  638. content.push(optionContent);
  639. } else if (parentGroup) {
  640. const groupContent = <OptionGroup {...parentGroup} key={parentGroup.label} />;
  641. groupStatus.set(parentGroup.label, true);
  642. content.push(groupContent);
  643. content.push(optionContent);
  644. } else {
  645. // when not use with OptionGroup
  646. content.push(optionContent);
  647. }
  648. });
  649. return content;
  650. }
  651. renderVirtualizeList(visibileOptions: OptionProps[]) {
  652. const { virtualize } = this.props;
  653. const { direction } = this.context;
  654. const { height, width, itemSize } = virtualize;
  655. return (
  656. <List
  657. height={height || numbers.LIST_HEIGHT}
  658. itemCount={visibileOptions.length}
  659. itemSize={itemSize}
  660. itemData={{ visibileOptions, renderOption: this.renderOption }}
  661. width={width || '100%'}
  662. style={{ direction }}
  663. >
  664. {VirtualRow}
  665. </List>
  666. );
  667. }
  668. renderOptions(children?: React.ReactNode) {
  669. const { dropdownMinWidth, options, selections } = this.state;
  670. const {
  671. maxHeight,
  672. dropdownClassName,
  673. dropdownStyle,
  674. outerTopSlot,
  675. innerTopSlot,
  676. outerBottomSlot,
  677. innerBottomSlot,
  678. loading,
  679. virtualize,
  680. } = this.props;
  681. // Do a filter first, instead of directly judging in forEach, so that the focusIndex can correspond to
  682. const visibileOptions = options.filter(item => item._show);
  683. let listContent: JSX.Element | JSX.Element[] = this.renderWithGroup(visibileOptions);
  684. if (virtualize) {
  685. listContent = this.renderVirtualizeList(visibileOptions);
  686. }
  687. const style = { minWidth: dropdownMinWidth, ...dropdownStyle };
  688. const optionListCls = cls({
  689. [`${prefixcls}-option-list`]: true,
  690. [`${prefixcls}-option-list-chosen`]: selections.size,
  691. });
  692. const isEmpty = !options.length || !options.some(item => item._show);
  693. return (
  694. <div className={dropdownClassName} style={style}>
  695. {outerTopSlot}
  696. <div
  697. style={{ maxHeight: `${maxHeight}px` }}
  698. className={optionListCls}
  699. role="listbox"
  700. onScroll={e => this.foundation.handleListScroll(e)}
  701. >
  702. {innerTopSlot}
  703. {!loading ? listContent : this.renderLoading()}
  704. {isEmpty && !loading ? this.renderEmpty() : null}
  705. {innerBottomSlot}
  706. </div>
  707. {outerBottomSlot}
  708. </div>
  709. );
  710. }
  711. renderSingleSelection(selections: Map<OptionProps['label'], any>, filterable: boolean) {
  712. let { renderSelectedItem } = this.props;
  713. const { placeholder } = this.props;
  714. const { showInput, inputValue } = this.state;
  715. let renderText: React.ReactNode = '';
  716. const selectedItems = [...selections];
  717. if (typeof renderSelectedItem === 'undefined') {
  718. renderSelectedItem = ((optionNode: OptionProps) => optionNode.label) as RenderSelectedItemFn;
  719. }
  720. if (selectedItems.length) {
  721. const selectedItem = selectedItems[0][1];
  722. renderText = (renderSelectedItem as RenderSingleSelectedItemFn)(selectedItem);
  723. }
  724. const spanCls = cls({
  725. [`${prefixcls}-selection-text`]: true,
  726. [`${prefixcls}-selection-placeholder`]: !renderText && renderText !== 0,
  727. [`${prefixcls}-selection-text-hide`]: inputValue && showInput, // show Input
  728. [`${prefixcls}-selection-text-inactive`]: !inputValue && showInput, // Stack Input & RenderText(opacity 0.4)
  729. });
  730. const contentWrapperCls = `${prefixcls}-content-wrapper`;
  731. return (
  732. <>
  733. <div className={contentWrapperCls}>
  734. {<span className={spanCls}>{renderText || renderText === 0 ? renderText : placeholder}</span>}
  735. {filterable && showInput ? this.renderInput() : null}
  736. </div>
  737. </>
  738. );
  739. }
  740. renderMultipleSelection(selections: Map<OptionProps['label'], any>, filterable: boolean) {
  741. let { renderSelectedItem } = this.props;
  742. const { placeholder, maxTagCount, size } = this.props;
  743. const { inputValue } = this.state;
  744. const selectDisabled = this.props.disabled;
  745. const renderTags = [];
  746. const selectedItems = [...selections];
  747. if (typeof renderSelectedItem === 'undefined') {
  748. renderSelectedItem = (optionNode: OptionProps) => ({
  749. isRenderInTag: true,
  750. content: optionNode.label,
  751. });
  752. }
  753. const tags = selectedItems.map((item, i) => {
  754. const label = item[0];
  755. const { value } = item[1];
  756. const disabled = item[1].disabled || selectDisabled;
  757. const onClose = (tagContent: React.ReactNode, e: MouseEvent) => {
  758. if (e && typeof e.preventDefault === 'function') {
  759. e.preventDefault(); // make sure that tag will not hidden immediately in controlled mode
  760. }
  761. this.foundation.removeTag({ label, value });
  762. };
  763. const { content, isRenderInTag } = (renderSelectedItem as RenderMultipleSelectedItemFn)(item[1], { index: i, disabled, onClose });
  764. const basic = {
  765. disabled,
  766. closable: !disabled,
  767. onClose,
  768. };
  769. if (isRenderInTag) {
  770. return (
  771. <Tag {...basic} color="white" size={size || 'large'} key={value}>
  772. {content}
  773. </Tag>
  774. );
  775. } else {
  776. return content;
  777. }
  778. });
  779. const contentWrapperCls = cls({
  780. [`${prefixcls}-content-wrapper`]: true,
  781. [`${prefixcls}-content-wrapper-one-line`]: maxTagCount,
  782. [`${prefixcls}-content-wrapper-empty`]: !tags.length,
  783. });
  784. const spanCls = cls({
  785. [`${prefixcls}-selection-text`]: true,
  786. [`${prefixcls}-selection-placeholder`]: !tags.length,
  787. [`${prefixcls}-selection-text-hide`]: tags && tags.length,
  788. // [prefixcls + '-selection-text-inactive']: !inputValue && !tags.length,
  789. });
  790. const placeholderText = placeholder && !inputValue ? <span className={spanCls}>{placeholder}</span> : null;
  791. const n = tags.length > maxTagCount ? maxTagCount : undefined;
  792. const NotOneLine = !maxTagCount; // Multiple lines (that is, do not set maxTagCount), do not use TagGroup, directly traverse with Tag, otherwise Input cannot follow the correct position
  793. const tagContent = NotOneLine ? tags : <TagGroup tagList={tags} maxTagCount={n} size="large" mode="custom" />;
  794. return (
  795. <>
  796. <div className={contentWrapperCls}>
  797. {tags && tags.length ? tagContent : placeholderText}
  798. {!filterable ? null : this.renderInput()}
  799. </div>
  800. </>
  801. );
  802. }
  803. onMouseEnter(e: MouseEvent) {
  804. this.foundation.handleMouseEnter(e as any);
  805. }
  806. onMouseLeave(e: MouseEvent) {
  807. this.foundation.handleMouseLeave(e as any);
  808. }
  809. renderSuffix() {
  810. const { suffix } = this.props;
  811. const suffixWrapperCls = cls({
  812. [`${prefixcls}-suffix`]: true,
  813. [`${prefixcls}-suffix-text`]: suffix && isString(suffix),
  814. [`${prefixcls}-suffix-icon`]: isSemiIcon(suffix),
  815. });
  816. return <div className={suffixWrapperCls}>{suffix}</div>;
  817. }
  818. renderPrefix() {
  819. const { prefix, insetLabel } = this.props;
  820. const labelNode = (prefix || insetLabel) as React.ReactElement<any, any>;
  821. const prefixWrapperCls = cls({
  822. [`${prefixcls}-prefix`]: true,
  823. [`${prefixcls}-inset-label`]: insetLabel,
  824. [`${prefixcls}-prefix-text`]: labelNode && isString(labelNode),
  825. [`${prefixcls}-prefix-icon`]: isSemiIcon(labelNode),
  826. });
  827. return <div className={prefixWrapperCls}>{labelNode}</div>;
  828. }
  829. renderSelection() {
  830. const {
  831. disabled,
  832. multiple,
  833. filter,
  834. style,
  835. size,
  836. className,
  837. validateStatus,
  838. showArrow,
  839. suffix,
  840. prefix,
  841. insetLabel,
  842. placeholder,
  843. triggerRender,
  844. arrowIcon,
  845. } = this.props;
  846. const { selections, isOpen, keyboardEventSet, inputValue, isHovering, isFocus } = this.state;
  847. const useCustomTrigger = typeof triggerRender === 'function';
  848. const filterable = Boolean(filter); // filter(boolean || function)
  849. const selectionCls = useCustomTrigger ?
  850. cls(className) :
  851. cls(prefixcls, className, {
  852. [`${prefixcls}-open`]: isOpen,
  853. [`${prefixcls}-focus`]: isFocus,
  854. [`${prefixcls}-disabled`]: disabled,
  855. [`${prefixcls}-single`]: !multiple,
  856. [`${prefixcls}-multiple`]: multiple,
  857. [`${prefixcls}-filterable`]: filterable,
  858. [`${prefixcls}-small`]: size === 'small',
  859. [`${prefixcls}-large`]: size === 'large',
  860. [`${prefixcls}-error`]: validateStatus === 'error',
  861. [`${prefixcls}-warning`]: validateStatus === 'warning',
  862. [`${prefixcls}-no-arrow`]: !showArrow,
  863. [`${prefixcls}-with-prefix`]: prefix || insetLabel,
  864. [`${prefixcls}-with-suffix`]: suffix,
  865. });
  866. const showClear = this.props.showClear &&
  867. (selections.size || inputValue) && !disabled && (isHovering || isOpen);
  868. const arrowContent = showArrow ? (
  869. <div className={`${prefixcls}-arrow`}>
  870. {arrowIcon}
  871. </div>
  872. ) : (
  873. <div className={`${prefixcls}-arrow-empty`} />
  874. );
  875. const inner = useCustomTrigger ? (
  876. <Trigger
  877. value={Array.from(selections.values())}
  878. inputValue={inputValue}
  879. onChange={this.handleInputChange}
  880. onClear={this.onClear}
  881. disabled={disabled}
  882. triggerRender={triggerRender}
  883. placeholder={placeholder as any}
  884. componentName="Select"
  885. componentProps={{ ...this.props }}
  886. />
  887. ) : (
  888. [
  889. <Fragment key="prefix">{prefix || insetLabel ? this.renderPrefix() : null}</Fragment>,
  890. <Fragment key="selection">
  891. <div className={cls(`${prefixcls}-selection`)}>
  892. {multiple ?
  893. this.renderMultipleSelection(selections, filterable) :
  894. this.renderSingleSelection(selections, filterable)}
  895. </div>
  896. </Fragment>,
  897. <Fragment key="clearicon">
  898. {showClear ? (
  899. <div className={cls(`${prefixcls}-clear`)} onClick={this.onClear}>
  900. <IconClear />
  901. </div>
  902. ) : arrowContent}
  903. </Fragment>,
  904. <Fragment key="suffix">{suffix ? this.renderSuffix() : null}</Fragment>,
  905. ]
  906. );
  907. const tabIndex = disabled ? null : 0;
  908. return (
  909. <div
  910. className={selectionCls}
  911. ref={ref => ((this.triggerRef as any).current = ref)}
  912. onClick={e => this.foundation.handleClick(e)}
  913. style={style}
  914. tabIndex={tabIndex}
  915. onMouseEnter={this.onMouseEnter}
  916. onMouseLeave={this.onMouseLeave}
  917. // onFocus={e => this.foundation.handleTriggerFocus(e)}
  918. onBlur={e => this.foundation.handleTriggerBlur(e as any)}
  919. {...keyboardEventSet}
  920. >
  921. {inner}
  922. </div>
  923. );
  924. }
  925. render() {
  926. const { direction } = this.context;
  927. const defaultPosition = direction === 'rtl' ? 'bottomRight' : 'bottomLeft';
  928. const {
  929. children,
  930. position = defaultPosition,
  931. zIndex,
  932. getPopupContainer,
  933. motion,
  934. autoAdjustOverflow,
  935. mouseLeaveDelay,
  936. mouseEnterDelay,
  937. spacing,
  938. stopPropagation,
  939. } = this.props;
  940. const { isOpen, optionKey } = this.state;
  941. const optionList = this.renderOptions(children);
  942. const selection = this.renderSelection();
  943. return (
  944. <Popover
  945. getPopupContainer={getPopupContainer}
  946. motion={motion}
  947. autoAdjustOverflow={autoAdjustOverflow}
  948. mouseLeaveDelay={mouseLeaveDelay}
  949. mouseEnterDelay={mouseEnterDelay}
  950. // transformFromCenter TODO: check no such property
  951. zIndex={zIndex}
  952. ref={this.optionsRef}
  953. content={optionList}
  954. visible={isOpen}
  955. trigger="custom"
  956. rePosKey={optionKey}
  957. position={position}
  958. spacing={spacing}
  959. stopPropagation={stopPropagation}
  960. >
  961. {selection}
  962. </Popover>
  963. );
  964. }
  965. }
  966. export default Select;