index.tsx 62 KB

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