index.tsx 39 KB

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