index.tsx 38 KB

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