index.tsx 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. import React, { Fragment, ReactNode, CSSProperties, MouseEvent, KeyboardEvent } from 'react';
  2. import ReactDOM from 'react-dom';
  3. import cls from 'classnames';
  4. import PropTypes from 'prop-types';
  5. import CascaderFoundation, {
  6. /* Corresponding to the state of react */
  7. BasicCascaderInnerData,
  8. /* Corresponding to the props of react */
  9. BasicCascaderProps,
  10. BasicTriggerRenderProps,
  11. BasicScrollPanelProps,
  12. CascaderAdapter,
  13. CascaderType
  14. } from '@douyinfe/semi-foundation/cascader/foundation';
  15. import { cssClasses, strings } from '@douyinfe/semi-foundation/cascader/constants';
  16. import { numbers as popoverNumbers } from '@douyinfe/semi-foundation/popover/constants';
  17. import { isSet, isEqual, isString, isEmpty, isFunction, isNumber, noop, flatten } from 'lodash';
  18. import '@douyinfe/semi-foundation/cascader/cascader.scss';
  19. import { IconClear, IconChevronDown } from '@douyinfe/semi-icons';
  20. import { findKeysForValues, convertDataToEntities, calcMergeType } from '@douyinfe/semi-foundation/cascader/util';
  21. import { calcCheckedKeys, normalizeKeyList, calcDisabledKeys } from '@douyinfe/semi-foundation/tree/treeUtil';
  22. import ConfigContext, { ContextValue } from '../configProvider/context';
  23. import BaseComponent, { ValidateStatus } from '../_base/baseComponent';
  24. import Input from '../input/index';
  25. import Popover, { PopoverProps } from '../popover/index';
  26. import Item, { CascaderData, Entities, Entity, Data, FilterRenderProps } from './item';
  27. import Trigger from '../trigger';
  28. import Tag from '../tag';
  29. import TagInput from '../tagInput';
  30. import { isSemiIcon } from '../_utils';
  31. import { Position } from '../tooltip/index';
  32. export type { CascaderType, ShowNextType } from '@douyinfe/semi-foundation/cascader/foundation';
  33. export type { CascaderData, Entity, Data, CascaderItemProps, FilterRenderProps } from './item';
  34. export interface ScrollPanelProps extends BasicScrollPanelProps {
  35. activeNode: CascaderData
  36. }
  37. export interface TriggerRenderProps extends BasicTriggerRenderProps {
  38. componentProps: CascaderProps;
  39. onClear: (e: React.MouseEvent) => void
  40. }
  41. /* The basic type of the value of Cascader */
  42. export type SimpleValueType = string | number | CascaderData;
  43. /* The value of Cascader */
  44. export type Value = SimpleValueType | Array<SimpleValueType> | Array<Array<SimpleValueType>>;
  45. export interface CascaderProps extends BasicCascaderProps {
  46. 'aria-describedby'?: React.AriaAttributes['aria-describedby'];
  47. 'aria-errormessage'?: React.AriaAttributes['aria-errormessage'];
  48. 'aria-invalid'?: React.AriaAttributes['aria-invalid'];
  49. 'aria-labelledby'?: React.AriaAttributes['aria-labelledby'];
  50. 'aria-required'?: React.AriaAttributes['aria-required'];
  51. 'aria-label'?: React.AriaAttributes['aria-label'];
  52. arrowIcon?: ReactNode;
  53. clearIcon?: ReactNode;
  54. defaultValue?: Value;
  55. dropdownStyle?: CSSProperties;
  56. dropdownMargin?: PopoverProps['margin'];
  57. emptyContent?: ReactNode;
  58. motion?: boolean;
  59. filterTreeNode?: ((inputValue: string, treeNodeString: string, data?: CascaderData) => boolean) | boolean;
  60. filterSorter?: (first: CascaderData, second: CascaderData, inputValue: string) => number;
  61. filterRender?: (props: FilterRenderProps) => ReactNode;
  62. treeData?: Array<CascaderData>;
  63. restTagsPopoverProps?: PopoverProps;
  64. children?: React.ReactNode;
  65. value?: Value;
  66. prefix?: ReactNode;
  67. suffix?: ReactNode;
  68. id?: string;
  69. insetLabel?: ReactNode;
  70. insetLabelId?: string;
  71. style?: CSSProperties;
  72. bottomSlot?: ReactNode;
  73. topSlot?: ReactNode;
  74. triggerRender?: (props: TriggerRenderProps) => ReactNode;
  75. onListScroll?: (e: React.UIEvent<HTMLUListElement, UIEvent>, panel: ScrollPanelProps) => void;
  76. loadData?: (selectOptions: CascaderData[]) => Promise<void>;
  77. onLoad?: (newLoadedKeys: Set<string>, data: CascaderData) => void;
  78. onChange?: (value: Value) => void;
  79. onExceed?: (checkedItem: Entity[]) => void;
  80. displayRender?: (selected: Array<string> | Entity, idx?: number) => ReactNode;
  81. onBlur?: (e: MouseEvent) => void;
  82. onFocus?: (e: MouseEvent) => void;
  83. validateStatus?: ValidateStatus;
  84. position?: Position
  85. }
  86. export interface CascaderState extends BasicCascaderInnerData {
  87. keyEntities: Entities;
  88. prevProps: CascaderProps;
  89. treeData?: Array<CascaderData>
  90. }
  91. const prefixcls = cssClasses.PREFIX;
  92. const resetkey = 0;
  93. class Cascader extends BaseComponent<CascaderProps, CascaderState> {
  94. static contextType = ConfigContext;
  95. static propTypes = {
  96. 'aria-labelledby': PropTypes.string,
  97. 'aria-invalid': PropTypes.bool,
  98. 'aria-errormessage': PropTypes.string,
  99. 'aria-describedby': PropTypes.string,
  100. 'aria-required': PropTypes.bool,
  101. 'aria-label': PropTypes.string,
  102. arrowIcon: PropTypes.node,
  103. borderless: PropTypes.bool,
  104. clearIcon: PropTypes.node,
  105. changeOnSelect: PropTypes.bool,
  106. defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  107. disabled: PropTypes.bool,
  108. dropdownClassName: PropTypes.string,
  109. dropdownStyle: PropTypes.object,
  110. dropdownMargin: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
  111. emptyContent: PropTypes.node,
  112. motion: PropTypes.bool,
  113. /* show search input, if passed in a function, used as custom filter */
  114. filterTreeNode: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
  115. filterLeafOnly: PropTypes.bool,
  116. placeholder: PropTypes.string,
  117. searchPlaceholder: PropTypes.string,
  118. size: PropTypes.oneOf<CascaderType>(strings.SIZE_SET),
  119. style: PropTypes.object,
  120. className: PropTypes.string,
  121. treeData: PropTypes.arrayOf(
  122. PropTypes.shape({
  123. value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  124. label: PropTypes.any,
  125. })
  126. ),
  127. treeNodeFilterProp: PropTypes.string,
  128. suffix: PropTypes.node,
  129. prefix: PropTypes.node,
  130. insetLabel: PropTypes.node,
  131. insetLabelId: PropTypes.string,
  132. id: PropTypes.string,
  133. displayProp: PropTypes.string,
  134. displayRender: PropTypes.func,
  135. onChange: PropTypes.func,
  136. onSearch: PropTypes.func,
  137. onSelect: PropTypes.func,
  138. onBlur: PropTypes.func,
  139. onFocus: PropTypes.func,
  140. children: PropTypes.node,
  141. getPopupContainer: PropTypes.func,
  142. zIndex: PropTypes.number,
  143. value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.array]),
  144. validateStatus: PropTypes.oneOf<CascaderProps['validateStatus']>(strings.VALIDATE_STATUS),
  145. showNext: PropTypes.oneOf([strings.SHOW_NEXT_BY_CLICK, strings.SHOW_NEXT_BY_HOVER]),
  146. stopPropagation: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
  147. showClear: PropTypes.bool,
  148. defaultOpen: PropTypes.bool,
  149. autoAdjustOverflow: PropTypes.bool,
  150. onDropdownVisibleChange: PropTypes.func,
  151. triggerRender: PropTypes.func,
  152. onListScroll: PropTypes.func,
  153. onChangeWithObject: PropTypes.bool,
  154. bottomSlot: PropTypes.node,
  155. topSlot: PropTypes.node,
  156. multiple: PropTypes.bool,
  157. autoMergeValue: PropTypes.bool,
  158. maxTagCount: PropTypes.number,
  159. showRestTagsPopover: PropTypes.bool,
  160. restTagsPopoverProps: PropTypes.object,
  161. max: PropTypes.number,
  162. separator: PropTypes.string,
  163. onExceed: PropTypes.func,
  164. onClear: PropTypes.func,
  165. loadData: PropTypes.func,
  166. onLoad: PropTypes.func,
  167. loadedKeys: PropTypes.array,
  168. disableStrictly: PropTypes.bool,
  169. leafOnly: PropTypes.bool,
  170. enableLeafClick: PropTypes.bool,
  171. preventScroll: PropTypes.bool,
  172. position: PropTypes.string
  173. };
  174. static defaultProps = {
  175. borderless: false,
  176. leafOnly: false,
  177. arrowIcon: <IconChevronDown />,
  178. stopPropagation: true,
  179. motion: true,
  180. defaultOpen: false,
  181. zIndex: popoverNumbers.DEFAULT_Z_INDEX,
  182. showClear: false,
  183. autoClearSearchValue: true,
  184. changeOnSelect: false,
  185. disableStrictly: false,
  186. autoMergeValue: true,
  187. multiple: false,
  188. filterTreeNode: false,
  189. filterLeafOnly: true,
  190. showRestTagsPopover: false,
  191. restTagsPopoverProps: {},
  192. separator: ' / ',
  193. size: 'default' as const,
  194. treeNodeFilterProp: 'label' as const,
  195. displayProp: 'label' as const,
  196. treeData: [] as Array<CascaderData>,
  197. showNext: strings.SHOW_NEXT_BY_CLICK,
  198. onExceed: noop,
  199. onClear: noop,
  200. onDropdownVisibleChange: noop,
  201. onListScroll: noop,
  202. enableLeafClick: false,
  203. 'aria-label': 'Cascader',
  204. };
  205. options: any;
  206. isEmpty: boolean;
  207. inputRef: React.RefObject<typeof Input>;
  208. triggerRef: React.RefObject<HTMLDivElement>;
  209. optionsRef: React.RefObject<any>;
  210. clickOutsideHandler: any;
  211. mergeType: string;
  212. context: ContextValue;
  213. constructor(props: CascaderProps) {
  214. super(props);
  215. this.state = {
  216. disabledKeys: new Set(),
  217. isOpen: props.defaultOpen,
  218. /* By changing rePosKey, the dropdown position can be refreshed */
  219. rePosKey: resetkey,
  220. /* A data structure for storing cascader data items */
  221. keyEntities: {},
  222. /* Selected and show tick icon */
  223. selectedKeys: new Set([]),
  224. /* The key of the activated node */
  225. activeKeys: new Set([]),
  226. /* The key of the filtered node */
  227. filteredKeys: new Set([]),
  228. /* Value of input box */
  229. inputValue: '',
  230. /* Is searching */
  231. isSearching: false,
  232. /* The placeholder of input box */
  233. inputPlaceHolder: props.searchPlaceholder || props.placeholder,
  234. /* Cache props */
  235. prevProps: {},
  236. /* Is hovering */
  237. isHovering: false,
  238. /* Key of checked node, when multiple */
  239. checkedKeys: new Set([]),
  240. /* Key of half checked node, when multiple */
  241. halfCheckedKeys: new Set([]),
  242. /* Auto merged checkedKeys or leaf checkedKeys, when multiple */
  243. resolvedCheckedKeys: new Set([]),
  244. /* Keys of loaded item */
  245. loadedKeys: new Set(),
  246. /* Keys of loading item */
  247. loadingKeys: new Set(),
  248. /* Mark whether this rendering has triggered asynchronous loading of data */
  249. loading: false,
  250. showInput: false,
  251. };
  252. this.options = {};
  253. this.isEmpty = false;
  254. this.mergeType = calcMergeType(props.autoMergeValue, props.leafOnly);
  255. this.inputRef = React.createRef();
  256. this.triggerRef = React.createRef();
  257. this.optionsRef = React.createRef();
  258. this.clickOutsideHandler = null;
  259. this.foundation = new CascaderFoundation(this.adapter);
  260. }
  261. get adapter(): CascaderAdapter {
  262. const filterAdapter: Pick<CascaderAdapter, 'updateInputValue' | 'updateInputPlaceHolder' | 'focusInput'> = {
  263. updateInputValue: value => {
  264. this.setState({ inputValue: value });
  265. },
  266. updateInputPlaceHolder: value => {
  267. this.setState({ inputPlaceHolder: value });
  268. },
  269. focusInput: () => {
  270. const { preventScroll } = this.props;
  271. if (this.inputRef && this.inputRef.current) {
  272. // TODO: check the reason
  273. (this.inputRef.current as any).focus({ preventScroll });
  274. }
  275. },
  276. };
  277. const cascaderAdapter: Pick<
  278. CascaderAdapter,
  279. 'registerClickOutsideHandler' | 'unregisterClickOutsideHandler' | 'rePositionDropdown'
  280. > = {
  281. registerClickOutsideHandler: cb => {
  282. const clickOutsideHandler = (e: Event) => {
  283. const optionInstance = this.optionsRef && this.optionsRef.current;
  284. const triggerDom = this.triggerRef && this.triggerRef.current;
  285. const optionsDom = ReactDOM.findDOMNode(optionInstance);
  286. const target = e.target as Element;
  287. if (
  288. optionsDom &&
  289. (!optionsDom.contains(target) || !optionsDom.contains(target.parentNode)) &&
  290. triggerDom &&
  291. !triggerDom.contains(target)
  292. ) {
  293. cb(e);
  294. }
  295. };
  296. this.clickOutsideHandler = clickOutsideHandler;
  297. document.addEventListener('mousedown', clickOutsideHandler, false);
  298. },
  299. unregisterClickOutsideHandler: () => {
  300. document.removeEventListener('mousedown', this.clickOutsideHandler, false);
  301. },
  302. rePositionDropdown: () => {
  303. let { rePosKey } = this.state;
  304. rePosKey = rePosKey + 1;
  305. this.setState({ rePosKey });
  306. },
  307. };
  308. return {
  309. ...super.adapter,
  310. ...filterAdapter,
  311. ...cascaderAdapter,
  312. updateStates: states => {
  313. this.setState({ ...states } as CascaderState);
  314. },
  315. openMenu: () => {
  316. this.setState({ isOpen: true });
  317. },
  318. closeMenu: cb => {
  319. this.setState({ isOpen: false }, () => {
  320. cb && cb();
  321. });
  322. },
  323. updateSelection: selectedKeys => this.setState({ selectedKeys }),
  324. notifyChange: value => {
  325. this.props.onChange && this.props.onChange(value);
  326. },
  327. notifySelect: selected => {
  328. this.props.onSelect && this.props.onSelect(selected);
  329. },
  330. notifyOnSearch: input => {
  331. this.props.onSearch && this.props.onSearch(input);
  332. },
  333. notifyFocus: (...v) => {
  334. this.props.onFocus && this.props.onFocus(...v);
  335. },
  336. notifyBlur: (...v) => {
  337. this.props.onBlur && this.props.onBlur(...v);
  338. },
  339. notifyDropdownVisibleChange: visible => {
  340. this.props.onDropdownVisibleChange(visible);
  341. },
  342. toggleHovering: bool => {
  343. this.setState({ isHovering: bool });
  344. },
  345. notifyLoadData: (selectedOpt, callback) => {
  346. const { loadData } = this.props;
  347. if (loadData) {
  348. new Promise<void>(resolve => {
  349. loadData(selectedOpt).then(() => {
  350. callback();
  351. this.setState({ loading: false });
  352. resolve();
  353. });
  354. });
  355. }
  356. },
  357. notifyOnLoad: (newLoadedKeys, data) => {
  358. const { onLoad } = this.props;
  359. onLoad && onLoad(newLoadedKeys, data);
  360. },
  361. notifyListScroll: (e, { panelIndex, activeNode }) => {
  362. this.props.onListScroll(e, { panelIndex, activeNode });
  363. },
  364. notifyOnExceed: data => this.props.onExceed(data),
  365. notifyClear: () => this.props.onClear(),
  366. toggleInputShow: (showInput: boolean, cb: (...args: any) => void) => {
  367. this.setState({ showInput }, () => {
  368. cb();
  369. });
  370. },
  371. updateFocusState: (isFocus: boolean) => {
  372. this.setState({ isFocus });
  373. },
  374. };
  375. }
  376. static getDerivedStateFromProps(props: CascaderProps, prevState: CascaderState) {
  377. const { multiple, value, defaultValue, onChangeWithObject, leafOnly, autoMergeValue } = props;
  378. const { prevProps } = prevState;
  379. let keyEntities = prevState.keyEntities || {};
  380. const newState: Partial<CascaderState> = {};
  381. const needUpdate = (name: string) => {
  382. const firstInProps = isEmpty(prevProps) && name in props;
  383. const nameHasChange = prevProps && !isEqual(prevProps[name], props[name]);
  384. return firstInProps || nameHasChange;
  385. };
  386. const needUpdateData = () => {
  387. const firstInProps = !prevProps && 'treeData' in props;
  388. const treeDataHasChange = prevProps && prevProps.treeData !== props.treeData;
  389. return firstInProps || treeDataHasChange;
  390. };
  391. const getRealKeys = (realValue: Value, keyEntities: Entities) => {
  392. // normallizedValue is used to save the value in two-dimensional array format
  393. let normallizedValue: SimpleValueType[][] = [];
  394. if (Array.isArray(realValue)) {
  395. normallizedValue = Array.isArray(realValue[0])
  396. ? (realValue as SimpleValueType[][])
  397. : ([realValue] as SimpleValueType[][]);
  398. } else {
  399. if (realValue !== undefined) {
  400. normallizedValue = [[realValue]];
  401. }
  402. }
  403. // formatValuePath is used to save value of valuePath
  404. const formatValuePath: (string | number)[][] = [];
  405. normallizedValue.forEach((valueItem: SimpleValueType[]) => {
  406. const formatItem: (string | number)[] = onChangeWithObject ?
  407. (valueItem as CascaderData[]).map(i => i?.value) :
  408. valueItem as (string | number)[];
  409. formatValuePath.push(formatItem);
  410. });
  411. // formatKeys is used to save key of value
  412. const formatKeys: any[] = [];
  413. formatValuePath.forEach(v => {
  414. const formatKeyItem = findKeysForValues(v, keyEntities);
  415. !isEmpty(formatKeyItem) && formatKeys.push(formatKeyItem);
  416. });
  417. return formatKeys;
  418. };
  419. const needUpdateTreeData = needUpdate('treeData') || needUpdateData();
  420. const needUpdateValue = needUpdate('value') || (isEmpty(prevProps) && defaultValue);
  421. if (multiple) {
  422. // when value and treedata need updated
  423. if (needUpdateTreeData || needUpdateValue) {
  424. // update state.keyEntities
  425. if (needUpdateTreeData) {
  426. newState.treeData = props.treeData;
  427. keyEntities = convertDataToEntities(props.treeData);
  428. newState.keyEntities = keyEntities;
  429. }
  430. let realKeys: Array<string> | Set<string> = prevState.checkedKeys;
  431. // when data was updated
  432. if (needUpdateValue) {
  433. const realValue = needUpdate('value') ? value : defaultValue;
  434. realKeys = getRealKeys(realValue, keyEntities);
  435. } else {
  436. // needUpdateValue is false
  437. // if treeData is updated & Cascader is controlled, realKeys should be recalculated
  438. if (needUpdateTreeData && 'value' in props) {
  439. const realValue = value;
  440. realKeys = getRealKeys(realValue, keyEntities);
  441. }
  442. }
  443. if (isSet(realKeys)) {
  444. realKeys = [...realKeys];
  445. }
  446. const calRes = calcCheckedKeys(flatten(realKeys), keyEntities);
  447. const checkedKeys = new Set(calRes.checkedKeys);
  448. const halfCheckedKeys = new Set(calRes.halfCheckedKeys);
  449. // disableStrictly
  450. if (props.disableStrictly) {
  451. newState.disabledKeys = calcDisabledKeys(keyEntities);
  452. }
  453. const isLeafOnlyMerge = calcMergeType(autoMergeValue, leafOnly) === strings.LEAF_ONLY_MERGE_TYPE;
  454. newState.prevProps = props;
  455. newState.checkedKeys = checkedKeys;
  456. newState.halfCheckedKeys = halfCheckedKeys;
  457. newState.resolvedCheckedKeys = new Set(normalizeKeyList(checkedKeys, keyEntities, isLeafOnlyMerge));
  458. }
  459. }
  460. return newState;
  461. }
  462. componentDidMount() {
  463. this.foundation.init();
  464. }
  465. componentWillUnmount() {
  466. this.foundation.destroy();
  467. }
  468. componentDidUpdate(prevProps: CascaderProps) {
  469. let isOptionsChanged = false;
  470. if (!isEqual(prevProps.treeData, this.props.treeData)) {
  471. isOptionsChanged = true;
  472. this.foundation.collectOptions();
  473. }
  474. if (prevProps.value !== this.props.value && !isOptionsChanged) {
  475. this.foundation.handleValueChange(this.props.value);
  476. }
  477. }
  478. handleInputChange = (value: string) => {
  479. this.foundation.handleInputChange(value);
  480. };
  481. handleTagRemove = (e: any, tagValuePath: Array<string | number>) => {
  482. this.foundation.handleTagRemove(e, tagValuePath);
  483. };
  484. handleRemoveByKey = (key) => {
  485. const { keyEntities } = this.state;
  486. this.handleTagRemove(null, keyEntities[key].valuePath);
  487. }
  488. renderTagItem = (value: string | Array<string>, idx: number, type: string) => {
  489. const { keyEntities, disabledKeys } = this.state;
  490. const { size, disabled, displayProp, displayRender, disableStrictly } = this.props;
  491. const nodeKey = type === strings.IS_VALUE ? findKeysForValues(value, keyEntities)[0] : value;
  492. const isDsiabled =
  493. disabled || keyEntities[nodeKey].data.disabled || (disableStrictly && disabledKeys.has(nodeKey));
  494. if (!isEmpty(keyEntities) && !isEmpty(keyEntities[nodeKey])) {
  495. const tagCls = cls(`${prefixcls}-selection-tag`, {
  496. [`${prefixcls}-selection-tag-disabled`]: isDsiabled,
  497. });
  498. // custom render tags
  499. if (isFunction(displayRender)) {
  500. return displayRender(keyEntities[nodeKey], idx);
  501. // default render tags
  502. } else {
  503. return (
  504. <Tag
  505. size={size === 'default' ? 'large' : size}
  506. key={`tag-${nodeKey}-${idx}`}
  507. color="white"
  508. className={tagCls}
  509. closable
  510. onClose={(tagChildren, e) => {
  511. // When value has not changed, prevent clicking tag closeBtn to close tag
  512. e.preventDefault();
  513. this.handleTagRemove(e, keyEntities[nodeKey].valuePath);
  514. }}
  515. >
  516. {keyEntities[nodeKey].data[displayProp]}
  517. </Tag>
  518. );
  519. }
  520. }
  521. return null;
  522. };
  523. renderTagInput() {
  524. const { size, disabled, placeholder, maxTagCount, showRestTagsPopover, restTagsPopoverProps } = this.props;
  525. const { inputValue, checkedKeys, keyEntities, resolvedCheckedKeys } = this.state;
  526. const tagInputcls = cls(`${prefixcls}-tagInput-wrapper`);
  527. const tagValue: Array<Array<string>> = [];
  528. const realKeys = this.mergeType === strings.NONE_MERGE_TYPE ? checkedKeys : resolvedCheckedKeys;
  529. [...realKeys].forEach(checkedKey => {
  530. if (!isEmpty(keyEntities[checkedKey])) {
  531. tagValue.push(keyEntities[checkedKey].valuePath);
  532. }
  533. });
  534. return (
  535. <TagInput
  536. className={tagInputcls}
  537. ref={this.inputRef as any}
  538. disabled={disabled}
  539. size={size}
  540. // TODO Modify logic, not modify type
  541. value={(tagValue as unknown) as string[]}
  542. showRestTagsPopover={showRestTagsPopover}
  543. restTagsPopoverProps={restTagsPopoverProps}
  544. maxTagCount={maxTagCount}
  545. renderTagItem={(value, index) => this.renderTagItem(value, index, strings.IS_VALUE)}
  546. inputValue={inputValue}
  547. onInputChange={this.handleInputChange}
  548. // TODO Modify logic, not modify type
  549. onRemove={v => this.handleTagRemove(null, (v as unknown) as (string | number)[])}
  550. placeholder={placeholder}
  551. expandRestTagsOnClick={false}
  552. />
  553. );
  554. }
  555. renderInput() {
  556. const { size, disabled } = this.props;
  557. const inputcls = cls(`${prefixcls}-input`);
  558. const { inputValue, inputPlaceHolder, showInput } = this.state;
  559. const inputProps = {
  560. disabled,
  561. value: inputValue,
  562. className: inputcls,
  563. onChange: this.handleInputChange,
  564. };
  565. const wrappercls = cls({
  566. [`${prefixcls}-search-wrapper`]: true,
  567. [`${prefixcls}-search-wrapper-${size}`]: size !== 'default',
  568. });
  569. const displayText = this.renderDisplayText();
  570. const spanCls = cls({
  571. [`${prefixcls}-selection-placeholder`]: !displayText,
  572. [`${prefixcls}-selection-text-hide`]: showInput && inputValue,
  573. [`${prefixcls}-selection-text-inactive`]: showInput && !inputValue,
  574. });
  575. return (
  576. <div className={wrappercls}>
  577. <span className={spanCls}>{displayText ? displayText : inputPlaceHolder}</span>
  578. {showInput && <Input ref={this.inputRef as any} size={size} {...inputProps} />}
  579. </div>
  580. );
  581. }
  582. handleItemClick = (e: MouseEvent | KeyboardEvent, item: Entity | Data) => {
  583. this.foundation.handleItemClick(e, item);
  584. };
  585. handleItemHover = (e: MouseEvent, item: Entity) => {
  586. this.foundation.handleItemHover(e, item);
  587. };
  588. onItemCheckboxClick = (item: Entity | Data) => {
  589. this.foundation.onItemCheckboxClick(item);
  590. };
  591. handleListScroll = (e: React.UIEvent<HTMLUListElement, UIEvent>, ind: number) => {
  592. this.foundation.handleListScroll(e, ind);
  593. };
  594. close() {
  595. this.foundation.close();
  596. }
  597. open() {
  598. this.foundation.open();
  599. }
  600. renderContent = () => {
  601. const {
  602. inputValue,
  603. isSearching,
  604. activeKeys,
  605. selectedKeys,
  606. checkedKeys,
  607. halfCheckedKeys,
  608. loadedKeys,
  609. loadingKeys,
  610. } = this.state;
  611. const {
  612. filterTreeNode,
  613. dropdownClassName,
  614. dropdownStyle,
  615. loadData,
  616. emptyContent,
  617. separator,
  618. topSlot,
  619. bottomSlot,
  620. showNext,
  621. multiple,
  622. filterRender
  623. } = this.props;
  624. const searchable = Boolean(filterTreeNode) && isSearching;
  625. const popoverCls = cls(dropdownClassName, `${prefixcls}-popover`);
  626. const renderData = this.foundation.getRenderData();
  627. const content = (
  628. <div className={popoverCls} role="listbox" style={dropdownStyle}>
  629. {topSlot}
  630. <Item
  631. activeKeys={activeKeys}
  632. selectedKeys={selectedKeys}
  633. separator={separator}
  634. loadedKeys={loadedKeys}
  635. loadingKeys={loadingKeys}
  636. onItemClick={this.handleItemClick}
  637. onItemHover={this.handleItemHover}
  638. showNext={showNext}
  639. onItemCheckboxClick={this.onItemCheckboxClick}
  640. onListScroll={this.handleListScroll}
  641. searchable={searchable}
  642. keyword={inputValue}
  643. emptyContent={emptyContent}
  644. loadData={loadData}
  645. data={renderData}
  646. multiple={multiple}
  647. checkedKeys={checkedKeys}
  648. halfCheckedKeys={halfCheckedKeys}
  649. filterRender={filterRender}
  650. />
  651. {bottomSlot}
  652. </div>
  653. );
  654. return content;
  655. };
  656. renderPlusN = (hiddenTag: Array<ReactNode>) => {
  657. const { disabled, showRestTagsPopover, restTagsPopoverProps } = this.props;
  658. const plusNCls = cls(`${prefixcls}-selection-n`, {
  659. [`${prefixcls}-selection-n-disabled`]: disabled,
  660. });
  661. const renderPlusNChildren = <span className={plusNCls}>+{hiddenTag.length}</span>;
  662. return showRestTagsPopover && !disabled ? (
  663. <Popover
  664. content={hiddenTag}
  665. showArrow
  666. trigger="hover"
  667. position="top"
  668. autoAdjustOverflow
  669. {...restTagsPopoverProps}
  670. >
  671. {renderPlusNChildren}
  672. </Popover>
  673. ) : (
  674. renderPlusNChildren
  675. );
  676. };
  677. renderMultipleTags = () => {
  678. const { autoMergeValue, maxTagCount } = this.props;
  679. const { checkedKeys, resolvedCheckedKeys } = this.state;
  680. const realKeys = this.mergeType === strings.NONE_MERGE_TYPE ? checkedKeys : resolvedCheckedKeys;
  681. const displayTag: Array<ReactNode> = [];
  682. const hiddenTag: Array<ReactNode> = [];
  683. [...realKeys].forEach((checkedKey, idx) => {
  684. const notExceedMaxTagCount = !isNumber(maxTagCount) || maxTagCount >= idx + 1;
  685. const item = this.renderTagItem(checkedKey, idx, strings.IS_KEY);
  686. if (notExceedMaxTagCount) {
  687. displayTag.push(item);
  688. } else {
  689. hiddenTag.push(item);
  690. }
  691. });
  692. return (
  693. <>
  694. {displayTag}
  695. {!isEmpty(hiddenTag) && this.renderPlusN(hiddenTag)}
  696. </>
  697. );
  698. };
  699. renderDisplayText = (): ReactNode => {
  700. const { displayProp, separator, displayRender } = this.props;
  701. const { selectedKeys } = this.state;
  702. let displayText: ReactNode = '';
  703. if (selectedKeys.size) {
  704. const displayPath = this.foundation.getItemPropPath([...selectedKeys][0], displayProp);
  705. if (displayRender && typeof displayRender === 'function') {
  706. displayText = displayRender(displayPath);
  707. } else {
  708. displayText = displayPath.map((path: ReactNode, index: number) => (
  709. <Fragment key={`${path}-${index}`}>
  710. {index < displayPath.length - 1 ? (
  711. <>
  712. {path}
  713. {separator}
  714. </>
  715. ) : (
  716. path
  717. )}
  718. </Fragment>
  719. ));
  720. }
  721. }
  722. return displayText;
  723. };
  724. renderSelectContent = () => {
  725. const { placeholder, filterTreeNode, multiple } = this.props;
  726. const { checkedKeys } = this.state;
  727. const searchable = Boolean(filterTreeNode);
  728. if (!searchable) {
  729. if (multiple) {
  730. if (isEmpty(checkedKeys)) {
  731. return <span className={`${prefixcls}-selection-placeholder`}>{placeholder}</span>;
  732. }
  733. return this.renderMultipleTags();
  734. } else {
  735. const displayText = this.renderDisplayText();
  736. const spanCls = cls({
  737. [`${prefixcls}-selection-placeholder`]: !displayText,
  738. });
  739. return <span className={spanCls}>{displayText ? displayText : placeholder}</span>;
  740. }
  741. }
  742. const input = multiple ? this.renderTagInput() : this.renderInput();
  743. return input;
  744. };
  745. renderSuffix = () => {
  746. const { suffix }: any = this.props;
  747. const suffixWrapperCls = cls({
  748. [`${prefixcls}-suffix`]: true,
  749. [`${prefixcls}-suffix-text`]: suffix && isString(suffix),
  750. [`${prefixcls}-suffix-icon`]: isSemiIcon(suffix),
  751. });
  752. return (
  753. <div className={suffixWrapperCls} x-semi-prop="suffix">
  754. {suffix}
  755. </div>
  756. );
  757. };
  758. renderPrefix = () => {
  759. const { prefix, insetLabel, insetLabelId } = this.props;
  760. const labelNode: any = prefix || insetLabel;
  761. const prefixWrapperCls = cls({
  762. [`${prefixcls}-prefix`]: true,
  763. // to be doublechecked
  764. [`${prefixcls}-inset-label`]: insetLabel,
  765. [`${prefixcls}-prefix-text`]: labelNode && isString(labelNode),
  766. [`${prefixcls}-prefix-icon`]: isSemiIcon(labelNode),
  767. });
  768. return (
  769. <div className={prefixWrapperCls} id={insetLabelId} x-semi-prop="prefix,insetLabel">
  770. {labelNode}
  771. </div>
  772. );
  773. };
  774. renderCustomTrigger = () => {
  775. const { disabled, triggerRender, multiple } = this.props;
  776. const { selectedKeys, inputValue, inputPlaceHolder, resolvedCheckedKeys, checkedKeys } = this.state;
  777. let realValue;
  778. if (multiple) {
  779. if (this.mergeType === strings.NONE_MERGE_TYPE) {
  780. realValue = checkedKeys;
  781. } else {
  782. realValue = resolvedCheckedKeys;
  783. }
  784. } else {
  785. realValue = [...selectedKeys][0];
  786. }
  787. return (
  788. <Trigger
  789. value={realValue}
  790. inputValue={inputValue}
  791. onChange={this.handleInputChange}
  792. onClear={this.handleClear}
  793. placeholder={inputPlaceHolder}
  794. disabled={disabled}
  795. triggerRender={triggerRender}
  796. componentName={'Cascader'}
  797. componentProps={{ ...this.props }}
  798. onSearch={this.handleInputChange}
  799. onRemove={this.handleRemoveByKey}
  800. />
  801. );
  802. };
  803. handleMouseOver = () => {
  804. this.foundation.toggleHoverState(true);
  805. };
  806. handleMouseLeave = () => {
  807. this.foundation.toggleHoverState(false);
  808. };
  809. handleClear = (e: MouseEvent) => {
  810. e && e.stopPropagation();
  811. this.foundation.handleClear();
  812. };
  813. /**
  814. * A11y: simulate clear button click
  815. */
  816. /* istanbul ignore next */
  817. handleClearEnterPress = (e: KeyboardEvent) => {
  818. e && e.stopPropagation();
  819. this.foundation.handleClearEnterPress(e);
  820. };
  821. showClearBtn = () => {
  822. const { showClear, disabled, multiple } = this.props;
  823. const { selectedKeys, isOpen, isHovering, checkedKeys } = this.state;
  824. const hasValue = selectedKeys.size;
  825. const multipleWithHaveValue = multiple && checkedKeys.size;
  826. return showClear && (hasValue || multipleWithHaveValue) && !disabled && (isOpen || isHovering);
  827. };
  828. renderClearBtn = () => {
  829. const clearCls = cls(`${prefixcls}-clearbtn`);
  830. const { clearIcon } = this.props;
  831. const allowClear = this.showClearBtn();
  832. if (allowClear) {
  833. return (
  834. <div
  835. className={clearCls}
  836. onClick={this.handleClear}
  837. onKeyPress={this.handleClearEnterPress}
  838. role="button"
  839. tabIndex={0}
  840. >
  841. {
  842. clearIcon ? clearIcon : <IconClear />
  843. }
  844. </div>
  845. );
  846. }
  847. return null;
  848. };
  849. renderArrow = () => {
  850. const { arrowIcon } = this.props;
  851. const showClearBtn = this.showClearBtn();
  852. if (showClearBtn) {
  853. return null;
  854. }
  855. return arrowIcon ? (
  856. <div className={cls(`${prefixcls}-arrow`)} x-semi-prop="arrowIcon">
  857. {arrowIcon}
  858. </div>
  859. ) : null;
  860. };
  861. renderSelection = () => {
  862. const {
  863. disabled,
  864. multiple,
  865. filterTreeNode,
  866. style,
  867. size,
  868. className,
  869. validateStatus,
  870. prefix,
  871. suffix,
  872. insetLabel,
  873. triggerRender,
  874. showClear,
  875. id,
  876. borderless,
  877. } = this.props;
  878. const { isOpen, isFocus, isInput, checkedKeys } = this.state;
  879. const filterable = Boolean(filterTreeNode);
  880. const useCustomTrigger = typeof triggerRender === 'function';
  881. const classNames = useCustomTrigger ?
  882. cls(className) :
  883. cls(prefixcls, className, {
  884. [`${prefixcls}-borderless`]: borderless,
  885. [`${prefixcls}-focus`]: isFocus || (isOpen && !isInput),
  886. [`${prefixcls}-disabled`]: disabled,
  887. [`${prefixcls}-single`]: true,
  888. [`${prefixcls}-filterable`]: filterable,
  889. [`${prefixcls}-error`]: validateStatus === 'error',
  890. [`${prefixcls}-warning`]: validateStatus === 'warning',
  891. [`${prefixcls}-small`]: size === 'small',
  892. [`${prefixcls}-large`]: size === 'large',
  893. [`${prefixcls}-with-prefix`]: prefix || insetLabel,
  894. [`${prefixcls}-with-suffix`]: suffix,
  895. });
  896. const mouseEvent = showClear ?
  897. {
  898. onMouseEnter: () => this.handleMouseOver(),
  899. onMouseLeave: () => this.handleMouseLeave(),
  900. } :
  901. {};
  902. const sectionCls = cls(`${prefixcls}-selection`, {
  903. [`${prefixcls}-selection-multiple`]: multiple && !isEmpty(checkedKeys),
  904. });
  905. const inner = useCustomTrigger
  906. ? this.renderCustomTrigger()
  907. : [
  908. <Fragment key={'prefix'}>{prefix || insetLabel ? this.renderPrefix() : null}</Fragment>,
  909. <Fragment key={'selection'}>
  910. <div className={sectionCls}>{this.renderSelectContent()}</div>
  911. </Fragment>,
  912. <Fragment key={'clearbtn'}>{this.renderClearBtn()}</Fragment>,
  913. <Fragment key={'suffix'}>{suffix ? this.renderSuffix() : null}</Fragment>,
  914. <Fragment key={'arrow'}>{this.renderArrow()}</Fragment>,
  915. ];
  916. /**
  917. * Reasons for disabling the a11y eslint rule:
  918. * The following attributes(aria-controls,aria-expanded) will be automatically added by Tooltip, no need to declare here
  919. */
  920. return (
  921. <div
  922. className={classNames}
  923. style={style}
  924. ref={this.triggerRef}
  925. onClick={e => this.foundation.handleClick(e)}
  926. onKeyPress={e => this.foundation.handleSelectionEnterPress(e)}
  927. aria-invalid={this.props['aria-invalid']}
  928. aria-errormessage={this.props['aria-errormessage']}
  929. aria-label={this.props['aria-label']}
  930. aria-labelledby={this.props['aria-labelledby']}
  931. aria-describedby={this.props['aria-describedby']}
  932. aria-required={this.props['aria-required']}
  933. id={id}
  934. {...mouseEvent}
  935. // eslint-disable-next-line jsx-a11y/role-has-required-aria-props
  936. role="combobox"
  937. tabIndex={0}
  938. >
  939. {inner}
  940. </div>
  941. );
  942. };
  943. render() {
  944. const {
  945. zIndex,
  946. getPopupContainer,
  947. autoAdjustOverflow,
  948. stopPropagation,
  949. mouseLeaveDelay,
  950. mouseEnterDelay,
  951. position,
  952. motion,
  953. dropdownMargin,
  954. } = this.props;
  955. const { isOpen, rePosKey } = this.state;
  956. const { direction } = this.context;
  957. const content = this.renderContent();
  958. const selection = this.renderSelection();
  959. const pos = position ?? (direction === 'rtl' ? 'bottomRight' : 'bottomLeft');
  960. return (
  961. <Popover
  962. getPopupContainer={getPopupContainer}
  963. zIndex={zIndex}
  964. motion={motion}
  965. margin={dropdownMargin}
  966. ref={this.optionsRef}
  967. content={content}
  968. visible={isOpen}
  969. trigger="custom"
  970. rePosKey={rePosKey}
  971. position={pos}
  972. autoAdjustOverflow={autoAdjustOverflow}
  973. stopPropagation={stopPropagation}
  974. mouseLeaveDelay={mouseLeaveDelay}
  975. mouseEnterDelay={mouseEnterDelay}
  976. afterClose={()=>this.foundation.updateSearching(false)}
  977. >
  978. {selection}
  979. </Popover>
  980. );
  981. }
  982. }
  983. export default Cascader;