index.tsx 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  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. const clickOutsideHandler = (e: Event) => {
  513. const optionInstance = this.optionsRef && this.optionsRef.current as React.ReactInstance;
  514. const triggerDom = this.triggerRef && this.triggerRef.current;
  515. // eslint-disable-next-line
  516. const optionsDom = ReactDOM.findDOMNode(optionInstance);
  517. const target = e.target as Element;
  518. if (
  519. optionsDom &&
  520. (
  521. !optionsDom.contains(target) ||
  522. !optionsDom.contains(target.parentNode)
  523. ) &&
  524. triggerDom &&
  525. !triggerDom.contains(target)
  526. ) {
  527. cb(e);
  528. }
  529. };
  530. this.clickOutsideHandler = clickOutsideHandler;
  531. document.addEventListener('mousedown', clickOutsideHandler, false);
  532. },
  533. unregisterClickOutsideHandler: () => {
  534. document.removeEventListener('mousedown', this.clickOutsideHandler, false);
  535. this.clickOutsideHandler = null;
  536. },
  537. rePositionDropdown: () => {
  538. let { rePosKey } = this.state;
  539. rePosKey = rePosKey + 1;
  540. this.setState({ rePosKey });
  541. },
  542. };
  543. const treeAdapter: Pick<TreeSelectAdapter,
  544. 'updateState'
  545. | 'notifySelect'
  546. | 'notifySearch'
  547. | 'cacheFlattenNodes'
  548. | 'notifyLoad'
  549. > = {
  550. updateState: states => {
  551. this.setState({ ...states } as TreeSelectState);
  552. },
  553. notifySelect: ((selectKey, bool, node) => {
  554. this.props.onSelect && this.props.onSelect(selectKey, bool, node);
  555. }),
  556. notifySearch: (input, filteredExpandedKeys) => {
  557. this.props.onSearch && this.props.onSearch(input, filteredExpandedKeys);
  558. },
  559. cacheFlattenNodes: bool => {
  560. this._flattenNodes = bool ? cloneDeep(this.state.flattenNodes) : null;
  561. },
  562. notifyLoad: (newLoadedKeys, data) => {
  563. const { onLoad } = this.props;
  564. isFunction(onLoad) && onLoad(newLoadedKeys, data);
  565. }
  566. };
  567. return {
  568. ...super.adapter,
  569. ...filterAdapter,
  570. ...treeSelectAdapter,
  571. ...treeAdapter,
  572. updateLoadKeys: (data, resolve) => {
  573. this.setState(({ loadedKeys, loadingKeys }) =>
  574. this.foundation.handleNodeLoad(loadedKeys, loadingKeys, data, resolve));
  575. },
  576. updateState: states => {
  577. this.setState({ ...states } as TreeSelectState);
  578. },
  579. openMenu: () => {
  580. this.setState({ isOpen: true }, () => {
  581. this.props.onVisibleChange(true);
  582. });
  583. },
  584. closeMenu: cb => {
  585. this.setState({ isOpen: false }, () => {
  586. cb && cb();
  587. this.props.onVisibleChange(false);
  588. });
  589. },
  590. getTriggerWidth: () => {
  591. const el = this.triggerRef.current;
  592. return el && el.getBoundingClientRect().width;
  593. },
  594. setOptionWrapperWidth: width => {
  595. this.setState({ dropdownMinWidth: width });
  596. },
  597. notifyChange: (value, node, e) => {
  598. this.props.onChange && this.props.onChange(value, node, e);
  599. },
  600. notifyChangeWithObject: (node, e) => {
  601. this.props.onChange && this.props.onChange(node, e);
  602. },
  603. notifyExpand: (expandedKeys, { expanded: bool, node }) => {
  604. this.props.onExpand && this.props.onExpand([...expandedKeys], { expanded: bool, node });
  605. if (bool && this.props.loadData) {
  606. this.onNodeLoad(node);
  607. }
  608. },
  609. notifyFocus: (...v) => {
  610. this.props.onFocus && this.props.onFocus(...v);
  611. },
  612. notifyBlur: (...v) => {
  613. this.props.onBlur && this.props.onBlur(...v);
  614. },
  615. toggleHovering: bool => {
  616. this.setState({ isHovering: bool });
  617. },
  618. updateInputFocus: bool => {
  619. if (bool) {
  620. if (this.inputRef && this.inputRef.current) {
  621. const { preventScroll } = this.props;
  622. (this.inputRef.current as any).focus({ preventScroll });
  623. }
  624. if (this.tagInputRef && this.tagInputRef.current) {
  625. this.tagInputRef.current.focus();
  626. }
  627. } else {
  628. if (this.inputRef && this.inputRef.current) {
  629. (this.inputRef.current as any).blur();
  630. }
  631. if (this.tagInputRef && this.tagInputRef.current) {
  632. this.tagInputRef.current.blur();
  633. }
  634. }
  635. },
  636. updateIsFocus: bool => {
  637. this.setState({ isFocus: bool });
  638. }
  639. };
  640. }
  641. componentDidMount() {
  642. this.foundation.init();
  643. }
  644. componentWillUnmount() {
  645. this.foundation.destroy();
  646. }
  647. renderSuffix = () => {
  648. const { suffix }: any = this.props;
  649. const suffixWrapperCls = cls({
  650. [`${prefixcls}-suffix`]: true,
  651. [`${prefixcls}-suffix-text`]: suffix && isString(suffix),
  652. [`${prefixcls}-suffix-icon`]: isSemiIcon(suffix),
  653. });
  654. return (
  655. <div className={suffixWrapperCls} x-semi-prop="suffix">
  656. {suffix}
  657. </div>
  658. );
  659. };
  660. renderPrefix = () => {
  661. const { prefix, insetLabel, insetLabelId }: any = this.props;
  662. const labelNode = prefix || insetLabel;
  663. const prefixWrapperCls = cls({
  664. [`${prefixcls}-prefix`]: true,
  665. // to be doublechecked
  666. [`${prefixcls}-inset-label`]: insetLabel,
  667. [`${prefixcls}-prefix-text`]: labelNode && isString(labelNode),
  668. [`${prefixcls}-prefix-icon`]: isSemiIcon(labelNode),
  669. });
  670. return (
  671. <div className={prefixWrapperCls} id={insetLabelId} x-semi-prop="prefix,insetLabel">
  672. {labelNode}
  673. </div>
  674. );
  675. };
  676. renderContent = () => {
  677. const { dropdownMinWidth } = this.state;
  678. const { dropdownStyle, dropdownClassName } = this.props;
  679. const style = { minWidth: dropdownMinWidth, ...dropdownStyle };
  680. const popoverCls = cls(dropdownClassName, `${prefixcls}-popover`);
  681. return (
  682. <div className={popoverCls} style={style}>
  683. {this.renderTree()}
  684. </div>
  685. );
  686. };
  687. removeTag = (removedKey: TreeNodeData['key']) => {
  688. this.foundation.removeTag(removedKey);
  689. };
  690. handleClick = (e: React.MouseEvent) => {
  691. this.foundation.handleClick(e);
  692. };
  693. getDataForKeyNotInKeyEntities = (key: string) => {
  694. return this.foundation.getDataForKeyNotInKeyEntities(key);
  695. }
  696. /* istanbul ignore next */
  697. handleSelectionEnterPress = (e: React.KeyboardEvent<HTMLDivElement>) => {
  698. this.foundation.handleSelectionEnterPress(e);
  699. };
  700. hasValue = (): boolean => {
  701. const { multiple, checkRelation } = this.props;
  702. const { realCheckedKeys, checkedKeys, selectedKeys } = this.state;
  703. let hasValue = false;
  704. if (multiple) {
  705. if (checkRelation === 'related') {
  706. hasValue = Boolean(checkedKeys.size);
  707. } else if (checkRelation === 'unRelated') {
  708. hasValue = Boolean(realCheckedKeys.size);
  709. }
  710. } else {
  711. hasValue = Boolean(selectedKeys.length);
  712. }
  713. return hasValue;
  714. }
  715. showClearBtn = () => {
  716. const { showClear, disabled, searchPosition } = this.props;
  717. const { inputValue, isOpen, isHovering } = this.state;
  718. const triggerSearchHasInputValue = searchPosition === strings.SEARCH_POSITION_TRIGGER && inputValue;
  719. return showClear && (this.hasValue() || triggerSearchHasInputValue) && !disabled && (isOpen || isHovering);
  720. };
  721. renderTagList = () => {
  722. const { checkedKeys, keyEntities, disabledKeys, realCheckedKeys } = this.state;
  723. const {
  724. treeNodeLabelProp,
  725. leafOnly,
  726. disabled,
  727. disableStrictly,
  728. size,
  729. checkRelation,
  730. renderSelectedItem: propRenderSelectedItem
  731. } = this.props;
  732. const renderSelectedItem = isFunction(propRenderSelectedItem) ?
  733. propRenderSelectedItem :
  734. (item: TreeNodeData) => ({
  735. isRenderInTag: true,
  736. content: get(item, treeNodeLabelProp, null)
  737. });
  738. let renderKeys = [];
  739. if (checkRelation === 'related') {
  740. renderKeys = normalizeKeyList([...checkedKeys], keyEntities, leafOnly, true);
  741. } else if (checkRelation === 'unRelated' && Object.keys(keyEntities).length > 0) {
  742. renderKeys = [...realCheckedKeys];
  743. }
  744. const tagList: Array<React.ReactNode> = [];
  745. // eslint-disable-next-line @typescript-eslint/no-shadow
  746. renderKeys.forEach((key: TreeNodeData['key'], index) => {
  747. const item = (keyEntities[key] && keyEntities[key].data.key === key) ? keyEntities[key].data : this.getDataForKeyNotInKeyEntities(key);
  748. const onClose = (tagContent: any, e: React.MouseEvent) => {
  749. if (e && typeof e.preventDefault === 'function') {
  750. // make sure that tag will not hidden immediately in controlled mode
  751. e.preventDefault();
  752. }
  753. this.removeTag(key);
  754. };
  755. const { content, isRenderInTag } = (item && treeNodeLabelProp in item) ?
  756. (renderSelectedItem as RenderSelectedItemInMultiple)(item, { index, onClose }) :
  757. null;
  758. if (isNull(content) || isUndefined(content)) {
  759. return;
  760. }
  761. const isDisabled = disabled || item.disabled || (disableStrictly && disabledKeys.has(item.key));
  762. const tag: Partial<TagProps> & React.Attributes = {
  763. closable: !isDisabled,
  764. color: 'white',
  765. visible: true,
  766. onClose,
  767. key: `tag-${key}-${index}`,
  768. size: size === 'small' ? 'small' : 'large'
  769. };
  770. if (isRenderInTag) {
  771. // pass ReactNode list to tagList when using tagGroup custom mode
  772. tagList.push(<Tag {...tag}>{content}</Tag>);
  773. } else {
  774. tagList.push(content);
  775. }
  776. });
  777. return tagList;
  778. };
  779. /**
  780. * When single selection and the search box is on trigger, the items displayed in the rendered search box
  781. */
  782. renderSingleTriggerSearchItem = () => {
  783. const { placeholder, disabled } = this.props;
  784. const { inputTriggerFocus } = this.state;
  785. const renderText = this.foundation.getRenderTextInSingle();
  786. const spanCls = cls(`${prefixcls}-selection-TriggerSearchItem`, {
  787. [`${prefixcls}-selection-TriggerSearchItem-placeholder`]: (inputTriggerFocus || !renderText) && !disabled,
  788. [`${prefixcls}-selection-TriggerSearchItem-disabled`]: disabled,
  789. });
  790. return (
  791. <span className={spanCls}>
  792. {renderText ? renderText : placeholder}
  793. </span>
  794. );
  795. };
  796. /**
  797. * Single selection and the search box content rendered when the search box is on trigger
  798. */
  799. renderSingleTriggerSearch = () => {
  800. const { inputValue } = this.state;
  801. return (
  802. <>
  803. {!inputValue && this.renderSingleTriggerSearchItem()}
  804. {this.renderInput()}
  805. </>
  806. );
  807. };
  808. renderSelectContent = () => {
  809. const {
  810. multiple,
  811. placeholder,
  812. maxTagCount,
  813. searchPosition,
  814. filterTreeNode,
  815. showRestTagsPopover,
  816. restTagsPopoverProps
  817. } = this.props;
  818. const isTriggerPositionSearch = filterTreeNode && searchPosition === strings.SEARCH_POSITION_TRIGGER;
  819. // searchPosition = trigger
  820. if (isTriggerPositionSearch) {
  821. return multiple ? this.renderTagInput() : this.renderSingleTriggerSearch();
  822. }
  823. // searchPosition = dropdown and single seleciton
  824. if (!multiple || !this.hasValue()) {
  825. const renderText = this.foundation.getRenderTextInSingle();
  826. const spanCls = cls({
  827. [`${prefixcls}-selection-placeholder`]: !renderText,
  828. });
  829. return <span className={spanCls}>{renderText ? renderText : placeholder}</span>;
  830. }
  831. // searchPosition = dropdown and multiple seleciton
  832. const tagList = this.renderTagList();
  833. // mode=custom to return tagList directly
  834. return (
  835. <TagGroup<'custom'>
  836. maxTagCount={maxTagCount}
  837. tagList={tagList}
  838. size="large"
  839. mode="custom"
  840. showPopover={showRestTagsPopover}
  841. popoverProps={restTagsPopoverProps}
  842. />
  843. );
  844. };
  845. handleClear = (e: React.MouseEvent) => {
  846. e && e.stopPropagation();
  847. this.foundation.handleClear(e);
  848. };
  849. /* istanbul ignore next */
  850. handleClearEnterPress = (e: React.KeyboardEvent<HTMLDivElement>) => {
  851. e && e.stopPropagation();
  852. this.foundation.handleClearEnterPress(e);
  853. };
  854. handleMouseOver = (e: React.MouseEvent) => {
  855. this.foundation.toggleHoverState(true);
  856. };
  857. handleMouseLeave = (e: React.MouseEvent) => {
  858. this.foundation.toggleHoverState(false);
  859. };
  860. search = (value: string) => {
  861. const { isOpen } = this.state;
  862. if (!isOpen) {
  863. this.foundation.open();
  864. }
  865. this.foundation.handleInputChange(value);
  866. };
  867. close = () => {
  868. this.foundation.close(null);
  869. };
  870. renderArrow = () => {
  871. const showClearBtn = this.showClearBtn();
  872. const { arrowIcon } = this.props;
  873. if (showClearBtn) {
  874. return null;
  875. }
  876. return arrowIcon ? (
  877. <div className={cls(`${prefixcls}-arrow`)} x-semi-prop="arrowIcon">
  878. {arrowIcon}
  879. </div>
  880. ) : null;
  881. };
  882. renderClearBtn = () => {
  883. const showClearBtn = this.showClearBtn();
  884. const { clearIcon } = this.props;
  885. const clearCls = cls(`${prefixcls}-clearbtn`);
  886. if (showClearBtn) {
  887. return (
  888. <div
  889. role='button'
  890. tabIndex={0}
  891. aria-label="Clear TreeSelect value"
  892. className={clearCls}
  893. onClick={this.handleClear}
  894. onKeyPress={this.handleClearEnterPress}
  895. >
  896. { clearIcon ? clearIcon : <IconClear />}
  897. </div>
  898. );
  899. }
  900. return null;
  901. };
  902. renderSelection = () => {
  903. const {
  904. disabled,
  905. multiple,
  906. filterTreeNode,
  907. validateStatus,
  908. prefix,
  909. suffix,
  910. style,
  911. size,
  912. insetLabel,
  913. className,
  914. placeholder,
  915. showClear,
  916. leafOnly,
  917. searchPosition,
  918. triggerRender,
  919. borderless,
  920. ...rest
  921. } = this.props;
  922. const { inputValue, selectedKeys, checkedKeys, keyEntities, isFocus } = this.state;
  923. const filterable = Boolean(filterTreeNode);
  924. const useCustomTrigger = typeof triggerRender === 'function';
  925. const mouseEvent = showClear ?
  926. {
  927. onMouseEnter: (e: React.MouseEvent) => this.handleMouseOver(e),
  928. onMouseLeave: (e: React.MouseEvent) => this.handleMouseLeave(e),
  929. } :
  930. {};
  931. const isTriggerPositionSearch = searchPosition === strings.SEARCH_POSITION_TRIGGER && filterable;
  932. const isEmptyTriggerSearch = isTriggerPositionSearch && isEmpty(checkedKeys);
  933. const isValueTriggerSearch = isTriggerPositionSearch && !isEmpty(checkedKeys);
  934. const classNames = useCustomTrigger ?
  935. cls(className) :
  936. cls(
  937. prefixcls,
  938. {
  939. [`${prefixcls}-borderless`]: borderless,
  940. [`${prefixcls}-focus`]: isFocus,
  941. [`${prefixcls}-disabled`]: disabled,
  942. [`${prefixcls}-single`]: !multiple,
  943. [`${prefixcls}-multiple`]: multiple,
  944. [`${prefixcls}-multiple-tagInput-empty`]: multiple && isEmptyTriggerSearch,
  945. [`${prefixcls}-multiple-tagInput-notEmpty`]: multiple && isValueTriggerSearch,
  946. [`${prefixcls}-filterable`]: filterable,
  947. [`${prefixcls}-error`]: validateStatus === 'error',
  948. [`${prefixcls}-warning`]: validateStatus === 'warning',
  949. [`${prefixcls}-small`]: size === 'small',
  950. [`${prefixcls}-large`]: size === 'large',
  951. [`${prefixcls}-with-prefix`]: prefix || insetLabel,
  952. [`${prefixcls}-with-suffix`]: suffix,
  953. [`${prefixcls}-with-suffix`]: suffix,
  954. },
  955. className
  956. );
  957. const triggerRenderKeys = multiple ? normalizeKeyList([...checkedKeys], keyEntities, leafOnly, true) : selectedKeys;
  958. const inner = useCustomTrigger ? (
  959. <Trigger
  960. inputValue={inputValue}
  961. // eslint-disable-next-line @typescript-eslint/no-shadow
  962. value={triggerRenderKeys.map((key: string) => get(keyEntities, [key, 'data']))}
  963. disabled={disabled}
  964. placeholder={placeholder}
  965. onClear={this.handleClear}
  966. componentName={'TreeSelect'}
  967. triggerRender={triggerRender}
  968. componentProps={{ ...this.props }}
  969. onSearch={this.search}
  970. onRemove={this.removeTag}
  971. />
  972. ) : (
  973. [
  974. <Fragment key={'prefix'}>{prefix || insetLabel ? this.renderPrefix() : null}</Fragment>,
  975. <Fragment key={'selection'}>
  976. <div className={`${prefixcls}-selection`}>{this.renderSelectContent()}</div>
  977. </Fragment>,
  978. <Fragment key={'suffix'}>{suffix ? this.renderSuffix() : null}</Fragment>,
  979. <Fragment key={'clearBtn'}>
  980. {
  981. (showClear || (isTriggerPositionSearch && inputValue)) ?
  982. this.renderClearBtn() :
  983. null
  984. }
  985. </Fragment>,
  986. <Fragment key={'arrow'}>{this.renderArrow()}</Fragment>,
  987. ]
  988. );
  989. const tabIndex = disabled ? null : 0;
  990. /**
  991. * Reasons for disabling the a11y eslint rule:
  992. * The following attributes(aria-controls,aria-expanded) will be automatically added by Tooltip, no need to declare here
  993. */
  994. return (
  995. <div
  996. // eslint-disable-next-line jsx-a11y/role-has-required-aria-props
  997. role='combobox'
  998. aria-disabled={disabled}
  999. aria-haspopup="tree"
  1000. tabIndex={tabIndex}
  1001. className={classNames}
  1002. style={style}
  1003. ref={this.triggerRef}
  1004. onClick={this.handleClick}
  1005. onKeyPress={this.handleSelectionEnterPress}
  1006. aria-invalid={this.props['aria-invalid']}
  1007. aria-errormessage={this.props['aria-errormessage']}
  1008. aria-label={this.props['aria-label']}
  1009. aria-labelledby={this.props['aria-labelledby']}
  1010. aria-describedby={this.props['aria-describedby']}
  1011. aria-required={this.props['aria-required']}
  1012. {...mouseEvent}
  1013. {...this.getDataAttr(rest)}
  1014. >
  1015. {inner}
  1016. </div>
  1017. );
  1018. };
  1019. // eslint-disable-next-line @typescript-eslint/no-shadow
  1020. renderTagItem = (key: string, idx: number) => {
  1021. const { keyEntities, disabledKeys } = this.state;
  1022. const {
  1023. size,
  1024. leafOnly,
  1025. disabled,
  1026. disableStrictly,
  1027. renderSelectedItem: propRenderSelectedItem,
  1028. treeNodeLabelProp
  1029. } = this.props;
  1030. const keyList = normalizeKeyList([key], keyEntities, leafOnly, true);
  1031. const nodes = keyList.map(i => (keyEntities[key] && keyEntities[key].data.key === key) ? keyEntities[key].data : this.getDataForKeyNotInKeyEntities(key));
  1032. const value = getValueOrKey(nodes);
  1033. const tagCls = cls(`${prefixcls}-selection-tag`, {
  1034. [`${prefixcls}-selection-tag-disabled`]: disabled,
  1035. });
  1036. const nodeHaveData = !isEmpty(nodes) && !isEmpty(nodes[0]);
  1037. const isDisableStrictlyNode = disableStrictly && nodeHaveData && disabledKeys.has(nodes[0].key);
  1038. const closable = nodeHaveData && !nodes[0].disabled && !disabled && !isDisableStrictlyNode;
  1039. const onClose = (tagChildren: React.ReactNode, e: React.MouseEvent) => {
  1040. // When value has not changed, prevent clicking tag closeBtn to close tag
  1041. e.preventDefault();
  1042. this.removeTag(key);
  1043. };
  1044. const tagProps: Partial<TagProps> & React.Attributes = {
  1045. size: size === 'small' ? 'small' : 'large',
  1046. key: `tag-${value}-${idx}`,
  1047. color: 'white',
  1048. className: tagCls,
  1049. closable,
  1050. onClose,
  1051. };
  1052. const item = nodes[0];
  1053. const renderSelectedItem = isFunction(propRenderSelectedItem) ? propRenderSelectedItem :
  1054. (selectedItem: TreeNodeData) => ({
  1055. isRenderInTag: true,
  1056. content: get(selectedItem, treeNodeLabelProp, null)
  1057. });
  1058. if (isFunction(renderSelectedItem)) {
  1059. const { content, isRenderInTag } = item && treeNodeLabelProp in item ?
  1060. (renderSelectedItem as RenderSelectedItemInMultiple)(item, { index: idx, onClose }) :
  1061. null;
  1062. if (isRenderInTag) {
  1063. return <Tag {...tagProps}>{content}</Tag>;
  1064. } else {
  1065. return content;
  1066. }
  1067. }
  1068. return (
  1069. <Tag {...tagProps}>
  1070. {value}
  1071. </Tag>
  1072. );
  1073. };
  1074. renderTagInput = () => {
  1075. const {
  1076. leafOnly,
  1077. disabled,
  1078. size,
  1079. searchAutoFocus,
  1080. placeholder,
  1081. maxTagCount,
  1082. checkRelation,
  1083. showRestTagsPopover,
  1084. restTagsPopoverProps,
  1085. searchPosition,
  1086. filterTreeNode,
  1087. preventScroll
  1088. } = this.props;
  1089. const {
  1090. keyEntities,
  1091. checkedKeys,
  1092. inputValue,
  1093. realCheckedKeys,
  1094. } = this.state;
  1095. let keyList = [];
  1096. if (checkRelation === 'related') {
  1097. keyList = normalizeKeyList(checkedKeys, keyEntities, leafOnly, true);
  1098. } else if (checkRelation === 'unRelated') {
  1099. keyList = [...realCheckedKeys];
  1100. }
  1101. // auto focus search input divide into two parts
  1102. // 1. filterTreeNode && searchPosition === strings.SEARCH_POSITION_TRIGGER
  1103. // Implemented by passing autofocus to the underlying input's autofocus
  1104. // 2. filterTreeNode && searchPosition === strings.SEARCH_POSITION_DROPDOWN
  1105. // Due to the off-screen rendering in the tooltip implementation mechanism, if it is implemented through the
  1106. // autofocus of the input, when the option panel is opened, the page will scroll to top, so it is necessary
  1107. // to call the focus method through ref in the onVisibleChange callback of the Popover to achieve focus
  1108. const autoFocus = (filterTreeNode && searchPosition === strings.SEARCH_POSITION_TRIGGER) ? searchAutoFocus : undefined;
  1109. return (
  1110. <TagInput
  1111. maxTagCount={maxTagCount}
  1112. disabled={disabled}
  1113. onInputChange={v => this.search(v)}
  1114. ref={this.tagInputRef}
  1115. placeholder={placeholder}
  1116. value={keyList}
  1117. inputValue={inputValue}
  1118. size={size}
  1119. showRestTagsPopover={showRestTagsPopover}
  1120. restTagsPopoverProps={restTagsPopoverProps}
  1121. // eslint-disable-next-line jsx-a11y/no-autofocus
  1122. autoFocus={autoFocus}
  1123. renderTagItem={(itemKey, index) => this.renderTagItem(itemKey, index)}
  1124. onRemove={itemKey => this.removeTag(itemKey)}
  1125. expandRestTagsOnClick={false}
  1126. preventScroll={preventScroll}
  1127. />
  1128. );
  1129. };
  1130. // render Tree
  1131. renderInput = () => {
  1132. const {
  1133. searchPlaceholder,
  1134. searchRender,
  1135. showSearchClear,
  1136. searchPosition,
  1137. searchAutoFocus,
  1138. multiple,
  1139. disabled,
  1140. } = this.props;
  1141. const isDropdownPositionSearch = searchPosition === strings.SEARCH_POSITION_DROPDOWN;
  1142. const inputcls = cls({
  1143. [`${prefixTree}-input`]: isDropdownPositionSearch,
  1144. [`${prefixcls}-inputTrigger`]: !isDropdownPositionSearch
  1145. });
  1146. const { inputValue } = this.state;
  1147. const baseInputProps = {
  1148. value: inputValue,
  1149. className: inputcls,
  1150. onChange: (value: string) => this.search(value),
  1151. };
  1152. const inputDropdownProps = {
  1153. showClear: showSearchClear,
  1154. prefix: <IconSearch />,
  1155. };
  1156. const inputTriggerProps = {
  1157. autofocus: searchAutoFocus,
  1158. onFocus: (e: React.FocusEvent) => this.foundation.handleInputTriggerFocus(),
  1159. onBlur: (e: React.FocusEvent) => this.foundation.handleInputTriggerBlur(),
  1160. disabled,
  1161. };
  1162. const realInputProps = isDropdownPositionSearch ? inputDropdownProps : inputTriggerProps;
  1163. const wrapperCls = cls({
  1164. [`${prefixTree}-search-wrapper`]: isDropdownPositionSearch,
  1165. [`${prefixcls}-triggerSingleSearch-wrapper`]: !isDropdownPositionSearch && !multiple,
  1166. });
  1167. const useCusSearch = typeof searchRender === 'function' || typeof searchRender === 'boolean';
  1168. if (useCusSearch && !searchRender) {
  1169. return null;
  1170. }
  1171. return (
  1172. <div className={wrapperCls}>
  1173. <LocaleConsumer componentName="TreeSelect">
  1174. {(locale: Locale['TreeSelect']) => {
  1175. const placeholder = isDropdownPositionSearch ?
  1176. searchPlaceholder || locale.searchPlaceholder :
  1177. '';
  1178. if (useCusSearch) {
  1179. return (searchRender as any)({ ...realInputProps, ...baseInputProps, placeholder });
  1180. }
  1181. return (
  1182. <Input
  1183. aria-label='Filter TreeSelect item'
  1184. ref={this.inputRef as any}
  1185. placeholder={placeholder}
  1186. {...baseInputProps}
  1187. {...realInputProps}
  1188. />
  1189. );
  1190. }}
  1191. </LocaleConsumer>
  1192. </div>
  1193. );
  1194. };
  1195. renderEmpty = () => {
  1196. const { emptyContent } = this.props;
  1197. if (emptyContent) {
  1198. return <TreeNode empty emptyContent={this.props.emptyContent} />;
  1199. } else {
  1200. return (
  1201. <LocaleConsumer componentName="Tree">
  1202. {(locale: Locale['Tree']) => <TreeNode empty emptyContent={locale.emptyText} />}
  1203. </LocaleConsumer>
  1204. );
  1205. }
  1206. };
  1207. onNodeLoad = (data: TreeNodeData) => new Promise(resolve => this.foundation.setLoadKeys(data, resolve));
  1208. onNodeSelect = (e: React.MouseEvent | React.KeyboardEvent, treeNode: TreeNodeProps) => {
  1209. this.foundation.handleNodeSelect(e, treeNode);
  1210. };
  1211. onNodeCheck = (e: React.MouseEvent | React.KeyboardEvent, treeNode: TreeNodeProps) => {
  1212. this.foundation.handleNodeSelect(e, treeNode);
  1213. };
  1214. onNodeExpand = (e: React.MouseEvent | React.KeyboardEvent, treeNode: TreeNodeProps) => {
  1215. this.foundation.handleNodeExpand(e, treeNode);
  1216. };
  1217. getTreeNodeRequiredProps = () => {
  1218. const { expandedKeys, selectedKeys, checkedKeys, halfCheckedKeys, keyEntities, filteredKeys } = this.state;
  1219. return {
  1220. expandedKeys: expandedKeys || new Set(),
  1221. selectedKeys: selectedKeys || [],
  1222. checkedKeys: checkedKeys || new Set(),
  1223. halfCheckedKeys: halfCheckedKeys || new Set(),
  1224. filteredKeys: filteredKeys || new Set(),
  1225. keyEntities,
  1226. };
  1227. };
  1228. getTreeNodeKey = (treeNode: TreeNodeData) => {
  1229. const { data } = treeNode;
  1230. // eslint-disable-next-line @typescript-eslint/no-shadow
  1231. const { key }: { key: string } = data;
  1232. return key;
  1233. };
  1234. /* Event handler function after popover is closed */
  1235. handlePopoverClose = isVisible => {
  1236. const { filterTreeNode, searchAutoFocus, searchPosition } = this.props;
  1237. if (isVisible === false && Boolean(filterTreeNode)) {
  1238. this.foundation.clearInput();
  1239. }
  1240. if (filterTreeNode && searchPosition === strings.SEARCH_POSITION_DROPDOWN && isVisible && searchAutoFocus) {
  1241. this.foundation.focusInput(true);
  1242. }
  1243. }
  1244. renderTreeNode = (treeNode: FlattenNode, ind: number, style: React.CSSProperties) => {
  1245. const { data } = treeNode;
  1246. // eslint-disable-next-line @typescript-eslint/no-shadow
  1247. const { key }: { key: string } = data;
  1248. const treeNodeProps = this.foundation.getTreeNodeProps(key);
  1249. if (!treeNodeProps) {
  1250. return null;
  1251. }
  1252. return <TreeNode {...treeNodeProps} {...data} key={key} data={data} style={style} />;
  1253. };
  1254. itemKey = (index: number, data: Record<string, any>) => {
  1255. const { visibleOptions } = data;
  1256. // Find the item at the specified index.
  1257. const item = visibleOptions[index];
  1258. // Return a value that uniquely identifies this item.
  1259. return item.key;
  1260. };
  1261. renderNodeList = () => {
  1262. const { flattenNodes, motionKeys, motionType, filteredKeys } = this.state;
  1263. const { direction } = this.context;
  1264. const { virtualize, motionExpand } = this.props;
  1265. const isExpandControlled = 'expandedKeys' in this.props;
  1266. if (!virtualize || isEmpty(virtualize)) {
  1267. return (
  1268. <NodeList
  1269. flattenNodes={flattenNodes}
  1270. flattenList={this._flattenNodes}
  1271. motionKeys={motionExpand ? motionKeys : new Set([])}
  1272. motionType={motionType}
  1273. // When motionKeys is empty, but filteredKeys is not empty (that is, the search hits), this situation should be distinguished from ordinary motionKeys
  1274. searchTargetIsDeep={
  1275. isExpandControlled &&
  1276. motionExpand &&
  1277. isEmpty(motionKeys) &&
  1278. !isEmpty(filteredKeys)
  1279. }
  1280. onMotionEnd={this.onMotionEnd}
  1281. renderTreeNode={this.renderTreeNode}
  1282. />
  1283. );
  1284. }
  1285. const data = {
  1286. visibleOptions: flattenNodes,
  1287. renderOption: this.renderTreeNode
  1288. };
  1289. return (
  1290. <AutoSizer defaultHeight={virtualize.height} defaultWidth={virtualize.width}>
  1291. {({ height, width }) => (
  1292. <VirtualList
  1293. itemCount={flattenNodes.length}
  1294. itemSize={virtualize.itemSize}
  1295. height={height}
  1296. width={width}
  1297. // @ts-ignore avoid strict check of itemKey
  1298. itemKey={this.itemKey}
  1299. itemData={data}
  1300. className={`${prefixTree}-virtual-list`}
  1301. style={{ direction }}
  1302. >
  1303. {VirtualRow}
  1304. </VirtualList>
  1305. )}
  1306. </AutoSizer>
  1307. );
  1308. };
  1309. renderTree = () => {
  1310. const { keyEntities, motionKeys, motionType, inputValue, filteredKeys, flattenNodes, checkedKeys, realCheckedKeys } = this.state;
  1311. const {
  1312. loadData,
  1313. filterTreeNode,
  1314. disabled,
  1315. multiple,
  1316. showFilteredOnly,
  1317. motionExpand,
  1318. outerBottomSlot,
  1319. outerTopSlot,
  1320. expandAction,
  1321. labelEllipsis,
  1322. virtualize,
  1323. optionListStyle,
  1324. searchPosition,
  1325. renderLabel,
  1326. renderFullLabel,
  1327. checkRelation,
  1328. } = this.props;
  1329. const wrapperCls = cls(`${prefixTree}-wrapper`);
  1330. const listCls = cls(`${prefixTree}-option-list`, {
  1331. [`${prefixTree}-option-list-block`]: true,
  1332. });
  1333. const searchNoRes = Boolean(inputValue) && !filteredKeys.size;
  1334. const noData = isEmpty(flattenNodes) || (showFilteredOnly && searchNoRes);
  1335. const isDropdownPositionSearch = searchPosition === strings.SEARCH_POSITION_DROPDOWN;
  1336. return (
  1337. <TreeContext.Provider
  1338. value={{
  1339. loadData,
  1340. treeDisabled: disabled,
  1341. motion: motionExpand,
  1342. motionKeys,
  1343. motionType,
  1344. expandAction,
  1345. filterTreeNode,
  1346. keyEntities,
  1347. onNodeClick: this.onNodeClick,
  1348. onNodeDoubleClick: this.onNodeDoubleClick,
  1349. // tree node will call this function when treeNode is right clicked
  1350. onNodeRightClick: noop,
  1351. onNodeExpand: this.onNodeExpand,
  1352. onNodeSelect: this.onNodeSelect,
  1353. onNodeCheck: this.onNodeCheck,
  1354. renderTreeNode: this.renderTreeNode,
  1355. multiple,
  1356. showFilteredOnly,
  1357. isSearching: Boolean(inputValue),
  1358. renderLabel,
  1359. renderFullLabel,
  1360. labelEllipsis: typeof labelEllipsis === 'undefined' ? virtualize : labelEllipsis,
  1361. }}
  1362. >
  1363. <div className={wrapperCls}>
  1364. {outerTopSlot}
  1365. {
  1366. !outerTopSlot &&
  1367. filterTreeNode &&
  1368. isDropdownPositionSearch &&
  1369. this.renderInput()
  1370. }
  1371. <div className={listCls} role="tree" aria-multiselectable={multiple ? true : false} style={optionListStyle}>
  1372. { noData ? this.renderEmpty() : (multiple ?
  1373. (<CheckboxGroup value={Array.from(checkRelation === 'related' ? checkedKeys : realCheckedKeys)}>
  1374. {this.renderNodeList()}
  1375. </CheckboxGroup>) :
  1376. this.renderNodeList()
  1377. )}
  1378. </div>
  1379. {outerBottomSlot}
  1380. </div>
  1381. </TreeContext.Provider>
  1382. );
  1383. };
  1384. render() {
  1385. const content = this.renderContent();
  1386. const {
  1387. motion,
  1388. zIndex,
  1389. mouseLeaveDelay,
  1390. mouseEnterDelay,
  1391. autoAdjustOverflow,
  1392. stopPropagation,
  1393. getPopupContainer,
  1394. dropdownMargin,
  1395. position,
  1396. } = this.props;
  1397. const { isOpen, rePosKey } = this.state;
  1398. const selection = this.renderSelection();
  1399. const pos = position ? position : 'bottomLeft';
  1400. return (
  1401. <Popover
  1402. stopPropagation={stopPropagation}
  1403. getPopupContainer={getPopupContainer}
  1404. zIndex={zIndex}
  1405. motion={motion}
  1406. margin={dropdownMargin}
  1407. ref={this.optionsRef}
  1408. content={content}
  1409. visible={isOpen}
  1410. trigger="custom"
  1411. rePosKey={rePosKey}
  1412. position={pos}
  1413. autoAdjustOverflow={autoAdjustOverflow}
  1414. mouseLeaveDelay={mouseLeaveDelay}
  1415. mouseEnterDelay={mouseEnterDelay}
  1416. onVisibleChange={this.handlePopoverClose}
  1417. >
  1418. {selection}
  1419. </Popover>
  1420. );
  1421. }
  1422. }
  1423. export default TreeSelect;