1
0

index.tsx 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  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. } = this.props;
  921. const { inputValue, selectedKeys, checkedKeys, keyEntities, isFocus } = this.state;
  922. const filterable = Boolean(filterTreeNode);
  923. const useCustomTrigger = typeof triggerRender === 'function';
  924. const mouseEvent = showClear ?
  925. {
  926. onMouseEnter: (e: React.MouseEvent) => this.handleMouseOver(e),
  927. onMouseLeave: (e: React.MouseEvent) => this.handleMouseLeave(e),
  928. } :
  929. {};
  930. const isTriggerPositionSearch = searchPosition === strings.SEARCH_POSITION_TRIGGER && filterable;
  931. const isEmptyTriggerSearch = isTriggerPositionSearch && isEmpty(checkedKeys);
  932. const isValueTriggerSearch = isTriggerPositionSearch && !isEmpty(checkedKeys);
  933. const classNames = useCustomTrigger ?
  934. cls(className) :
  935. cls(
  936. prefixcls,
  937. {
  938. [`${prefixcls}-borderless`]: borderless,
  939. [`${prefixcls}-focus`]: isFocus,
  940. [`${prefixcls}-disabled`]: disabled,
  941. [`${prefixcls}-single`]: !multiple,
  942. [`${prefixcls}-multiple`]: multiple,
  943. [`${prefixcls}-multiple-tagInput-empty`]: multiple && isEmptyTriggerSearch,
  944. [`${prefixcls}-multiple-tagInput-notEmpty`]: multiple && isValueTriggerSearch,
  945. [`${prefixcls}-filterable`]: filterable,
  946. [`${prefixcls}-error`]: validateStatus === 'error',
  947. [`${prefixcls}-warning`]: validateStatus === 'warning',
  948. [`${prefixcls}-small`]: size === 'small',
  949. [`${prefixcls}-large`]: size === 'large',
  950. [`${prefixcls}-with-prefix`]: prefix || insetLabel,
  951. [`${prefixcls}-with-suffix`]: suffix,
  952. [`${prefixcls}-with-suffix`]: suffix,
  953. },
  954. className
  955. );
  956. const triggerRenderKeys = multiple ? normalizeKeyList([...checkedKeys], keyEntities, leafOnly, true) : selectedKeys;
  957. const inner = useCustomTrigger ? (
  958. <Trigger
  959. inputValue={inputValue}
  960. // eslint-disable-next-line @typescript-eslint/no-shadow
  961. value={triggerRenderKeys.map((key: string) => get(keyEntities, [key, 'data']))}
  962. disabled={disabled}
  963. placeholder={placeholder}
  964. onClear={this.handleClear}
  965. componentName={'TreeSelect'}
  966. triggerRender={triggerRender}
  967. componentProps={{ ...this.props }}
  968. onSearch={this.search}
  969. onRemove={this.removeTag}
  970. />
  971. ) : (
  972. [
  973. <Fragment key={'prefix'}>{prefix || insetLabel ? this.renderPrefix() : null}</Fragment>,
  974. <Fragment key={'selection'}>
  975. <div className={`${prefixcls}-selection`}>{this.renderSelectContent()}</div>
  976. </Fragment>,
  977. <Fragment key={'suffix'}>{suffix ? this.renderSuffix() : null}</Fragment>,
  978. <Fragment key={'clearBtn'}>
  979. {
  980. (showClear || (isTriggerPositionSearch && inputValue)) ?
  981. this.renderClearBtn() :
  982. null
  983. }
  984. </Fragment>,
  985. <Fragment key={'arrow'}>{this.renderArrow()}</Fragment>,
  986. ]
  987. );
  988. const tabIndex = disabled ? null : 0;
  989. /**
  990. * Reasons for disabling the a11y eslint rule:
  991. * The following attributes(aria-controls,aria-expanded) will be automatically added by Tooltip, no need to declare here
  992. */
  993. return (
  994. <div
  995. // eslint-disable-next-line jsx-a11y/role-has-required-aria-props
  996. role='combobox'
  997. aria-disabled={disabled}
  998. aria-haspopup="tree"
  999. tabIndex={tabIndex}
  1000. className={classNames}
  1001. style={style}
  1002. ref={this.triggerRef}
  1003. onClick={this.handleClick}
  1004. onKeyPress={this.handleSelectionEnterPress}
  1005. aria-invalid={this.props['aria-invalid']}
  1006. aria-errormessage={this.props['aria-errormessage']}
  1007. aria-label={this.props['aria-label']}
  1008. aria-labelledby={this.props['aria-labelledby']}
  1009. aria-describedby={this.props['aria-describedby']}
  1010. aria-required={this.props['aria-required']}
  1011. {...mouseEvent}
  1012. >
  1013. {inner}
  1014. </div>
  1015. );
  1016. };
  1017. // eslint-disable-next-line @typescript-eslint/no-shadow
  1018. renderTagItem = (key: string, idx: number) => {
  1019. const { keyEntities, disabledKeys } = this.state;
  1020. const {
  1021. size,
  1022. leafOnly,
  1023. disabled,
  1024. disableStrictly,
  1025. renderSelectedItem: propRenderSelectedItem,
  1026. treeNodeLabelProp
  1027. } = this.props;
  1028. const keyList = normalizeKeyList([key], keyEntities, leafOnly, true);
  1029. const nodes = keyList.map(i => (keyEntities[key] && keyEntities[key].data.key === key) ? keyEntities[key].data : this.getDataForKeyNotInKeyEntities(key));
  1030. const value = getValueOrKey(nodes);
  1031. const tagCls = cls(`${prefixcls}-selection-tag`, {
  1032. [`${prefixcls}-selection-tag-disabled`]: disabled,
  1033. });
  1034. const nodeHaveData = !isEmpty(nodes) && !isEmpty(nodes[0]);
  1035. const isDisableStrictlyNode = disableStrictly && nodeHaveData && disabledKeys.has(nodes[0].key);
  1036. const closable = nodeHaveData && !nodes[0].disabled && !disabled && !isDisableStrictlyNode;
  1037. const onClose = (tagChildren: React.ReactNode, e: React.MouseEvent) => {
  1038. // When value has not changed, prevent clicking tag closeBtn to close tag
  1039. e.preventDefault();
  1040. this.removeTag(key);
  1041. };
  1042. const tagProps: Partial<TagProps> & React.Attributes = {
  1043. size: size === 'small' ? 'small' : 'large',
  1044. key: `tag-${value}-${idx}`,
  1045. color: 'white',
  1046. className: tagCls,
  1047. closable,
  1048. onClose,
  1049. };
  1050. const item = nodes[0];
  1051. const renderSelectedItem = isFunction(propRenderSelectedItem) ? propRenderSelectedItem :
  1052. (selectedItem: TreeNodeData) => ({
  1053. isRenderInTag: true,
  1054. content: get(selectedItem, treeNodeLabelProp, null)
  1055. });
  1056. if (isFunction(renderSelectedItem)) {
  1057. const { content, isRenderInTag } = item && treeNodeLabelProp in item ?
  1058. (renderSelectedItem as RenderSelectedItemInMultiple)(item, { index: idx, onClose }) :
  1059. null;
  1060. if (isRenderInTag) {
  1061. return <Tag {...tagProps}>{content}</Tag>;
  1062. } else {
  1063. return content;
  1064. }
  1065. }
  1066. return (
  1067. <Tag {...tagProps}>
  1068. {value}
  1069. </Tag>
  1070. );
  1071. };
  1072. renderTagInput = () => {
  1073. const {
  1074. leafOnly,
  1075. disabled,
  1076. size,
  1077. searchAutoFocus,
  1078. placeholder,
  1079. maxTagCount,
  1080. checkRelation,
  1081. showRestTagsPopover,
  1082. restTagsPopoverProps,
  1083. searchPosition,
  1084. filterTreeNode,
  1085. preventScroll
  1086. } = this.props;
  1087. const {
  1088. keyEntities,
  1089. checkedKeys,
  1090. inputValue,
  1091. realCheckedKeys,
  1092. } = this.state;
  1093. let keyList = [];
  1094. if (checkRelation === 'related') {
  1095. keyList = normalizeKeyList(checkedKeys, keyEntities, leafOnly, true);
  1096. } else if (checkRelation === 'unRelated') {
  1097. keyList = [...realCheckedKeys];
  1098. }
  1099. // auto focus search input divide into two parts
  1100. // 1. filterTreeNode && searchPosition === strings.SEARCH_POSITION_TRIGGER
  1101. // Implemented by passing autofocus to the underlying input's autofocus
  1102. // 2. filterTreeNode && searchPosition === strings.SEARCH_POSITION_DROPDOWN
  1103. // Due to the off-screen rendering in the tooltip implementation mechanism, if it is implemented through the
  1104. // autofocus of the input, when the option panel is opened, the page will scroll to top, so it is necessary
  1105. // to call the focus method through ref in the onVisibleChange callback of the Popover to achieve focus
  1106. const autoFocus = (filterTreeNode && searchPosition === strings.SEARCH_POSITION_TRIGGER) ? searchAutoFocus : undefined;
  1107. return (
  1108. <TagInput
  1109. maxTagCount={maxTagCount}
  1110. disabled={disabled}
  1111. onInputChange={v => this.search(v)}
  1112. ref={this.tagInputRef}
  1113. placeholder={placeholder}
  1114. value={keyList}
  1115. inputValue={inputValue}
  1116. size={size}
  1117. showRestTagsPopover={showRestTagsPopover}
  1118. restTagsPopoverProps={restTagsPopoverProps}
  1119. // eslint-disable-next-line jsx-a11y/no-autofocus
  1120. autoFocus={autoFocus}
  1121. renderTagItem={(itemKey, index) => this.renderTagItem(itemKey, index)}
  1122. onRemove={itemKey => this.removeTag(itemKey)}
  1123. expandRestTagsOnClick={false}
  1124. preventScroll={preventScroll}
  1125. />
  1126. );
  1127. };
  1128. // render Tree
  1129. renderInput = () => {
  1130. const {
  1131. searchPlaceholder,
  1132. searchRender,
  1133. showSearchClear,
  1134. searchPosition,
  1135. searchAutoFocus,
  1136. multiple,
  1137. disabled,
  1138. } = this.props;
  1139. const isDropdownPositionSearch = searchPosition === strings.SEARCH_POSITION_DROPDOWN;
  1140. const inputcls = cls({
  1141. [`${prefixTree}-input`]: isDropdownPositionSearch,
  1142. [`${prefixcls}-inputTrigger`]: !isDropdownPositionSearch
  1143. });
  1144. const { inputValue } = this.state;
  1145. const baseInputProps = {
  1146. value: inputValue,
  1147. className: inputcls,
  1148. onChange: (value: string) => this.search(value),
  1149. };
  1150. const inputDropdownProps = {
  1151. showClear: showSearchClear,
  1152. prefix: <IconSearch />,
  1153. };
  1154. const inputTriggerProps = {
  1155. autofocus: searchAutoFocus,
  1156. onFocus: (e: React.FocusEvent) => this.foundation.handleInputTriggerFocus(),
  1157. onBlur: (e: React.FocusEvent) => this.foundation.handleInputTriggerBlur(),
  1158. disabled,
  1159. };
  1160. const realInputProps = isDropdownPositionSearch ? inputDropdownProps : inputTriggerProps;
  1161. const wrapperCls = cls({
  1162. [`${prefixTree}-search-wrapper`]: isDropdownPositionSearch,
  1163. [`${prefixcls}-triggerSingleSearch-wrapper`]: !isDropdownPositionSearch && !multiple,
  1164. });
  1165. const useCusSearch = typeof searchRender === 'function' || typeof searchRender === 'boolean';
  1166. if (useCusSearch && !searchRender) {
  1167. return null;
  1168. }
  1169. return (
  1170. <div className={wrapperCls}>
  1171. <LocaleConsumer componentName="TreeSelect">
  1172. {(locale: Locale['TreeSelect']) => {
  1173. const placeholder = isDropdownPositionSearch ?
  1174. searchPlaceholder || locale.searchPlaceholder :
  1175. '';
  1176. if (useCusSearch) {
  1177. return (searchRender as any)({ ...realInputProps, ...baseInputProps, placeholder });
  1178. }
  1179. return (
  1180. <Input
  1181. aria-label='Filter TreeSelect item'
  1182. ref={this.inputRef as any}
  1183. placeholder={placeholder}
  1184. {...baseInputProps}
  1185. {...realInputProps}
  1186. />
  1187. );
  1188. }}
  1189. </LocaleConsumer>
  1190. </div>
  1191. );
  1192. };
  1193. renderEmpty = () => {
  1194. const { emptyContent } = this.props;
  1195. if (emptyContent) {
  1196. return <TreeNode empty emptyContent={this.props.emptyContent} />;
  1197. } else {
  1198. return (
  1199. <LocaleConsumer componentName="Tree">
  1200. {(locale: Locale['Tree']) => <TreeNode empty emptyContent={locale.emptyText} />}
  1201. </LocaleConsumer>
  1202. );
  1203. }
  1204. };
  1205. onNodeLoad = (data: TreeNodeData) => new Promise(resolve => this.foundation.setLoadKeys(data, resolve));
  1206. onNodeSelect = (e: React.MouseEvent | React.KeyboardEvent, treeNode: TreeNodeProps) => {
  1207. this.foundation.handleNodeSelect(e, treeNode);
  1208. };
  1209. onNodeCheck = (e: React.MouseEvent | React.KeyboardEvent, treeNode: TreeNodeProps) => {
  1210. this.foundation.handleNodeSelect(e, treeNode);
  1211. };
  1212. onNodeExpand = (e: React.MouseEvent | React.KeyboardEvent, treeNode: TreeNodeProps) => {
  1213. this.foundation.handleNodeExpand(e, treeNode);
  1214. };
  1215. getTreeNodeRequiredProps = () => {
  1216. const { expandedKeys, selectedKeys, checkedKeys, halfCheckedKeys, keyEntities, filteredKeys } = this.state;
  1217. return {
  1218. expandedKeys: expandedKeys || new Set(),
  1219. selectedKeys: selectedKeys || [],
  1220. checkedKeys: checkedKeys || new Set(),
  1221. halfCheckedKeys: halfCheckedKeys || new Set(),
  1222. filteredKeys: filteredKeys || new Set(),
  1223. keyEntities,
  1224. };
  1225. };
  1226. getTreeNodeKey = (treeNode: TreeNodeData) => {
  1227. const { data } = treeNode;
  1228. // eslint-disable-next-line @typescript-eslint/no-shadow
  1229. const { key }: { key: string } = data;
  1230. return key;
  1231. };
  1232. /* Event handler function after popover is closed */
  1233. handlePopoverClose = isVisible => {
  1234. const { filterTreeNode, searchAutoFocus, searchPosition } = this.props;
  1235. if (isVisible === false && Boolean(filterTreeNode)) {
  1236. this.foundation.clearInput();
  1237. }
  1238. if (filterTreeNode && searchPosition === strings.SEARCH_POSITION_DROPDOWN && isVisible && searchAutoFocus) {
  1239. this.foundation.focusInput(true);
  1240. }
  1241. }
  1242. renderTreeNode = (treeNode: FlattenNode, ind: number, style: React.CSSProperties) => {
  1243. const { data } = treeNode;
  1244. // eslint-disable-next-line @typescript-eslint/no-shadow
  1245. const { key }: { key: string } = data;
  1246. const treeNodeProps = this.foundation.getTreeNodeProps(key);
  1247. if (!treeNodeProps) {
  1248. return null;
  1249. }
  1250. return <TreeNode {...treeNodeProps} {...data} key={key} data={data} style={style} />;
  1251. };
  1252. itemKey = (index: number, data: Record<string, any>) => {
  1253. const { visibleOptions } = data;
  1254. // Find the item at the specified index.
  1255. const item = visibleOptions[index];
  1256. // Return a value that uniquely identifies this item.
  1257. return item.key;
  1258. };
  1259. renderNodeList = () => {
  1260. const { flattenNodes, motionKeys, motionType, filteredKeys } = this.state;
  1261. const { direction } = this.context;
  1262. const { virtualize, motionExpand } = this.props;
  1263. const isExpandControlled = 'expandedKeys' in this.props;
  1264. if (!virtualize || isEmpty(virtualize)) {
  1265. return (
  1266. <NodeList
  1267. flattenNodes={flattenNodes}
  1268. flattenList={this._flattenNodes}
  1269. motionKeys={motionExpand ? motionKeys : new Set([])}
  1270. motionType={motionType}
  1271. // When motionKeys is empty, but filteredKeys is not empty (that is, the search hits), this situation should be distinguished from ordinary motionKeys
  1272. searchTargetIsDeep={
  1273. isExpandControlled &&
  1274. motionExpand &&
  1275. isEmpty(motionKeys) &&
  1276. !isEmpty(filteredKeys)
  1277. }
  1278. onMotionEnd={this.onMotionEnd}
  1279. renderTreeNode={this.renderTreeNode}
  1280. />
  1281. );
  1282. }
  1283. const data = {
  1284. visibleOptions: flattenNodes,
  1285. renderOption: this.renderTreeNode
  1286. };
  1287. return (
  1288. <AutoSizer defaultHeight={virtualize.height} defaultWidth={virtualize.width}>
  1289. {({ height, width }) => (
  1290. <VirtualList
  1291. itemCount={flattenNodes.length}
  1292. itemSize={virtualize.itemSize}
  1293. height={height}
  1294. width={width}
  1295. // @ts-ignore avoid strict check of itemKey
  1296. itemKey={this.itemKey}
  1297. itemData={data}
  1298. className={`${prefixTree}-virtual-list`}
  1299. style={{ direction }}
  1300. >
  1301. {VirtualRow}
  1302. </VirtualList>
  1303. )}
  1304. </AutoSizer>
  1305. );
  1306. };
  1307. renderTree = () => {
  1308. const { keyEntities, motionKeys, motionType, inputValue, filteredKeys, flattenNodes, checkedKeys, realCheckedKeys } = this.state;
  1309. const {
  1310. loadData,
  1311. filterTreeNode,
  1312. disabled,
  1313. multiple,
  1314. showFilteredOnly,
  1315. motionExpand,
  1316. outerBottomSlot,
  1317. outerTopSlot,
  1318. expandAction,
  1319. labelEllipsis,
  1320. virtualize,
  1321. optionListStyle,
  1322. searchPosition,
  1323. renderLabel,
  1324. renderFullLabel,
  1325. checkRelation,
  1326. } = this.props;
  1327. const wrapperCls = cls(`${prefixTree}-wrapper`);
  1328. const listCls = cls(`${prefixTree}-option-list`, {
  1329. [`${prefixTree}-option-list-block`]: true,
  1330. });
  1331. const searchNoRes = Boolean(inputValue) && !filteredKeys.size;
  1332. const noData = isEmpty(flattenNodes) || (showFilteredOnly && searchNoRes);
  1333. const isDropdownPositionSearch = searchPosition === strings.SEARCH_POSITION_DROPDOWN;
  1334. return (
  1335. <TreeContext.Provider
  1336. value={{
  1337. loadData,
  1338. treeDisabled: disabled,
  1339. motion: motionExpand,
  1340. motionKeys,
  1341. motionType,
  1342. expandAction,
  1343. filterTreeNode,
  1344. keyEntities,
  1345. onNodeClick: this.onNodeClick,
  1346. onNodeDoubleClick: this.onNodeDoubleClick,
  1347. // tree node will call this function when treeNode is right clicked
  1348. onNodeRightClick: noop,
  1349. onNodeExpand: this.onNodeExpand,
  1350. onNodeSelect: this.onNodeSelect,
  1351. onNodeCheck: this.onNodeCheck,
  1352. renderTreeNode: this.renderTreeNode,
  1353. multiple,
  1354. showFilteredOnly,
  1355. isSearching: Boolean(inputValue),
  1356. renderLabel,
  1357. renderFullLabel,
  1358. labelEllipsis: typeof labelEllipsis === 'undefined' ? virtualize : labelEllipsis,
  1359. }}
  1360. >
  1361. <div className={wrapperCls}>
  1362. {outerTopSlot}
  1363. {
  1364. !outerTopSlot &&
  1365. filterTreeNode &&
  1366. isDropdownPositionSearch &&
  1367. this.renderInput()
  1368. }
  1369. <div className={listCls} role="tree" aria-multiselectable={multiple ? true : false} style={optionListStyle}>
  1370. { noData ? this.renderEmpty() : (multiple ?
  1371. (<CheckboxGroup value={Array.from(checkRelation === 'related' ? checkedKeys : realCheckedKeys)}>
  1372. {this.renderNodeList()}
  1373. </CheckboxGroup>) :
  1374. this.renderNodeList()
  1375. )}
  1376. </div>
  1377. {outerBottomSlot}
  1378. </div>
  1379. </TreeContext.Provider>
  1380. );
  1381. };
  1382. render() {
  1383. const content = this.renderContent();
  1384. const {
  1385. motion,
  1386. zIndex,
  1387. mouseLeaveDelay,
  1388. mouseEnterDelay,
  1389. autoAdjustOverflow,
  1390. stopPropagation,
  1391. getPopupContainer,
  1392. dropdownMargin,
  1393. position,
  1394. } = this.props;
  1395. const { isOpen, rePosKey } = this.state;
  1396. const selection = this.renderSelection();
  1397. const pos = position ? position : 'bottomLeft';
  1398. return (
  1399. <Popover
  1400. stopPropagation={stopPropagation}
  1401. getPopupContainer={getPopupContainer}
  1402. zIndex={zIndex}
  1403. motion={motion}
  1404. margin={dropdownMargin}
  1405. ref={this.optionsRef}
  1406. content={content}
  1407. visible={isOpen}
  1408. trigger="custom"
  1409. rePosKey={rePosKey}
  1410. position={pos}
  1411. autoAdjustOverflow={autoAdjustOverflow}
  1412. mouseLeaveDelay={mouseLeaveDelay}
  1413. mouseEnterDelay={mouseEnterDelay}
  1414. onVisibleChange={this.handlePopoverClose}
  1415. >
  1416. {selection}
  1417. </Popover>
  1418. );
  1419. }
  1420. }
  1421. export default TreeSelect;