index.tsx 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. import React, { Fragment } from 'react';
  2. import ReactDOM from 'react-dom';
  3. import cls from 'classnames';
  4. import PropTypes from 'prop-types';
  5. import { isEqual, isString, isEmpty, noop, get, isFunction } from 'lodash-es';
  6. import TreeSelectFoundation, {
  7. Size,
  8. BasicTriggerRenderProps,
  9. /* Corresponding props */
  10. BasicTreeSelectProps,
  11. /* Corresponding state */
  12. BasicTreeSelectInnerData,
  13. TreeSelectAdapter
  14. } from '@douyinfe/semi-foundation/treeSelect/foundation';
  15. import {
  16. convertDataToEntities,
  17. flattenTreeData,
  18. calcExpandedKeysForValues,
  19. calcMotionKeys,
  20. findKeysForValues,
  21. calcCheckedKeys,
  22. calcExpandedKeys,
  23. getValueOrKey,
  24. normalizeKeyList,
  25. calcDisabledKeys,
  26. normalizeValue
  27. } from '@douyinfe/semi-foundation/tree/treeUtil';
  28. import { cssClasses, strings } from '@douyinfe/semi-foundation/treeSelect/constants';
  29. import { numbers as popoverNumbers } from '@douyinfe/semi-foundation/popover/constants';
  30. import { FixedSizeList as VirtualList } from 'react-window';
  31. import '@douyinfe/semi-foundation/tree/tree.scss';
  32. import '@douyinfe/semi-foundation/treeSelect/treeSelect.scss';
  33. import BaseComponent, { ValidateStatus } from '../_base/baseComponent';
  34. import ConfigContext from '../configProvider/context';
  35. import TagGroup from '../tag/group';
  36. import Tag, { TagProps } from '../tag/index';
  37. import Input, { InputProps } from '../input/index';
  38. import Popover from '../popover/index';
  39. import AutoSizer from '../tree/autoSizer';
  40. import TreeContext from '../tree/treeContext';
  41. import TreeNode from '../tree/treeNode';
  42. import NodeList from '../tree/nodeList';
  43. import { cloneDeep } from '../tree/treeUtil';
  44. import LocaleConsumer from '../locale/localeConsumer';
  45. import { Locale } from '../locale/interface';
  46. import Trigger from '../trigger';
  47. import TagInput from '../tagInput';
  48. import { isSemiIcon } from '../_utils';
  49. import { OptionProps, TreeProps, TreeState, FlattenNode, TreeNodeData, TreeNodeProps } from '../tree/interface';
  50. import { Motion } from '../_base/base';
  51. import { IconChevronDown, IconClear, IconSearch } from '@douyinfe/semi-icons';
  52. export type ExpandAction = false | 'click' | 'doubleClick';
  53. export interface TriggerRenderProps extends Omit<BasicTriggerRenderProps, 'componentProps'> {
  54. [x: string]: any;
  55. componentProps: TreeSelectProps;
  56. value: TreeNodeData[];
  57. onClear: (e: React.MouseEvent) => void;
  58. }
  59. export interface OnChange {
  60. /* onChangeWithObject is false */
  61. (
  62. value: TreeNodeData['value'] | Array<TreeNodeData['value']>,
  63. node: TreeNodeData[] | TreeNodeData,
  64. e: React.MouseEvent
  65. ): void;
  66. /* onChangeWithObject is true */
  67. (node: TreeNodeData[] | TreeNodeData, e: React.MouseEvent): void;
  68. }
  69. export type RenderSelectedItemInSingle = (treeNode: TreeNodeData) => React.ReactNode;
  70. export type RenderSelectedItemInMultiple = (
  71. treeNode: TreeNodeData,
  72. otherProps: { index: number | string; onClose: (tagContent: any, e: React.MouseEvent) => void }
  73. ) => {
  74. isRenderInTag: boolean;
  75. content: React.ReactNode;
  76. };
  77. export interface RenderSelectedItem {
  78. (treeNode: TreeNodeData): React.ReactNode;
  79. (
  80. treeNode: TreeNodeData,
  81. otherProps: {
  82. index: number | string;
  83. onClose: (tagContent: any, e: React.MouseEvent) => void;
  84. }
  85. ):
  86. {
  87. isRenderInTag: boolean;
  88. content: React.ReactNode;
  89. };
  90. }
  91. export type OverrideCommonProps =
  92. 'renderFullLabel'
  93. | 'renderLabel'
  94. | 'defaultValue'
  95. | 'emptyContent'
  96. | 'filterTreeNode'
  97. | 'style'
  98. | 'treeData'
  99. | 'value'
  100. | 'onExpand';
  101. /**
  102. * Type definition description:
  103. * TreeSelectProps inherits some properties from BasicTreeSelectProps (from foundation) and TreeProps (from semi-ui-react).
  104. */
  105. // eslint-disable-next-line max-len
  106. export interface TreeSelectProps extends Omit<BasicTreeSelectProps, OverrideCommonProps | 'validateStatus' | 'searchRender'>, Pick<TreeProps, OverrideCommonProps>{
  107. motion?: Motion;
  108. mouseEnterDelay?: number;
  109. mouseLeaveDelay?: number;
  110. arrowIcon?: React.ReactNode;
  111. autoAdjustOverflow?: boolean;
  112. clickToHide?: boolean;
  113. defaultOpen?: boolean;
  114. dropdownClassName?: string;
  115. dropdownMatchSelectWidth?: boolean;
  116. dropdownStyle?: React.CSSProperties;
  117. insetLabel?: React.ReactNode;
  118. maxTagCount?: number;
  119. motionExpand?: boolean;
  120. optionListStyle?: React.CSSProperties;
  121. outerBottomSlot?: React.ReactNode;
  122. outerTopSlot?: React.ReactNode;
  123. placeholder?: string;
  124. prefix?: React.ReactNode;
  125. searchAutoFocus?: boolean;
  126. searchPlaceholder?: string;
  127. showSearchClear?: boolean;
  128. size?: Size;
  129. suffix?: React.ReactNode;
  130. treeNodeLabelProp?: string;
  131. validateStatus?: ValidateStatus;
  132. zIndex?: number;
  133. searchPosition?: string;
  134. stopPropagation?: boolean | string;
  135. searchRender?: boolean | ((inputProps: InputProps) => React.ReactNode);
  136. onSelect?: (selectedKeys: string, selected: boolean, selectedNode: TreeNodeData) => void;
  137. renderSelectedItem?: RenderSelectedItem;
  138. getPopupContainer?: () => HTMLElement;
  139. triggerRender?: (props?: TriggerRenderProps) => React.ReactNode;
  140. onBlur?: (e: React.MouseEvent) => void;
  141. onChange?: OnChange;
  142. onFocus?: (e: React.MouseEvent) => void;
  143. onVisibleChange?: (isVisible: boolean) => void;
  144. }
  145. export type OverrideCommonState =
  146. 'keyEntities'
  147. | 'treeData'
  148. | 'disabledKeys'
  149. | 'flattenNodes';
  150. // eslint-disable-next-line max-len
  151. export interface TreeSelectState extends Omit<BasicTreeSelectInnerData, OverrideCommonState | 'prevProps'>, Pick<TreeState, OverrideCommonState> {
  152. inputTriggerFocus: boolean;
  153. isOpen: boolean;
  154. isInput: boolean;
  155. rePosKey: number;
  156. dropdownMinWidth: null | number;
  157. isHovering: boolean;
  158. prevProps: TreeSelectProps;
  159. }
  160. const prefixcls = cssClasses.PREFIX;
  161. const prefixTree = cssClasses.PREFIXTREE;
  162. const key = 0;
  163. class TreeSelect extends BaseComponent<TreeSelectProps, TreeSelectState> {
  164. static contextType = ConfigContext;
  165. static propTypes = {
  166. loadedKeys: PropTypes.arrayOf(PropTypes.string),
  167. loadData: PropTypes.func,
  168. onLoad: PropTypes.func,
  169. arrowIcon: PropTypes.node,
  170. defaultOpen: PropTypes.bool,
  171. defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  172. defaultExpandAll: PropTypes.bool,
  173. defaultExpandedKeys: PropTypes.array,
  174. expandAll: PropTypes.bool,
  175. disabled: PropTypes.bool,
  176. disableStrictly: PropTypes.bool,
  177. // Whether to turn on the input box filtering function, when it is a function, it represents a custom filtering function
  178. filterTreeNode: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
  179. multiple: PropTypes.bool,
  180. searchPlaceholder: PropTypes.string,
  181. searchAutoFocus: PropTypes.bool,
  182. virtualize: PropTypes.object,
  183. treeNodeFilterProp: PropTypes.string,
  184. onChange: PropTypes.func,
  185. onSearch: PropTypes.func,
  186. onSelect: PropTypes.func,
  187. onExpand: PropTypes.func,
  188. onChangeWithObject: PropTypes.bool,
  189. onBlur: PropTypes.func,
  190. onFocus: PropTypes.func,
  191. value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.array, PropTypes.object]),
  192. expandedKeys: PropTypes.array,
  193. autoExpandParent: PropTypes.bool,
  194. showClear: PropTypes.bool,
  195. showSearchClear: PropTypes.bool,
  196. autoAdjustOverflow: PropTypes.bool,
  197. showFilteredOnly: PropTypes.bool,
  198. motionExpand: PropTypes.bool,
  199. emptyContent: PropTypes.node,
  200. leafOnly: PropTypes.bool,
  201. treeData: PropTypes.arrayOf(
  202. PropTypes.shape({
  203. key: PropTypes.string.isRequired,
  204. value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  205. label: PropTypes.any,
  206. })
  207. ),
  208. dropdownClassName: PropTypes.string,
  209. dropdownStyle: PropTypes.object,
  210. motion: PropTypes.oneOfType([PropTypes.bool, PropTypes.object, PropTypes.func]),
  211. placeholder: PropTypes.string,
  212. maxTagCount: PropTypes.number,
  213. size: PropTypes.oneOf<TreeSelectProps['size']>(strings.SIZE_SET),
  214. className: PropTypes.string,
  215. style: PropTypes.object,
  216. treeNodeLabelProp: PropTypes.string,
  217. suffix: PropTypes.node,
  218. prefix: PropTypes.node,
  219. insetLabel: PropTypes.node,
  220. zIndex: PropTypes.number,
  221. getPopupContainer: PropTypes.func,
  222. dropdownMatchSelectWidth: PropTypes.bool,
  223. validateStatus: PropTypes.oneOf(strings.STATUS),
  224. mouseEnterDelay: PropTypes.number,
  225. mouseLeaveDelay: PropTypes.number,
  226. triggerRender: PropTypes.func,
  227. stopPropagation: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
  228. outerBottomSlot: PropTypes.node,
  229. outerTopSlot: PropTypes.node,
  230. onVisibleChange: PropTypes.func,
  231. expandAction: PropTypes.oneOf(['click' as const, 'doubleClick' as const, false as const]),
  232. searchPosition: PropTypes.oneOf([strings.SEARCH_POSITION_DROPDOWN, strings.SEARCH_POSITION_TRIGGER]),
  233. clickToHide: PropTypes.bool,
  234. renderLabel: PropTypes.func,
  235. renderFullLabel: PropTypes.func,
  236. labelEllipsis: PropTypes.bool,
  237. optionListStyle: PropTypes.object,
  238. searchRender: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
  239. renderSelectedItem: PropTypes.func,
  240. };
  241. static defaultProps: Partial<TreeSelectProps> = {
  242. searchPosition: strings.SEARCH_POSITION_DROPDOWN,
  243. arrowIcon: <IconChevronDown />,
  244. autoExpandParent: false,
  245. autoAdjustOverflow: true,
  246. stopPropagation: true,
  247. motion: true,
  248. motionExpand: true,
  249. expandAll: false,
  250. zIndex: popoverNumbers.DEFAULT_Z_INDEX,
  251. disabled: false,
  252. disableStrictly: false,
  253. multiple: false,
  254. filterTreeNode: false,
  255. size: 'default' as const,
  256. treeNodeFilterProp: 'label' as const,
  257. onChangeWithObject: false,
  258. treeNodeLabelProp: 'label' as const,
  259. dropdownMatchSelectWidth: true,
  260. defaultOpen: false,
  261. showSearchClear: true,
  262. showClear: false,
  263. onVisibleChange: noop,
  264. expandAction: false,
  265. clickToHide: true,
  266. searchAutoFocus: false,
  267. };
  268. inputRef: React.RefObject<typeof Input>;
  269. tagInputRef: React.RefObject<TagInput>;
  270. triggerRef: React.RefObject<HTMLDivElement>;
  271. optionsRef: React.RefObject<any>;
  272. clickOutsideHandler: any;
  273. _flattenNodes: TreeState['flattenNodes'];
  274. onNodeClick: any;
  275. onNodeDoubleClick: any;
  276. onMotionEnd: any;
  277. constructor(props: TreeSelectProps) {
  278. super(props);
  279. this.state = {
  280. inputTriggerFocus: false,
  281. isOpen: false,
  282. isInput: false,
  283. rePosKey: key,
  284. dropdownMinWidth: null,
  285. inputValue: '',
  286. keyEntities: {},
  287. treeData: [],
  288. flattenNodes: [],
  289. selectedKeys: [],
  290. checkedKeys: new Set(),
  291. halfCheckedKeys: new Set(),
  292. disabledKeys: new Set(),
  293. motionKeys: new Set([]),
  294. motionType: 'hide',
  295. expandedKeys: new Set(props.expandedKeys),
  296. filteredKeys: new Set(),
  297. filteredExpandedKeys: new Set(),
  298. filteredShownKeys: new Set(),
  299. prevProps: null,
  300. isHovering: false,
  301. cachedKeyValuePairs: {},
  302. loadedKeys: new Set(),
  303. loadingKeys: new Set(),
  304. };
  305. this.inputRef = React.createRef();
  306. this.tagInputRef = React.createRef();
  307. this.triggerRef = React.createRef();
  308. this.optionsRef = React.createRef();
  309. this.clickOutsideHandler = null;
  310. this.foundation = new TreeSelectFoundation(this.adapter);
  311. }
  312. // eslint-disable-next-line max-lines-per-function
  313. static getDerivedStateFromProps(props: TreeSelectProps, prevState: TreeSelectState) {
  314. const { prevProps, rePosKey } = prevState;
  315. const needUpdate = (name: string) => (
  316. (!prevProps && name in props) ||
  317. (prevProps && !isEqual(prevProps[name], props[name]))
  318. );
  319. let treeData;
  320. const withObject = props.onChangeWithObject;
  321. let keyEntities = prevState.keyEntities || {};
  322. let valueEntities = prevState.cachedKeyValuePairs || {};
  323. const newState: Partial<TreeSelectState> = {
  324. prevProps: props,
  325. };
  326. // TreeNode
  327. if (needUpdate('treeData')) {
  328. treeData = props.treeData;
  329. newState.treeData = treeData;
  330. const entitiesMap = convertDataToEntities(treeData);
  331. newState.keyEntities = {
  332. ...entitiesMap.keyEntities,
  333. };
  334. keyEntities = newState.keyEntities;
  335. newState.cachedKeyValuePairs = { ...entitiesMap.valueEntities };
  336. valueEntities = newState.cachedKeyValuePairs;
  337. }
  338. // if treeData keys changes, we won't show animation
  339. if (
  340. treeData &&
  341. props.motion &&
  342. !isEqual(new Set(Object.keys(newState.keyEntities)), new Set(Object.keys(prevState.keyEntities)))
  343. ) {
  344. if (prevProps && props.motion) {
  345. newState.motionKeys = new Set([]);
  346. newState.motionType = null;
  347. }
  348. }
  349. const expandAllWhenDataChange = needUpdate('treeData') && props.expandAll;
  350. // expandedKeys
  351. if (needUpdate('expandedKeys') || (prevProps && needUpdate('autoExpandParent'))) {
  352. newState.expandedKeys = calcExpandedKeys(
  353. props.expandedKeys,
  354. keyEntities,
  355. props.autoExpandParent || !prevProps
  356. );
  357. // only show animation when treeData does not change
  358. if (prevProps && props.motion && !treeData) {
  359. const { motionKeys, motionType } = calcMotionKeys(
  360. prevState.expandedKeys,
  361. newState.expandedKeys,
  362. keyEntities
  363. );
  364. newState.motionKeys = new Set(motionKeys);
  365. newState.motionType = motionType;
  366. }
  367. } else if ((!prevProps && (props.defaultExpandAll || props.expandAll)) || expandAllWhenDataChange) {
  368. newState.expandedKeys = new Set(Object.keys(keyEntities));
  369. } else if (!prevProps && props.defaultExpandedKeys) {
  370. newState.expandedKeys = calcExpandedKeys(props.defaultExpandedKeys, keyEntities);
  371. } else if (!prevProps && props.defaultValue) {
  372. newState.expandedKeys = calcExpandedKeysForValues(
  373. normalizeValue(props.defaultValue, withObject),
  374. keyEntities,
  375. props.multiple,
  376. valueEntities
  377. );
  378. } else if (!prevProps && props.value) {
  379. newState.expandedKeys = calcExpandedKeysForValues(
  380. normalizeValue(props.value, withObject),
  381. keyEntities,
  382. props.multiple,
  383. valueEntities
  384. );
  385. }
  386. // flattenNodes
  387. if (treeData || needUpdate('expandedKeys')) {
  388. const flattenNodes = flattenTreeData(
  389. treeData || prevState.treeData,
  390. newState.expandedKeys || prevState.expandedKeys
  391. );
  392. newState.flattenNodes = flattenNodes;
  393. }
  394. // selectedKeys: single mode controlled
  395. const isMultiple = props.multiple;
  396. if (!isMultiple) {
  397. if (needUpdate('value')) {
  398. newState.selectedKeys = findKeysForValues(
  399. normalizeValue(props.value, withObject),
  400. valueEntities,
  401. isMultiple
  402. );
  403. } else if (!prevProps && props.defaultValue) {
  404. newState.selectedKeys = findKeysForValues(
  405. normalizeValue(props.defaultValue, withObject),
  406. valueEntities,
  407. isMultiple
  408. );
  409. } else if (treeData) {
  410. // If `treeData` changed, we also need check it
  411. newState.selectedKeys = findKeysForValues(
  412. normalizeValue(props.value, withObject) || '',
  413. valueEntities,
  414. isMultiple
  415. );
  416. }
  417. } else {
  418. // checkedKeys: multiple mode controlled || data changed
  419. let checkedKeyValues;
  420. if (needUpdate('value')) {
  421. checkedKeyValues = findKeysForValues(
  422. normalizeValue(props.value, withObject),
  423. valueEntities,
  424. isMultiple
  425. );
  426. } else if (!prevProps && props.defaultValue) {
  427. checkedKeyValues = findKeysForValues(
  428. normalizeValue(props.defaultValue, withObject),
  429. valueEntities,
  430. isMultiple
  431. );
  432. } else if (treeData) {
  433. // If `treeData` changed, we also need check it
  434. checkedKeyValues = findKeysForValues(
  435. normalizeValue(props.value, withObject) || [],
  436. valueEntities,
  437. isMultiple
  438. );
  439. }
  440. if (checkedKeyValues) {
  441. const { checkedKeys, halfCheckedKeys } = calcCheckedKeys(checkedKeyValues, keyEntities);
  442. newState.checkedKeys = checkedKeys;
  443. newState.halfCheckedKeys = halfCheckedKeys;
  444. }
  445. }
  446. // loadedKeys
  447. if (needUpdate('loadedKeys')) {
  448. newState.loadedKeys = new Set(props.loadedKeys);
  449. }
  450. // ================== rePosKey ==================
  451. if (needUpdate('treeData') || needUpdate('value')) {
  452. newState.rePosKey = rePosKey + 1;
  453. }
  454. // ================ disableStrictly =================
  455. if (treeData && props.disableStrictly) {
  456. newState.disabledKeys = calcDisabledKeys(keyEntities);
  457. }
  458. return newState;
  459. }
  460. get adapter(): TreeSelectAdapter<TreeSelectProps, TreeSelectState> {
  461. const filterAdapter: Pick<TreeSelectAdapter, 'updateInputValue'> = {
  462. updateInputValue: value => {
  463. this.setState({ inputValue: value });
  464. }
  465. };
  466. const treeSelectAdapter: Pick<TreeSelectAdapter,
  467. 'registerClickOutsideHandler'
  468. | 'unregisterClickOutsideHandler'
  469. | 'rePositionDropdown'
  470. > = {
  471. registerClickOutsideHandler: cb => {
  472. const clickOutsideHandler = (e: Event) => {
  473. const optionInstance = this.optionsRef && this.optionsRef.current as React.ReactInstance;
  474. const triggerDom = this.triggerRef && this.triggerRef.current;
  475. const optionsDom = ReactDOM.findDOMNode(optionInstance);
  476. const target = e.target as Element;
  477. if (
  478. optionsDom &&
  479. (
  480. !optionsDom.contains(target) ||
  481. !optionsDom.contains(target.parentNode)
  482. ) &&
  483. triggerDom &&
  484. !triggerDom.contains(target)
  485. ) {
  486. cb(e);
  487. }
  488. };
  489. this.clickOutsideHandler = clickOutsideHandler;
  490. document.addEventListener('mousedown', clickOutsideHandler, false);
  491. },
  492. unregisterClickOutsideHandler: () => {
  493. document.removeEventListener('mousedown', this.clickOutsideHandler, false);
  494. this.clickOutsideHandler = null;
  495. },
  496. rePositionDropdown: () => {
  497. let { rePosKey } = this.state;
  498. rePosKey = rePosKey + 1;
  499. this.setState({ rePosKey });
  500. },
  501. };
  502. const treeAdapter: Pick<TreeSelectAdapter,
  503. 'updateState'
  504. | 'notifySelect'
  505. | 'notifySearch'
  506. | 'cacheFlattenNodes'
  507. | 'notifyLoad'
  508. > = {
  509. updateState: states => {
  510. this.setState({ ...states } as TreeSelectState);
  511. },
  512. notifySelect: ((selectKey, bool, node) => {
  513. this.props.onSelect && this.props.onSelect(selectKey, bool, node);
  514. }),
  515. notifySearch: input => {
  516. this.props.onSearch && this.props.onSearch(input);
  517. },
  518. cacheFlattenNodes: bool => {
  519. this._flattenNodes = bool ? cloneDeep(this.state.flattenNodes) : null;
  520. },
  521. notifyLoad: (newLoadedKeys, data) => {
  522. const { onLoad } = this.props;
  523. isFunction(onLoad) && onLoad(newLoadedKeys, data);
  524. }
  525. };
  526. return {
  527. ...super.adapter,
  528. ...filterAdapter,
  529. ...treeSelectAdapter,
  530. ...treeAdapter,
  531. updateLoadKeys: (data, resolve) => {
  532. this.setState(({ loadedKeys, loadingKeys }) =>
  533. this.foundation.handleNodeLoad(loadedKeys, loadingKeys, data, resolve));
  534. },
  535. updateState: states => {
  536. this.setState({ ...states });
  537. },
  538. openMenu: () => {
  539. this.setState({ isOpen: true }, () => {
  540. this.props.onVisibleChange(true);
  541. });
  542. },
  543. closeMenu: cb => {
  544. this.setState({ isOpen: false }, () => {
  545. cb && cb();
  546. this.props.onVisibleChange(false);
  547. });
  548. },
  549. getTriggerWidth: () => {
  550. const el = this.triggerRef.current;
  551. return el && el.getBoundingClientRect().width;
  552. },
  553. setOptionWrapperWidth: width => {
  554. this.setState({ dropdownMinWidth: width });
  555. },
  556. notifyChange: (value, node, e) => {
  557. this.props.onChange && this.props.onChange(value, node, e);
  558. },
  559. notifyChangeWithObject: (node, e) => {
  560. this.props.onChange && this.props.onChange(node, e);
  561. },
  562. notifyExpand: (expandedKeys, { expanded: bool, node }) => {
  563. this.props.onExpand && this.props.onExpand([...expandedKeys], { expanded: bool, node });
  564. if (bool && this.props.loadData) {
  565. this.onNodeLoad(node);
  566. }
  567. },
  568. notifyFocus: (...v) => {
  569. this.props.onFocus && this.props.onFocus(...v);
  570. },
  571. notifyBlur: (...v) => {
  572. this.props.onBlur && this.props.onBlur(...v);
  573. },
  574. toggleHovering: bool => {
  575. this.setState({ isHovering: bool });
  576. },
  577. updateInputFocus: bool => {} // eslint-disable-line
  578. };
  579. }
  580. componentDidMount() {
  581. this.foundation.init();
  582. }
  583. componentWillUnmount() {
  584. this.foundation.destroy();
  585. }
  586. renderSuffix = () => {
  587. const { suffix }: any = this.props;
  588. const suffixWrapperCls = cls({
  589. [`${prefixcls}-suffix`]: true,
  590. [`${prefixcls}-suffix-text`]: suffix && isString(suffix),
  591. [`${prefixcls}-suffix-icon`]: isSemiIcon(suffix),
  592. });
  593. return <div className={suffixWrapperCls}>{suffix}</div>;
  594. };
  595. renderPrefix = () => {
  596. const { prefix, insetLabel }: any = this.props;
  597. const labelNode = prefix || insetLabel;
  598. const prefixWrapperCls = cls({
  599. [`${prefixcls}-prefix`]: true,
  600. // to be doublechecked
  601. [`${prefixcls}-inset-label`]: insetLabel,
  602. [`${prefixcls}-prefix-text`]: labelNode && isString(labelNode),
  603. [`${prefixcls}-prefix-icon`]: isSemiIcon(labelNode),
  604. });
  605. return <div className={prefixWrapperCls}>{labelNode}</div>;
  606. };
  607. renderContent = () => {
  608. const { dropdownMinWidth } = this.state;
  609. const { dropdownStyle, dropdownClassName } = this.props;
  610. const style = { minWidth: dropdownMinWidth, ...dropdownStyle };
  611. const popoverCls = cls(dropdownClassName, `${prefixcls}-popover`);
  612. return (
  613. <div className={popoverCls} role="list-box" style={style}>
  614. {this.renderTree()}
  615. </div>
  616. );
  617. };
  618. removeTag = (removedKey: TreeNodeData['key']) => {
  619. this.foundation.removeTag(removedKey);
  620. };
  621. handleClick = (e: React.MouseEvent) => {
  622. this.foundation.handleClick(e);
  623. };
  624. showClearBtn = () => {
  625. const { searchPosition } = this.props;
  626. const { inputValue } = this.state;
  627. const triggerSearchHasInputValue = searchPosition === strings.SEARCH_POSITION_TRIGGER && inputValue;
  628. const { showClear, disabled, multiple } = this.props;
  629. const { selectedKeys, checkedKeys, isOpen, isHovering } = this.state;
  630. const hasValue = multiple ? Boolean(checkedKeys.size) : Boolean(selectedKeys.length);
  631. return showClear && (hasValue || triggerSearchHasInputValue) && !disabled && (isOpen || isHovering);
  632. };
  633. renderTagList = () => {
  634. const { checkedKeys, keyEntities, disabledKeys } = this.state;
  635. const {
  636. treeNodeLabelProp,
  637. leafOnly,
  638. disabled,
  639. disableStrictly,
  640. size,
  641. renderSelectedItem: propRenderSelectedItem
  642. } = this.props;
  643. const renderSelectedItem = isFunction(propRenderSelectedItem) ?
  644. propRenderSelectedItem :
  645. (item: TreeNodeData) => ({
  646. isRenderInTag: true,
  647. content: get(item, treeNodeLabelProp, null)
  648. });
  649. const renderKeys = normalizeKeyList([...checkedKeys], keyEntities, leafOnly);
  650. const tagList: Array<React.ReactNode> = [];
  651. // eslint-disable-next-line @typescript-eslint/no-shadow
  652. renderKeys.forEach((key: TreeNodeData['key']) => {
  653. const item = keyEntities[key].data;
  654. const onClose = (tagContent: any, e: React.MouseEvent) => {
  655. if (e && typeof e.preventDefault === 'function') {
  656. // make sure that tag will not hidden immediately in controlled mode
  657. e.preventDefault();
  658. }
  659. this.removeTag(key);
  660. };
  661. const { content, isRenderInTag } = (treeNodeLabelProp in item && item) ?
  662. renderSelectedItem(item, { index: key, onClose }) :
  663. null;
  664. if (!content) {
  665. return;
  666. }
  667. const isDisabled = disabled || item.disabled || (disableStrictly && disabledKeys.has(item.key));
  668. const tag: Partial<TagProps> & React.Attributes = {
  669. closable: !isDisabled,
  670. color: 'white',
  671. visible: true,
  672. onClose,
  673. key,
  674. size: size === 'small' ? 'small' : 'large'
  675. };
  676. if (isRenderInTag) {
  677. // pass ReactNode list to tagList when using tagGroup custom mode
  678. tagList.push(<Tag {...tag}>{content}</Tag>);
  679. } else {
  680. tagList.push(content);
  681. }
  682. });
  683. return tagList;
  684. };
  685. /**
  686. * When single selection and the search box is on trigger, the items displayed in the rendered search box
  687. */
  688. renderSingleTriggerSearchItem = () => {
  689. const { placeholder, disabled } = this.props;
  690. const { inputTriggerFocus } = this.state;
  691. const renderText = this.foundation.getRenderTextInSingle();
  692. const spanCls = cls(`${prefixcls}-selection-TriggerSearchItem`, {
  693. [`${prefixcls}-selection-TriggerSearchItem-placeholder`]: (inputTriggerFocus || !renderText) && !disabled,
  694. [`${prefixcls}-selection-TriggerSearchItem-disabled`]: disabled,
  695. });
  696. return (
  697. <span className={spanCls}>
  698. {renderText ? renderText : placeholder}
  699. </span>
  700. );
  701. };
  702. /**
  703. * Single selection and the search box content rendered when the search box is on trigger
  704. */
  705. renderSingleTriggerSearch = () => {
  706. const { inputValue } = this.state;
  707. return (
  708. <>
  709. {!inputValue && this.renderSingleTriggerSearchItem()}
  710. {this.renderInput()}
  711. </>
  712. );
  713. };
  714. renderSelectContent = () => {
  715. const {
  716. multiple,
  717. placeholder,
  718. maxTagCount,
  719. searchPosition,
  720. filterTreeNode,
  721. } = this.props;
  722. const { selectedKeys, checkedKeys } = this.state;
  723. const hasValue = multiple ? Boolean(checkedKeys.size) : Boolean(selectedKeys.length);
  724. const isTriggerPositionSearch = filterTreeNode && searchPosition === strings.SEARCH_POSITION_TRIGGER;
  725. // searchPosition = trigger
  726. if (isTriggerPositionSearch) {
  727. return multiple ? this.renderTagInput() : this.renderSingleTriggerSearch();
  728. }
  729. // searchPosition = dropdown and single seleciton
  730. if (!multiple || !hasValue) {
  731. const renderText = this.foundation.getRenderTextInSingle();
  732. const spanCls = cls({
  733. [`${prefixcls}-selection-placeholder`]: !renderText,
  734. });
  735. return <span className={spanCls}>{renderText ? renderText : placeholder}</span>;
  736. }
  737. // searchPosition = dropdown and multiple seleciton
  738. const tagList = this.renderTagList();
  739. // mode=custom to return tagList directly
  740. return (
  741. <TagGroup
  742. maxTagCount={maxTagCount}
  743. tagList={tagList}
  744. size="large"
  745. mode="custom"
  746. />
  747. );
  748. };
  749. handleClear = (e: React.MouseEvent) => {
  750. e && e.stopPropagation();
  751. this.foundation.handleClear(e);
  752. };
  753. handleMouseOver = (e: React.MouseEvent) => {
  754. this.foundation.toggleHoverState(true);
  755. };
  756. handleMouseLeave = (e: React.MouseEvent) => {
  757. this.foundation.toggleHoverState(false);
  758. };
  759. search = (value: string) => {
  760. this.foundation.handleInputChange(value);
  761. };
  762. close = () => {
  763. this.foundation.close(null);
  764. };
  765. renderArrow = () => {
  766. const showClearBtn = this.showClearBtn();
  767. const { arrowIcon } = this.props;
  768. if (showClearBtn) {
  769. return null;
  770. }
  771. return arrowIcon ? <div className={cls(`${prefixcls}-arrow`)}>{arrowIcon}</div> : null;
  772. };
  773. renderClearBtn = () => {
  774. const showClearBtn = this.showClearBtn();
  775. const clearCls = cls(`${prefixcls}-clearbtn`);
  776. if (showClearBtn) {
  777. return (
  778. <div className={clearCls} onClick={this.handleClear}>
  779. <IconClear />
  780. </div>
  781. );
  782. }
  783. return null;
  784. };
  785. renderSelection = () => {
  786. const {
  787. disabled,
  788. multiple,
  789. filterTreeNode,
  790. validateStatus,
  791. prefix,
  792. suffix,
  793. style,
  794. size,
  795. insetLabel,
  796. className,
  797. placeholder,
  798. showClear,
  799. leafOnly,
  800. searchPosition,
  801. triggerRender,
  802. } = this.props;
  803. const { isOpen, isInput, inputValue, selectedKeys, checkedKeys, keyEntities } = this.state;
  804. const filterable = Boolean(filterTreeNode);
  805. const useCustomTrigger = typeof triggerRender === 'function';
  806. const mouseEvent = showClear ?
  807. {
  808. onMouseEnter: (e: React.MouseEvent) => this.handleMouseOver(e),
  809. onMouseLeave: (e: React.MouseEvent) => this.handleMouseLeave(e),
  810. } :
  811. {};
  812. const isTriggerPositionSearch = searchPosition === strings.SEARCH_POSITION_TRIGGER && filterable;
  813. const isEmptyTriggerSearch = isTriggerPositionSearch && isEmpty(checkedKeys);
  814. const isValueTriggerSearch = isTriggerPositionSearch && !isEmpty(checkedKeys);
  815. const classNames = useCustomTrigger ?
  816. cls(className) :
  817. cls(
  818. prefixcls,
  819. {
  820. [`${prefixcls}-focus`]: isOpen && !isInput,
  821. [`${prefixcls}-disabled`]: disabled,
  822. [`${prefixcls}-single`]: !multiple,
  823. [`${prefixcls}-multiple`]: multiple,
  824. [`${prefixcls}-multiple-tagInput-empty`]: multiple && isEmptyTriggerSearch,
  825. [`${prefixcls}-multiple-tagInput-notEmpty`]: multiple && isValueTriggerSearch,
  826. [`${prefixcls}-filterable`]: filterable,
  827. [`${prefixcls}-error`]: validateStatus === 'error',
  828. [`${prefixcls}-warning`]: validateStatus === 'warning',
  829. [`${prefixcls}-small`]: size === 'small',
  830. [`${prefixcls}-large`]: size === 'large',
  831. [`${prefixcls}-with-prefix`]: prefix || insetLabel,
  832. [`${prefixcls}-with-suffix`]: suffix,
  833. [`${prefixcls}-with-suffix`]: suffix,
  834. },
  835. className
  836. );
  837. const triggerRenderKeys = multiple ? normalizeKeyList([...checkedKeys], keyEntities, leafOnly) : selectedKeys;
  838. const inner = useCustomTrigger ? (
  839. <Trigger
  840. inputValue={inputValue}
  841. // eslint-disable-next-line @typescript-eslint/no-shadow
  842. value={triggerRenderKeys.map((key: string) => get(keyEntities, [key, 'data']))}
  843. disabled={disabled}
  844. placeholder={placeholder}
  845. onClear={this.handleClear}
  846. componentName={'TreeSelect'}
  847. triggerRender={triggerRender}
  848. componentProps={{ ...this.props }}
  849. />
  850. ) : (
  851. [
  852. <Fragment key={'prefix'}>{prefix || insetLabel ? this.renderPrefix() : null}</Fragment>,
  853. <Fragment key={'selection'}>
  854. <div className={`${prefixcls}-selection`}>{this.renderSelectContent()}</div>
  855. </Fragment>,
  856. <Fragment key={'suffix'}>{suffix ? this.renderSuffix() : null}</Fragment>,
  857. <Fragment key={'clearBtn'}>
  858. {
  859. (showClear || (isTriggerPositionSearch && inputValue)) ?
  860. this.renderClearBtn() :
  861. null
  862. }
  863. </Fragment>,
  864. <Fragment key={'arrow'}>{this.renderArrow()}</Fragment>,
  865. ]
  866. );
  867. return (
  868. <div
  869. className={classNames}
  870. style={style}
  871. ref={this.triggerRef}
  872. onClick={this.handleClick}
  873. {...mouseEvent}
  874. >
  875. {inner}
  876. </div>
  877. );
  878. };
  879. // eslint-disable-next-line @typescript-eslint/no-shadow
  880. renderTagItem = (key: string, idx: number) => {
  881. const { keyEntities, disabledKeys } = this.state;
  882. const {
  883. size,
  884. leafOnly,
  885. disabled,
  886. disableStrictly,
  887. renderSelectedItem: propRenderSelectedItem,
  888. treeNodeLabelProp
  889. } = this.props;
  890. const keyList = normalizeKeyList([key], keyEntities, leafOnly);
  891. const nodes = keyList.map(i => keyEntities[i].data);
  892. const value = getValueOrKey(nodes);
  893. const tagCls = cls(`${prefixcls}-selection-tag`, {
  894. [`${prefixcls}-selection-tag-disabled`]: disabled,
  895. });
  896. const nodeHaveData = !isEmpty(nodes) && !isEmpty(nodes[0]);
  897. const isDisableStrictlyNode = disableStrictly && nodeHaveData && disabledKeys.has(nodes[0].key);
  898. const closable = nodeHaveData && !nodes[0].disabled && !disabled && !isDisableStrictlyNode;
  899. const onClose = (tagChildren: string, e: React.MouseEvent) => {
  900. // When value has not changed, prevent clicking tag closeBtn to close tag
  901. e.preventDefault();
  902. this.removeTag(key);
  903. };
  904. const tagProps: Partial<TagProps> & React.Attributes = {
  905. size: size === 'small' ? 'small' : 'large',
  906. key: `tag-${value}-${idx}`,
  907. color: 'white',
  908. className: tagCls,
  909. closable,
  910. onClose,
  911. };
  912. const item = nodes[0];
  913. const renderSelectedItem = isFunction(propRenderSelectedItem) ? propRenderSelectedItem :
  914. (selectedItem: TreeNodeData) => ({
  915. isRenderInTag: true,
  916. content: get(selectedItem, treeNodeLabelProp, null)
  917. });
  918. if (isFunction(renderSelectedItem)) {
  919. const { content, isRenderInTag } = treeNodeLabelProp in item && item ?
  920. renderSelectedItem(item, { index: idx, onClose }) :
  921. null;
  922. if (isRenderInTag) {
  923. return <Tag {...tagProps}>{content}</Tag>;
  924. } else {
  925. return content;
  926. }
  927. }
  928. return (
  929. <Tag {...tagProps}>
  930. {value}
  931. </Tag>
  932. );
  933. };
  934. renderTagInput = () => {
  935. const {
  936. leafOnly,
  937. disabled,
  938. size,
  939. searchAutoFocus,
  940. placeholder,
  941. } = this.props;
  942. const {
  943. keyEntities,
  944. checkedKeys,
  945. inputValue
  946. } = this.state;
  947. const keyList = normalizeKeyList(checkedKeys, keyEntities, leafOnly);
  948. return (
  949. <TagInput
  950. disabled={disabled}
  951. onInputChange={v => this.search(v)}
  952. ref={this.tagInputRef}
  953. placeholder={placeholder}
  954. value={keyList}
  955. inputValue={inputValue}
  956. size={size}
  957. autoFocus={searchAutoFocus}
  958. renderTagItem={(itemKey, index) => this.renderTagItem(itemKey, index)}
  959. onRemove={itemKey => this.removeTag(itemKey)}
  960. />
  961. );
  962. };
  963. // render Tree
  964. renderInput = () => {
  965. const {
  966. searchPlaceholder,
  967. searchRender,
  968. showSearchClear,
  969. searchPosition,
  970. searchAutoFocus,
  971. multiple,
  972. disabled,
  973. } = this.props;
  974. const isDropdownPositionSearch = searchPosition === strings.SEARCH_POSITION_DROPDOWN;
  975. const inputcls = cls({
  976. [`${prefixTree}-input`]: isDropdownPositionSearch,
  977. [`${prefixcls}-inputTrigger`]: !isDropdownPositionSearch
  978. });
  979. const { inputValue } = this.state;
  980. const baseInputProps = {
  981. value: inputValue,
  982. className: inputcls,
  983. onChange: (value: string) => this.search(value),
  984. };
  985. const inputDropdownProps = {
  986. showClear: showSearchClear,
  987. prefix: <IconSearch />,
  988. };
  989. const inputTriggerProps = {
  990. onFocus: (e: React.FocusEvent) => this.foundation.handleInputTriggerFocus(),
  991. onBlur: (e: React.FocusEvent) => this.foundation.handleInputTriggerBlur(),
  992. disabled,
  993. };
  994. const realInputProps = isDropdownPositionSearch ? inputDropdownProps : inputTriggerProps;
  995. const wrapperCls = cls({
  996. [`${prefixTree}-search-wrapper`]: isDropdownPositionSearch,
  997. [`${prefixcls}-triggerSingleSearch-wrapper`]: !isDropdownPositionSearch && !multiple,
  998. });
  999. const useCusSearch = typeof searchRender === 'function' || typeof searchRender === 'boolean';
  1000. if (useCusSearch && !searchRender) {
  1001. return null;
  1002. }
  1003. return (
  1004. <div className={wrapperCls}>
  1005. <LocaleConsumer componentName="TreeSelect">
  1006. {(locale: Locale['TreeSelect']) => {
  1007. const placeholder = isDropdownPositionSearch ?
  1008. searchPlaceholder || locale.searchPlaceholder :
  1009. '';
  1010. if (useCusSearch) {
  1011. return (searchRender as any)({ ...realInputProps, ...baseInputProps, placeholder });
  1012. }
  1013. return (
  1014. <Input
  1015. ref={this.inputRef as any}
  1016. autofocus={searchAutoFocus}
  1017. placeholder={placeholder}
  1018. {...baseInputProps}
  1019. {...realInputProps}
  1020. />
  1021. );
  1022. }}
  1023. </LocaleConsumer>
  1024. </div>
  1025. );
  1026. };
  1027. renderEmpty = () => {
  1028. const { emptyContent } = this.props;
  1029. if (emptyContent) {
  1030. return <TreeNode empty emptyContent={this.props.emptyContent} />;
  1031. } else {
  1032. return (
  1033. <LocaleConsumer componentName="Tree">
  1034. {(locale: Locale['Tree']) => <TreeNode empty emptyContent={locale.emptyText} />}
  1035. </LocaleConsumer>
  1036. );
  1037. }
  1038. };
  1039. onNodeLoad = (data: TreeNodeData) => new Promise(resolve => this.foundation.setLoadKeys(data, resolve));
  1040. onNodeSelect = (e: React.MouseEvent, treeNode: TreeNodeProps) => {
  1041. this.foundation.handleNodeSelect(e, treeNode);
  1042. };
  1043. onNodeCheck = (e: React.MouseEvent, treeNode: TreeNodeProps) => {
  1044. this.foundation.handleNodeSelect(e, treeNode);
  1045. };
  1046. onNodeExpand = (e: React.MouseEvent, treeNode: TreeNodeProps) => {
  1047. this.foundation.handleNodeExpand(e, treeNode);
  1048. };
  1049. getTreeNodeRequiredProps = () => {
  1050. const { expandedKeys, selectedKeys, checkedKeys, halfCheckedKeys, keyEntities, filteredKeys } = this.state;
  1051. return {
  1052. expandedKeys: expandedKeys || new Set(),
  1053. selectedKeys: selectedKeys || [],
  1054. checkedKeys: checkedKeys || new Set(),
  1055. halfCheckedKeys: halfCheckedKeys || new Set(),
  1056. filteredKeys: filteredKeys || new Set(),
  1057. keyEntities,
  1058. };
  1059. };
  1060. getTreeNodeKey = (treeNode: TreeNodeData) => {
  1061. const { data } = treeNode;
  1062. // eslint-disable-next-line @typescript-eslint/no-shadow
  1063. const { key }: { key: string } = data;
  1064. return key;
  1065. };
  1066. /* Event handler function after popover is closed */
  1067. handlePopoverClose = isVisible => {
  1068. const { filterTreeNode } = this.props;
  1069. if (isVisible === false && Boolean(filterTreeNode)) {
  1070. this.foundation.clearInput();
  1071. }
  1072. }
  1073. renderTreeNode = (treeNode: FlattenNode, ind: number, style: React.CSSProperties) => {
  1074. const { data } = treeNode;
  1075. // eslint-disable-next-line @typescript-eslint/no-shadow
  1076. const { key }: { key: string } = data;
  1077. const treeNodeProps = this.foundation.getTreeNodeProps(key);
  1078. if (!treeNodeProps) {
  1079. return null;
  1080. }
  1081. return <TreeNode {...treeNodeProps} {...data} key={key} data={data} style={style} />;
  1082. };
  1083. itemKey = (index: number, data: TreeNodeData) => {
  1084. // Find the item at the specified index.
  1085. const item = data[index];
  1086. // Return a value that uniquely identifies this item.
  1087. return item.key;
  1088. };
  1089. renderNodeList = () => {
  1090. const { flattenNodes, motionKeys, motionType } = this.state;
  1091. const { direction } = this.context;
  1092. const { virtualize, motionExpand } = this.props;
  1093. if (!virtualize || isEmpty(virtualize)) {
  1094. return (
  1095. <NodeList
  1096. flattenNodes={flattenNodes}
  1097. flattenList={this._flattenNodes}
  1098. motionKeys={motionExpand ? motionKeys : new Set([])}
  1099. motionType={motionType}
  1100. onMotionEnd={this.onMotionEnd}
  1101. renderTreeNode={this.renderTreeNode}
  1102. />
  1103. );
  1104. }
  1105. const option = ({ index, style, data }: OptionProps) => this.renderTreeNode(data[index], index, style);
  1106. return (
  1107. <AutoSizer defaultHeight={virtualize.height} defaultWidth={virtualize.width}>
  1108. {({ height, width }) => (
  1109. <VirtualList
  1110. itemCount={flattenNodes.length}
  1111. itemSize={virtualize.itemSize}
  1112. height={height}
  1113. width={width}
  1114. itemKey={this.itemKey}
  1115. itemData={flattenNodes as any}
  1116. className={`${prefixTree}-virtual-list`}
  1117. style={{ direction }}
  1118. >
  1119. {option}
  1120. </VirtualList>
  1121. )}
  1122. </AutoSizer>
  1123. );
  1124. };
  1125. renderTree = () => {
  1126. const { keyEntities, motionKeys, motionType, inputValue, filteredKeys, flattenNodes } = this.state;
  1127. const {
  1128. loadData,
  1129. filterTreeNode,
  1130. disabled,
  1131. multiple,
  1132. showFilteredOnly,
  1133. motionExpand,
  1134. outerBottomSlot,
  1135. outerTopSlot,
  1136. expandAction,
  1137. labelEllipsis,
  1138. virtualize,
  1139. optionListStyle,
  1140. searchPosition,
  1141. renderLabel,
  1142. renderFullLabel,
  1143. } = this.props;
  1144. const wrapperCls = cls(`${prefixTree}-wrapper`);
  1145. const listCls = cls(`${prefixTree}-option-list`, {
  1146. [`${prefixTree}-option-list-block`]: true,
  1147. });
  1148. const searchNoRes = Boolean(inputValue) && !filteredKeys.size;
  1149. const noData = isEmpty(flattenNodes) || (showFilteredOnly && searchNoRes);
  1150. const isDropdownPositionSearch = searchPosition === strings.SEARCH_POSITION_DROPDOWN;
  1151. return (
  1152. <TreeContext.Provider
  1153. value={{
  1154. loadData,
  1155. treeDisabled: disabled,
  1156. motion: motionExpand,
  1157. motionKeys,
  1158. motionType,
  1159. expandAction,
  1160. filterTreeNode,
  1161. keyEntities,
  1162. onNodeClick: this.onNodeClick,
  1163. onNodeDoubleClick: this.onNodeDoubleClick,
  1164. // tree node will call this function when treeNode is right clicked
  1165. onNodeRightClick: noop,
  1166. onNodeExpand: this.onNodeExpand,
  1167. onNodeSelect: this.onNodeSelect,
  1168. onNodeCheck: this.onNodeCheck,
  1169. renderTreeNode: this.renderTreeNode,
  1170. multiple,
  1171. showFilteredOnly,
  1172. isSearching: Boolean(inputValue),
  1173. renderLabel,
  1174. renderFullLabel,
  1175. labelEllipsis: typeof labelEllipsis === 'undefined' ? virtualize : labelEllipsis,
  1176. }}
  1177. >
  1178. <div className={wrapperCls} role="list-box">
  1179. {outerTopSlot}
  1180. {
  1181. !outerTopSlot &&
  1182. filterTreeNode &&
  1183. isDropdownPositionSearch &&
  1184. this.renderInput()
  1185. }
  1186. <div className={listCls} role="tree" style={optionListStyle}>
  1187. {noData ? this.renderEmpty() : this.renderNodeList()}
  1188. </div>
  1189. {outerBottomSlot}
  1190. </div>
  1191. </TreeContext.Provider>
  1192. );
  1193. };
  1194. render() {
  1195. const content = this.renderContent();
  1196. const {
  1197. motion,
  1198. zIndex,
  1199. mouseLeaveDelay,
  1200. mouseEnterDelay,
  1201. autoAdjustOverflow,
  1202. stopPropagation,
  1203. getPopupContainer,
  1204. } = this.props;
  1205. const { isOpen, rePosKey } = this.state;
  1206. const selection = this.renderSelection();
  1207. const pos = 'bottomLeft';
  1208. return (
  1209. <Popover
  1210. stopPropagation={stopPropagation}
  1211. getPopupContainer={getPopupContainer}
  1212. zIndex={zIndex}
  1213. motion={motion}
  1214. ref={this.optionsRef}
  1215. content={content}
  1216. visible={isOpen}
  1217. trigger="custom"
  1218. rePosKey={rePosKey}
  1219. position={pos}
  1220. autoAdjustOverflow={autoAdjustOverflow}
  1221. mouseLeaveDelay={mouseLeaveDelay}
  1222. mouseEnterDelay={mouseEnterDelay}
  1223. onVisibleChange={this.handlePopoverClose}
  1224. >
  1225. {selection}
  1226. </Popover>
  1227. );
  1228. }
  1229. }
  1230. export default TreeSelect;