index.tsx 42 KB

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