index.tsx 57 KB

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