index.tsx 50 KB

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