index.tsx 38 KB

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