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