index.tsx 63 KB

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