index.tsx 58 KB

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