index.tsx 42 KB

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