index.tsx 37 KB

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