1
0

index.tsx 50 KB

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