index.tsx 62 KB

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