index.tsx 62 KB

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