index.tsx 58 KB

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