index.tsx 51 KB

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