1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063 |
- /* eslint-disable max-len */
- /* eslint-disable max-lines-per-function */
- import React, { Fragment, MouseEvent, ReactInstance } from 'react';
- import ReactDOM from 'react-dom';
- import cls from 'classnames';
- import PropTypes from 'prop-types';
- import ConfigContext from '../configProvider/context';
- import SelectFoundation, { SelectAdapter } from '@douyinfe/semi-foundation/select/foundation';
- import { cssClasses, strings, numbers } from '@douyinfe/semi-foundation/select/constants';
- import BaseComponent, { ValidateStatus } from '../_base/baseComponent';
- import { isEqual, isString, noop } from 'lodash-es';
- import Tag from '../tag/index';
- import TagGroup from '../tag/group';
- import LocaleCosumer from '../locale/localeConsumer';
- import Popover from '../popover/index';
- import { numbers as popoverNumbers } from '@douyinfe/semi-foundation/popover/constants';
- import { FixedSizeList as List } from 'react-window';
- import { getOptionsFromGroup } from './utils';
- import VirtualRow from './virtualRow';
- import Input from '../input/index';
- import Option, { OptionProps } from './option';
- import OptionGroup from './optionGroup';
- import Spin from '../spin';
- import Trigger from '../trigger';
- import { IconChevronDown, IconClear } from '@douyinfe/semi-icons';
- import { isSemiIcon } from '../_utils';
- import warning from '@douyinfe/semi-foundation/utils/warning';
- import '@douyinfe/semi-foundation/select/select.scss';
- import '@douyinfe/semi-foundation/select/option.scss';
- import { Locale } from '../locale/interface';
- import { Position, TooltipProps } from '../tooltip';
- export { OptionProps } from './option';
- export { OptionGroupProps } from './optionGroup';
- export { VirtualRowProps } from './virtualRow';
- const prefixcls = cssClasses.PREFIX;
- const key = 0;
- type OnChangeValueType = string | number | Record<string, any>;
- export interface optionRenderProps {
- key?: any;
- label?: string | React.ReactNode | number;
- value?: string | number;
- style?: React.CSSProperties;
- className?: string;
- selected?: boolean;
- focused?: boolean;
- show?: boolean;
- disabled?: boolean;
- onMouseEnter?: (e: React.MouseEvent) => any;
- onClick?: (e: React.MouseEvent) => any;
- [x: string]: any;
- }
- export interface selectMethod {
- clearInput?: () => void;
- selectAll?: () => void;
- deselectAll?: () => void;
- focus?: () => void;
- close?: () => void;
- open?: () => void;
- }
- export type SelectSize = 'small' | 'large' | 'default';
- export interface virtualListProps {
- itemSize?: number;
- height?: number;
- width?: string | number;
- }
- export type RenderSingleSelectedItemFn = (optionNode: Record<string, any>) => React.ReactNode;
- export type RenderMultipleSelectedItemFn = (optionNode: Record<string, any>, multipleProps: { index: number; disabled: boolean; onClose: (tagContent: React.ReactNode, e: MouseEvent) => void }) => { isRenderInTag: boolean; content: React.ReactNode };
- export type RenderSelectedItemFn = RenderSingleSelectedItemFn | RenderMultipleSelectedItemFn;
- export type SelectProps = {
- autoFocus?: boolean;
- arrowIcon?: React.ReactNode;
- defaultValue?: string | number | any[] | Record<string, any>;
- value?: string | number | any[] | Record<string, any>;
- placeholder?: React.ReactNode;
- onChange?: (value: SelectProps['value']) => void;
- multiple?: boolean;
- filter?: boolean | ((inpueValue: string, option: OptionProps) => boolean);
- max?: number;
- maxTagCount?: number;
- maxHeight?: string | number;
- style?: React.CSSProperties;
- className?: string;
- size?: SelectSize;
- disabled?: boolean;
- emptyContent?: React.ReactNode;
- onDropdownVisibleChange?: (visible: boolean) => void;
- zIndex?: number;
- position?: Position;
- onSearch?: (value: string) => void;
- dropdownClassName?: string;
- dropdownStyle?: React.CSSProperties;
- outerTopSlot?: React.ReactNode;
- innerTopSlot?: React.ReactNode;
- outerBottomSlot?: React.ReactNode;
- innerBottomSlot?: React.ReactNode;
- optionList?: OptionProps[];
- dropdownMatchSelectWidth?: boolean;
- loading?: boolean;
- defaultOpen?: boolean;
- validateStatus?: ValidateStatus;
- defaultActiveFirstOption?: boolean;
- onChangeWithObject?: boolean;
- suffix?: React.ReactNode;
- prefix?: React.ReactNode;
- insetLabel?: React.ReactNode;
- showClear?: boolean;
- showArrow?: boolean;
- renderSelectedItem?: RenderSelectedItemFn;
- renderCreateItem?: (inputValue: OptionProps['value'], focus: boolean) => React.ReactNode;
- renderOptionItem?: (props: optionRenderProps) => React.ReactNode;
- onMouseEnter?: (e: React.MouseEvent) => any;
- onMouseLeave?: (e: React.MouseEvent) => any;
- clickToHide?: boolean;
- onExceed?: (option: OptionProps) => void;
- onCreate?: (option: OptionProps) => void;
- remote?: boolean;
- onDeselect?: (value: SelectProps['value'], option: Record<string, any>) => void;
- onSelect?: (value: SelectProps['value'], option: Record<string, any>) => void;
- allowCreate?: boolean;
- triggerRender?: (props?: any) => React.ReactNode;
- onClear?: () => void;
- virtualize?: virtualListProps;
- onFocus?: (e: React.FocusEvent) => void;
- onBlur?: (e: React.FocusEvent) => void;
- onListScroll?: (e: React.UIEvent<HTMLDivElement>) => void;
- children?: React.ReactNode;
- } & Pick<
- TooltipProps,
- | 'spacing'
- | 'getPopupContainer'
- | 'motion'
- | 'autoAdjustOverflow'
- | 'mouseLeaveDelay'
- | 'mouseEnterDelay'
- | 'stopPropagation'
- > & React.RefAttributes<any>;
- export interface SelectState {
- isOpen: boolean;
- isFocus: boolean;
- options: Array<OptionProps>;
- selections: Map<OptionProps['label'], any>; // A collection of all currently selected items, k: label, v: {value,... otherProps}
- dropdownMinWidth: number;
- optionKey: number;
- inputValue: string;
- showInput: boolean;
- focusIndex: number;
- keyboardEventSet: any; // {}
- optionGroups: Array<any>;
- isHovering: boolean;
- }
- // 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
- class Select extends BaseComponent<SelectProps, SelectState> {
- static contextType = ConfigContext;
- static Option = Option;
- static OptGroup = OptionGroup;
- static propTypes = {
- autoFocus: PropTypes.bool,
- children: PropTypes.node,
- defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.array, PropTypes.object]),
- value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.array, PropTypes.object]),
- placeholder: PropTypes.node,
- onChange: PropTypes.func,
- multiple: PropTypes.bool,
- // Whether to turn on the input box filtering function, when it is a function, it represents a custom filtering function
- filter: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
- // How many tags can you choose?
- max: PropTypes.number,
- // How many tabs are displayed at most, and the rest are displayed in + N
- maxTagCount: PropTypes.number,
- maxHeight: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
- style: PropTypes.object,
- className: PropTypes.string,
- size: PropTypes.oneOf<SelectProps['size']>(strings.SIZE_SET),
- disabled: PropTypes.bool,
- emptyContent: PropTypes.node,
- onDropdownVisibleChange: PropTypes.func,
- zIndex: PropTypes.number,
- position: PropTypes.oneOf(strings.POSITION_SET),
- onSearch: PropTypes.func,
- getPopupContainer: PropTypes.func,
- dropdownClassName: PropTypes.string,
- dropdownStyle: PropTypes.object,
- outerTopSlot: PropTypes.node,
- innerTopSlot: PropTypes.node,
- outerBottomSlot: PropTypes.node,
- innerBottomSlot: PropTypes.node, // Options slot
- optionList: PropTypes.array,
- dropdownMatchSelectWidth: PropTypes.bool,
- loading: PropTypes.bool,
- defaultOpen: PropTypes.bool,
- validateStatus: PropTypes.oneOf(strings.STATUS),
- defaultActiveFirstOption: PropTypes.bool,
- triggerRender: PropTypes.func,
- stopPropagation: PropTypes.bool,
- // motion doesn't need to be exposed
- motion: PropTypes.oneOfType([PropTypes.func, PropTypes.bool, PropTypes.object]),
- onChangeWithObject: PropTypes.bool,
- suffix: PropTypes.node,
- prefix: PropTypes.node,
- insetLabel: PropTypes.node,
- showClear: PropTypes.bool,
- showArrow: PropTypes.bool,
- renderSelectedItem: PropTypes.func,
- allowCreate: PropTypes.bool,
- renderCreateItem: PropTypes.func,
- onMouseEnter: PropTypes.func,
- onMouseLeave: PropTypes.func,
- clickToHide: PropTypes.bool,
- onExceed: PropTypes.func,
- onCreate: PropTypes.func,
- remote: PropTypes.bool,
- onDeselect: PropTypes.func,
- // 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
- onSelect: PropTypes.func,
- autoAdjustOverflow: PropTypes.bool,
- mouseEnterDelay: PropTypes.number,
- mouseLeaveDelay: PropTypes.number,
- spacing: PropTypes.number,
- onBlur: PropTypes.func,
- onFocus: PropTypes.func,
- onClear: PropTypes.func,
- virtualize: PropTypes.object,
- renderOptionItem: PropTypes.func,
- onListScroll: PropTypes.func,
- arrowIcon: PropTypes.node,
- // open: PropTypes.bool,
- // tagClosable: PropTypes.bool,
- };
- static defaultProps: Partial<SelectProps> = {
- stopPropagation: true,
- motion: true,
- zIndex: popoverNumbers.DEFAULT_Z_INDEX,
- // position: 'bottomLeft',
- filter: false,
- multiple: false,
- disabled: false,
- defaultOpen: false,
- allowCreate: false,
- placeholder: '',
- onDropdownVisibleChange: noop,
- onChangeWithObject: false,
- onChange: noop,
- onSearch: noop,
- onMouseEnter: noop,
- onMouseLeave: noop,
- onDeselect: noop,
- onSelect: noop,
- onCreate: noop,
- onExceed: noop,
- onFocus: noop,
- onBlur: noop,
- onClear: noop,
- onListScroll: noop,
- maxHeight: 300,
- dropdownMatchSelectWidth: true,
- defaultActiveFirstOption: false,
- showArrow: true,
- showClear: false,
- remote: false,
- autoAdjustOverflow: true,
- arrowIcon: <IconChevronDown />
- // Radio selection is different from the default renderSelectedItem for multiple selection, so it is not declared here
- // renderSelectedItem: (optionNode) => optionNode.label,
- // The default creator rendering is related to i18, so it is not declared here
- // renderCreateItem: (input) => input
- };
- inputRef: React.RefObject<HTMLInputElement>;
- triggerRef: React.RefObject<HTMLDivElement>;
- optionsRef: React.RefObject<any>;
- clickOutsideHandler: (e: MouseEvent) => void;
- foundation: SelectFoundation;
- constructor(props: SelectProps) {
- super(props);
- this.state = {
- isOpen: false,
- isFocus: false,
- options: [], // All options
- selections: new Map(), // A collection of all currently selected items, k: label, v: {value,... otherProps}
- dropdownMinWidth: null,
- optionKey: key,
- inputValue: '',
- showInput: false,
- focusIndex: props.defaultActiveFirstOption ? 0 : -1,
- keyboardEventSet: {},
- optionGroups: [],
- isHovering: false,
- };
- this.inputRef = React.createRef();
- this.triggerRef = React.createRef();
- this.optionsRef = React.createRef();
- this.clickOutsideHandler = null;
- this.onSelect = this.onSelect.bind(this);
- this.onClear = this.onClear.bind(this);
- this.onMouseEnter = this.onMouseEnter.bind(this);
- this.onMouseLeave = this.onMouseLeave.bind(this);
- this.renderOption = this.renderOption.bind(this);
- this.foundation = new SelectFoundation(this.adapter);
- warning(
- 'optionLabelProp' in this.props,
- '[Semi Select] \'optionLabelProp\' has already been deprecated, please use \'renderSelectedItem\' instead.'
- );
- warning(
- 'labelInValue' in this.props,
- '[Semi Select] \'labelInValue\' has already been deprecated, please use \'onChangeWithObject\' instead.'
- );
- }
- get adapter(): SelectAdapter<SelectProps, SelectState> {
- const keyboardAdapter = {
- registerKeyDown: (cb: () => void) => {
- const keyboardEventSet = {
- onKeyDown: cb,
- };
- this.setState({ keyboardEventSet });
- },
- unregisterKeyDown: () => {
- this.setState({ keyboardEventSet: {} });
- },
- updateFocusIndex: (focusIndex: number) => {
- this.setState({ focusIndex });
- },
- // eslint-disable-next-line @typescript-eslint/no-empty-function
- scrollToFocusOption: () => {},
- };
- const filterAdapter = {
- updateInputValue: (value: string) => {
- this.setState({ inputValue: value });
- },
- toggleInputShow: (showInput: boolean, cb: (...args: any) => void) => {
- this.setState({ showInput }, () => {
- cb();
- });
- },
- focusInput: () => {
- if (this.inputRef && this.inputRef.current) {
- this.inputRef.current.focus();
- }
- },
- };
- const multipleAdapter = {
- notifyMaxLimit: (option: OptionProps) => this.props.onExceed(option),
- getMaxLimit: () => this.props.max,
- registerClickOutsideHandler: (cb: (e: MouseEvent) => void) => {
- const clickOutsideHandler: (e: MouseEvent) => void = e => {
- const optionInstance = this.optionsRef && this.optionsRef.current;
- const triggerDom = (this.triggerRef && this.triggerRef.current) as Element;
- // eslint-disable-next-line react/no-find-dom-node
- const optionsDom = ReactDOM.findDOMNode(optionInstance as ReactInstance);
- // let isInPanel = optionsDom && optionsDom.contains(e.target);
- // let isInTrigger = triggerDom && triggerDom.contains(e.target);
- if (optionsDom && !optionsDom.contains(e.target as Node) &&
- triggerDom && !triggerDom.contains(e.target as Node)) {
- cb(e);
- }
- };
- this.clickOutsideHandler = clickOutsideHandler;
- document.addEventListener('mousedown', clickOutsideHandler as any, false);
- },
- unregisterClickOutsideHandler: () => {
- if (this.clickOutsideHandler) {
- document.removeEventListener('mousedown', this.clickOutsideHandler as any, false);
- this.clickOutsideHandler = null;
- }
- },
- rePositionDropdown: () => {
- let { optionKey } = this.state;
- optionKey = optionKey + 1;
- this.setState({ optionKey });
- },
- notifyDeselect: (value: OptionProps['value'], option: OptionProps) => {
- delete option._parentGroup;
- this.props.onDeselect(value, option);
- },
- };
- return {
- ...super.adapter,
- ...keyboardAdapter,
- ...filterAdapter,
- ...multipleAdapter,
- // Collect all subitems, each item is visible by default when collected, and is not selected
- getOptionsFromChildren: (children = this.props.children) => {
- let optionGroups = [];
- let options = [];
- const { optionList } = this.props;
- if (optionList && optionList.length) {
- options = optionList.map(itemOpt => ({ _show: true, _selected: false, ...itemOpt }));
- optionGroups[0] = { children: options, label: '' };
- } else {
- const result = getOptionsFromGroup(children);
- optionGroups = result.optionGroups;
- options = result.options;
- }
- this.setState({ optionGroups });
- return options;
- },
- updateOptions: (options: OptionProps[]) => {
- this.setState({ options });
- },
- openMenu: () => {
- this.setState({ isOpen: true });
- },
- closeMenu: () => {
- this.setState({ isOpen: false });
- },
- getTriggerWidth: () => {
- const el = this.triggerRef.current;
- return el && el.getBoundingClientRect().width;
- },
- setOptionWrapperWidth: (width: number) => {
- this.setState({ dropdownMinWidth: width });
- },
- updateSelection: (selections: Map<OptionProps['label'], any>) => {
- this.setState({ selections });
- },
- // clone Map, important!!!, prevent unexpected modify on state
- getSelections: () => new Map(this.state.selections),
- notifyChange: (value: OnChangeValueType | OnChangeValueType[]) => {
- this.props.onChange(value);
- },
- notifySelect: (value: OptionProps['value'], option: OptionProps) => {
- delete option._parentGroup;
- this.props.onSelect(value, option);
- },
- notifyDropdownVisibleChange: (visible: boolean) => {
- this.props.onDropdownVisibleChange(visible);
- },
- notifySearch: (input: string) => {
- this.props.onSearch(input);
- },
- notifyCreate: (input: OptionProps) => {
- this.props.onCreate(input);
- },
- notifyMouseEnter: (e: React.MouseEvent<HTMLDivElement>) => {
- this.props.onMouseEnter(e);
- },
- notifyMouseLeave: (e: React.MouseEvent<HTMLDivElement>) => {
- this.props.onMouseLeave(e);
- },
- notifyFocus: (event: React.FocusEvent) => {
- this.props.onFocus(event);
- },
- notifyBlur: (event: React.FocusEvent) => {
- this.props.onBlur(event);
- },
- notifyClear: () => {
- this.props.onClear();
- },
- notifyListScroll: (e: React.UIEvent<HTMLDivElement>) => {
- this.props.onListScroll(e);
- },
- updateHovering: (isHovering: boolean) => {
- this.setState({ isHovering });
- },
- updateFocusState: (isFocus: boolean) => {
- this.setState({ isFocus });
- },
- focusTrigger: () => {
- try {
- const el = (this.triggerRef.current) as any;
- el.focus();
- } catch (error) {
- }
- }
- };
- }
- componentDidMount() {
- this.foundation.init();
- }
- componentWillUnmount() {
- this.foundation.destroy();
- }
- componentDidUpdate(prevProps: SelectProps, prevState: SelectState) {
- const prevChildrenKeys = React.Children.toArray(prevProps.children).map((child: any) => child.key);
- const nowChildrenKeys = React.Children.toArray(this.props.children).map((child: any) => child.key);
- let isOptionsChanged = false;
- if (!isEqual(prevChildrenKeys, nowChildrenKeys) || !isEqual(prevProps.optionList, this.props.optionList)) {
- isOptionsChanged = true;
- this.foundation.handleOptionListChange();
- }
- // 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
- if (prevProps.value !== this.props.value || isOptionsChanged) {
- if ('value' in this.props) {
- this.foundation.handleValueChange(this.props.value as any);
- } else {
- this.foundation.handleOptionListChangeHadDefaultValue();
- }
- }
- }
- handleInputChange = (value: string) => this.foundation.handleInputChange(value);
- renderInput() {
- const { size, multiple, disabled } = this.props;
- const inputcls = cls(`${prefixcls}-input`, {
- [`${prefixcls}-input-single`]: !multiple,
- [`${prefixcls}-input-multiple`]: multiple,
- });
- const { inputValue } = this.state;
- const inputProps: Record<string, any> = {
- value: inputValue,
- disabled,
- className: inputcls,
- onChange: this.handleInputChange,
- };
- let style = {};
- // Multiple choice mode
- if (multiple) {
- style = {
- width: inputValue ? `${inputValue.length * 16}px` : '2px',
- };
- inputProps.style = style;
- }
- return (
- <Input
- ref={this.inputRef as any}
- size={size}
- {...inputProps}
- onFocus={(e: React.FocusEvent<HTMLInputElement>) => {
- // prevent event bubbling which will fire trigger onFocus event
- e.stopPropagation();
- // e.nativeEvent.stopImmediatePropagation();
- }}
- />
- );
- }
- close() {
- this.foundation.close();
- }
- open() {
- this.foundation.open();
- }
- clearInput() {
- this.foundation.clearInput();
- }
- selectAll() {
- this.foundation.selectAll();
- }
- deselectAll() {
- this.foundation.clearSelected();
- }
- focus() {
- this.foundation.focus();
- }
- onSelect(option: OptionProps, optionIndex: number, e: any) {
- this.foundation.onSelect(option, optionIndex, e);
- }
- onClear(e: React.MouseEvent) {
- e.nativeEvent.stopImmediatePropagation();
- this.foundation.handleClearClick(e as any);
- }
- renderEmpty() {
- return <Option empty={true} emptyContent={this.props.emptyContent} />;
- }
- renderLoading() {
- const loadingWrapperCls = `${prefixcls}-loading-wrapper`;
- return (
- <div className={loadingWrapperCls}>
- <Spin />
- </div>
- );
- }
- renderOption(option: OptionProps, optionIndex: number, style?: React.CSSProperties) {
- const { focusIndex, inputValue } = this.state;
- const { renderOptionItem } = this.props;
- let optionContent;
- const isFocused = optionIndex === focusIndex;
- let optionStyle = style || {};
- if (option.style) {
- optionStyle = { ...optionStyle, ...option.style };
- }
- if (option._inputCreateOnly) {
- optionContent = this.renderCreateOption(option, isFocused, optionIndex, style);
- } else {
- // use another name to make sure that 'key' in optionList still exist when we call onChange
- if ('key' in option) {
- option._keyInOptionList = option.key;
- }
- optionContent = (
- <Option
- showTick
- {...option}
- selected={option._selected}
- onSelect={(v: OptionProps, e: MouseEvent) => this.onSelect(v, optionIndex, e)}
- focused={isFocused}
- onMouseEnter={() => this.onOptionHover(optionIndex)}
- style={optionStyle}
- key={option.key || option.label as string + option.value as string + optionIndex}
- renderOptionItem={renderOptionItem}
- inputValue={inputValue}
- >
- {option.label}
- </Option>
- );
- }
- return optionContent;
- }
- renderCreateOption(option: OptionProps, isFocused: boolean, optionIndex: number, style: React.CSSProperties) {
- const { renderCreateItem } = this.props;
- // default render method
- if (typeof renderCreateItem === 'undefined') {
- const defaultCreateItem = (
- <Option
- key={option.key || option.label as string + option.value as string}
- onSelect={(v: OptionProps, e: MouseEvent) => this.onSelect(v, optionIndex, e)}
- onMouseEnter={() => this.onOptionHover(optionIndex)}
- showTick
- {...option}
- focused={isFocused}
- style={style}
- >
- <LocaleCosumer componentName="Select">
- {(locale: Locale['Select']) => (
- <>
- <span className={`${prefixcls}-create-tips`}>{locale.createText}</span>
- {option.value}
- </>
- )}
- </LocaleCosumer>
- </Option>
- );
- return defaultCreateItem;
- }
- const customCreateItem = renderCreateItem(option.value, isFocused);
- return (
- <div onClick={e => this.onSelect(option, optionIndex, e)} key={new Date().valueOf()}>
- {customCreateItem}
- </div>
- );
- }
- onOptionHover(optionIndex: number) {
- this.foundation.handleOptionMouseEnter(optionIndex);
- }
- renderWithGroup(visibileOptions: OptionProps[]) {
- const content: JSX.Element[] = [];
- const groupStatus = new Map();
- visibileOptions.forEach((option, optionIndex) => {
- const parentGroup = option._parentGroup;
- const optionContent = this.renderOption(option, optionIndex);
- if (parentGroup && groupStatus.has(parentGroup.label)) {
- // group content already insert
- content.push(optionContent);
- } else if (parentGroup) {
- const groupContent = <OptionGroup {...parentGroup} key={parentGroup.label} />;
- groupStatus.set(parentGroup.label, true);
- content.push(groupContent);
- content.push(optionContent);
- } else {
- // when not use with OptionGroup
- content.push(optionContent);
- }
- });
- return content;
- }
- renderVirtualizeList(visibileOptions: OptionProps[]) {
- const { virtualize } = this.props;
- const { direction } = this.context;
- const { height, width, itemSize } = virtualize;
- return (
- <List
- height={height || numbers.LIST_HEIGHT}
- itemCount={visibileOptions.length}
- itemSize={itemSize}
- itemData={{ visibileOptions, renderOption: this.renderOption }}
- width={width || '100%'}
- style={{ direction }}
- >
- {VirtualRow}
- </List>
- );
- }
- renderOptions(children?: React.ReactNode) {
- const { dropdownMinWidth, options, selections } = this.state;
- const {
- maxHeight,
- dropdownClassName,
- dropdownStyle,
- outerTopSlot,
- innerTopSlot,
- outerBottomSlot,
- innerBottomSlot,
- loading,
- virtualize,
- } = this.props;
- // Do a filter first, instead of directly judging in forEach, so that the focusIndex can correspond to
- const visibileOptions = options.filter(item => item._show);
- let listContent: JSX.Element | JSX.Element[] = this.renderWithGroup(visibileOptions);
- if (virtualize) {
- listContent = this.renderVirtualizeList(visibileOptions);
- }
- const style = { minWidth: dropdownMinWidth, ...dropdownStyle };
- const optionListCls = cls({
- [`${prefixcls}-option-list`]: true,
- [`${prefixcls}-option-list-chosen`]: selections.size,
- });
- const isEmpty = !options.length || !options.some(item => item._show);
- return (
- <div className={dropdownClassName} style={style}>
- {outerTopSlot}
- <div
- style={{ maxHeight: `${maxHeight}px` }}
- className={optionListCls}
- role="listbox"
- onScroll={e => this.foundation.handleListScroll(e)}
- >
- {innerTopSlot}
- {!loading ? listContent : this.renderLoading()}
- {isEmpty && !loading ? this.renderEmpty() : null}
- {innerBottomSlot}
- </div>
- {outerBottomSlot}
- </div>
- );
- }
- renderSingleSelection(selections: Map<OptionProps['label'], any>, filterable: boolean) {
- let { renderSelectedItem } = this.props;
- const { placeholder } = this.props;
- const { showInput, inputValue } = this.state;
- let renderText: React.ReactNode = '';
- const selectedItems = [...selections];
- if (typeof renderSelectedItem === 'undefined') {
- renderSelectedItem = ((optionNode: OptionProps) => optionNode.label) as RenderSelectedItemFn;
- }
- if (selectedItems.length) {
- const selectedItem = selectedItems[0][1];
- renderText = (renderSelectedItem as RenderSingleSelectedItemFn)(selectedItem);
- }
- const spanCls = cls({
- [`${prefixcls}-selection-text`]: true,
- [`${prefixcls}-selection-placeholder`]: !renderText && renderText !== 0,
- [`${prefixcls}-selection-text-hide`]: inputValue && showInput, // show Input
- [`${prefixcls}-selection-text-inactive`]: !inputValue && showInput, // Stack Input & RenderText(opacity 0.4)
- });
- const contentWrapperCls = `${prefixcls}-content-wrapper`;
- return (
- <>
- <div className={contentWrapperCls}>
- {<span className={spanCls}>{renderText || renderText === 0 ? renderText : placeholder}</span>}
- {filterable && showInput ? this.renderInput() : null}
- </div>
- </>
- );
- }
- renderMultipleSelection(selections: Map<OptionProps['label'], any>, filterable: boolean) {
- let { renderSelectedItem } = this.props;
- const { placeholder, maxTagCount, size } = this.props;
- const { inputValue } = this.state;
- const selectDisabled = this.props.disabled;
- const renderTags = [];
- const selectedItems = [...selections];
- if (typeof renderSelectedItem === 'undefined') {
- renderSelectedItem = (optionNode: OptionProps) => ({
- isRenderInTag: true,
- content: optionNode.label,
- });
- }
- const tags = selectedItems.map((item, i) => {
- const label = item[0];
- const { value } = item[1];
- const disabled = item[1].disabled || selectDisabled;
- const onClose = (tagContent: React.ReactNode, e: MouseEvent) => {
- if (e && typeof e.preventDefault === 'function') {
- e.preventDefault(); // make sure that tag will not hidden immediately in controlled mode
- }
- this.foundation.removeTag({ label, value });
- };
- const { content, isRenderInTag } = (renderSelectedItem as RenderMultipleSelectedItemFn)(item[1], { index: i, disabled, onClose });
- const basic = {
- disabled,
- closable: !disabled,
- onClose,
- };
- if (isRenderInTag) {
- return (
- <Tag {...basic} color="white" size={size || 'large'} key={value}>
- {content}
- </Tag>
- );
- } else {
- return content;
- }
- });
- const contentWrapperCls = cls({
- [`${prefixcls}-content-wrapper`]: true,
- [`${prefixcls}-content-wrapper-one-line`]: maxTagCount,
- [`${prefixcls}-content-wrapper-empty`]: !tags.length,
- });
- const spanCls = cls({
- [`${prefixcls}-selection-text`]: true,
- [`${prefixcls}-selection-placeholder`]: !tags.length,
- [`${prefixcls}-selection-text-hide`]: tags && tags.length,
- // [prefixcls + '-selection-text-inactive']: !inputValue && !tags.length,
- });
- const placeholderText = placeholder && !inputValue ? <span className={spanCls}>{placeholder}</span> : null;
- const n = tags.length > maxTagCount ? maxTagCount : undefined;
- const NotOneLine = !maxTagCount; // Multiple lines (that is, do not set maxTagCount), do not use TagGroup, directly traverse with Tag, otherwise Input cannot follow the correct position
- const tagContent = NotOneLine ? tags : <TagGroup tagList={tags} maxTagCount={n} size="large" mode="custom" />;
- return (
- <>
- <div className={contentWrapperCls}>
- {tags && tags.length ? tagContent : placeholderText}
- {!filterable ? null : this.renderInput()}
- </div>
- </>
- );
- }
- onMouseEnter(e: MouseEvent) {
- this.foundation.handleMouseEnter(e as any);
- }
- onMouseLeave(e: MouseEvent) {
- this.foundation.handleMouseLeave(e as any);
- }
- renderSuffix() {
- const { suffix } = this.props;
- const suffixWrapperCls = cls({
- [`${prefixcls}-suffix`]: true,
- [`${prefixcls}-suffix-text`]: suffix && isString(suffix),
- [`${prefixcls}-suffix-icon`]: isSemiIcon(suffix),
- });
- return <div className={suffixWrapperCls}>{suffix}</div>;
- }
- renderPrefix() {
- const { prefix, insetLabel } = this.props;
- const labelNode = (prefix || insetLabel) as React.ReactElement<any, any>;
- const prefixWrapperCls = cls({
- [`${prefixcls}-prefix`]: true,
- [`${prefixcls}-inset-label`]: insetLabel,
- [`${prefixcls}-prefix-text`]: labelNode && isString(labelNode),
- [`${prefixcls}-prefix-icon`]: isSemiIcon(labelNode),
- });
- return <div className={prefixWrapperCls}>{labelNode}</div>;
- }
- renderSelection() {
- const {
- disabled,
- multiple,
- filter,
- style,
- size,
- className,
- validateStatus,
- showArrow,
- suffix,
- prefix,
- insetLabel,
- placeholder,
- triggerRender,
- arrowIcon,
- } = this.props;
- const { selections, isOpen, keyboardEventSet, inputValue, isHovering, isFocus } = this.state;
- const useCustomTrigger = typeof triggerRender === 'function';
- const filterable = Boolean(filter); // filter(boolean || function)
- const selectionCls = useCustomTrigger ?
- cls(className) :
- cls(prefixcls, className, {
- [`${prefixcls}-open`]: isOpen,
- [`${prefixcls}-focus`]: isFocus,
- [`${prefixcls}-disabled`]: disabled,
- [`${prefixcls}-single`]: !multiple,
- [`${prefixcls}-multiple`]: multiple,
- [`${prefixcls}-filterable`]: filterable,
- [`${prefixcls}-small`]: size === 'small',
- [`${prefixcls}-large`]: size === 'large',
- [`${prefixcls}-error`]: validateStatus === 'error',
- [`${prefixcls}-warning`]: validateStatus === 'warning',
- [`${prefixcls}-no-arrow`]: !showArrow,
- [`${prefixcls}-with-prefix`]: prefix || insetLabel,
- [`${prefixcls}-with-suffix`]: suffix,
- });
- const showClear = this.props.showClear &&
- (selections.size || inputValue) && !disabled && (isHovering || isOpen);
- const arrowContent = showArrow ? (
- <div className={`${prefixcls}-arrow`}>
- {arrowIcon}
- </div>
- ) : (
- <div className={`${prefixcls}-arrow-empty`} />
- );
- const inner = useCustomTrigger ? (
- <Trigger
- value={Array.from(selections.values())}
- inputValue={inputValue}
- onChange={this.handleInputChange}
- onClear={this.onClear}
- disabled={disabled}
- triggerRender={triggerRender}
- placeholder={placeholder as any}
- componentName="Select"
- componentProps={{ ...this.props }}
- />
- ) : (
- [
- <Fragment key="prefix">{prefix || insetLabel ? this.renderPrefix() : null}</Fragment>,
- <Fragment key="selection">
- <div className={cls(`${prefixcls}-selection`)}>
- {multiple ?
- this.renderMultipleSelection(selections, filterable) :
- this.renderSingleSelection(selections, filterable)}
- </div>
- </Fragment>,
- <Fragment key="clearicon">
- {showClear ? (
- <div className={cls(`${prefixcls}-clear`)} onClick={this.onClear}>
- <IconClear />
- </div>
- ) : arrowContent}
- </Fragment>,
- <Fragment key="suffix">{suffix ? this.renderSuffix() : null}</Fragment>,
- ]
- );
- const tabIndex = disabled ? null : 0;
- return (
- <div
- className={selectionCls}
- ref={ref => ((this.triggerRef as any).current = ref)}
- onClick={e => this.foundation.handleClick(e)}
- style={style}
- tabIndex={tabIndex}
- onMouseEnter={this.onMouseEnter}
- onMouseLeave={this.onMouseLeave}
- // onFocus={e => this.foundation.handleTriggerFocus(e)}
- onBlur={e => this.foundation.handleTriggerBlur(e as any)}
- {...keyboardEventSet}
- >
- {inner}
- </div>
- );
- }
- render() {
- const { direction } = this.context;
- const defaultPosition = direction === 'rtl' ? 'bottomRight' : 'bottomLeft';
- const {
- children,
- position = defaultPosition,
- zIndex,
- getPopupContainer,
- motion,
- autoAdjustOverflow,
- mouseLeaveDelay,
- mouseEnterDelay,
- spacing,
- stopPropagation,
- } = this.props;
- const { isOpen, optionKey } = this.state;
- const optionList = this.renderOptions(children);
- const selection = this.renderSelection();
- return (
- <Popover
- getPopupContainer={getPopupContainer}
- motion={motion}
- autoAdjustOverflow={autoAdjustOverflow}
- mouseLeaveDelay={mouseLeaveDelay}
- mouseEnterDelay={mouseEnterDelay}
- // transformFromCenter TODO: check no such property
- zIndex={zIndex}
- ref={this.optionsRef}
- content={optionList}
- visible={isOpen}
- trigger="custom"
- rePosKey={optionKey}
- position={position}
- spacing={spacing}
- stopPropagation={stopPropagation}
- >
- {selection}
- </Popover>
- );
- }
- }
- export default Select;
|