index.tsx 48 KB

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