1
0

index.tsx 57 KB

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