index.tsx 57 KB

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