index.tsx 58 KB

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