index.tsx 38 KB

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