index.tsx 57 KB

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