index.tsx 51 KB

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