index.tsx 42 KB

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