index.tsx 50 KB

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