index.tsx 39 KB

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