index.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. import React from 'react';
  2. import cls from 'classnames';
  3. import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
  4. import PropTypes from 'prop-types';
  5. import { isEqual, noop, omit, isEmpty, isArray } from 'lodash';
  6. import TransferFoundation, { TransferAdapter, BasicDataItem, OnSortEndProps } from '@douyinfe/semi-foundation/transfer/foundation';
  7. import { _generateDataByType, _generateSelectedItems } from '@douyinfe/semi-foundation/transfer/transferUtils';
  8. import { cssClasses, strings } from '@douyinfe/semi-foundation/transfer/constants';
  9. import '@douyinfe/semi-foundation/transfer/transfer.scss';
  10. import BaseComponent from '../_base/baseComponent';
  11. import LocaleConsumer from '../locale/localeConsumer';
  12. import { Locale } from '../locale/interface';
  13. import { Checkbox } from '../checkbox/index';
  14. import Input, { InputProps } from '../input/index';
  15. import Spin from '../spin';
  16. import Button from '../button';
  17. import Tree from '../tree';
  18. import { IconClose, IconSearch, IconHandle } from '@douyinfe/semi-icons';
  19. import { Value as TreeValue, TreeProps } from '../tree/interface';
  20. export interface DataItem extends BasicDataItem {
  21. label?: React.ReactNode;
  22. style?: React.CSSProperties
  23. }
  24. export interface GroupItem {
  25. title?: string;
  26. children?: Array<DataItem>
  27. }
  28. export interface TreeItem extends DataItem {
  29. children: Array<TreeItem>
  30. }
  31. export interface RenderSourceItemProps extends DataItem {
  32. checked: boolean;
  33. onChange?: () => void
  34. }
  35. export interface RenderSelectedItemProps extends DataItem {
  36. onRemove?: () => void;
  37. sortableHandle?: typeof SortableHandle
  38. }
  39. export interface EmptyContent {
  40. left?: React.ReactNode;
  41. right?: React.ReactNode;
  42. search?: React.ReactNode
  43. }
  44. export type Type = 'list' | 'groupList' | 'treeList';
  45. export interface SourcePanelProps {
  46. value: Array<string | number>;
  47. /* Loading */
  48. loading: boolean;
  49. /* Whether there are no items that match the current search value */
  50. noMatch: boolean;
  51. /* Items that match the current search value */
  52. filterData: Array<DataItem>;
  53. /* All items */
  54. sourceData: Array<DataItem>;
  55. /* transfer props' dataSource */
  56. propsDataSource: DataSource;
  57. /* Whether to select all */
  58. allChecked: boolean;
  59. /* Number of filtered results */
  60. showNumber: number;
  61. /* Input search box value */
  62. inputValue: string;
  63. /* The function that should be called when the search box changes */
  64. onSearch: (searchString: string) => void;
  65. /* The function that should be called when all the buttons on the left are clicked */
  66. onAllClick: () => void;
  67. /* Selected item on the left */
  68. selectedItems: Map<string | number, DataItem>;
  69. /* The function that should be called when selecting or deleting a single option */
  70. onSelectOrRemove: (item: DataItem) => void;
  71. /* The function that should be called when selecting an option, */
  72. onSelect: (value: Array<string | number>) => void
  73. }
  74. export type OnSortEnd = ({ oldIndex, newIndex }: OnSortEndProps) => void;
  75. export interface SelectedPanelProps {
  76. /* Number of selected options */
  77. length: number;
  78. /* Collection of all selected options */
  79. selectedData: Array<DataItem>;
  80. /* Callback function that should be called when click to clear */
  81. onClear: () => void;
  82. /* The function that should be called when a single option is deleted */
  83. onRemove: (item: DataItem) => void;
  84. /* The function that should be called when reordering the results */
  85. onSortEnd: OnSortEnd
  86. }
  87. export interface ResolvedDataItem extends DataItem {
  88. _parent?: {
  89. title: string
  90. };
  91. _optionKey?: string | number
  92. }
  93. export interface DraggableResolvedDataItem {
  94. key?: string | number;
  95. index?: number;
  96. item?: ResolvedDataItem
  97. }
  98. export type DataSource = Array<DataItem> | Array<GroupItem> | Array<TreeItem>;
  99. interface HeaderConfig {
  100. totalContent: string;
  101. allContent: string;
  102. onAllClick: () => void;
  103. type: string;
  104. showButton: boolean
  105. }
  106. export interface TransferState {
  107. data: Array<ResolvedDataItem>;
  108. selectedItems: Map<number | string, ResolvedDataItem>;
  109. searchResult: Set<number | string>;
  110. inputValue: string
  111. }
  112. export interface TransferProps {
  113. style?: React.CSSProperties;
  114. className?: string;
  115. disabled?: boolean;
  116. dataSource?: DataSource;
  117. filter?: boolean | ((sugInput: string, item: DataItem) => boolean);
  118. defaultValue?: Array<string | number>;
  119. value?: Array<string | number>;
  120. inputProps?: InputProps;
  121. type?: Type;
  122. emptyContent?: EmptyContent;
  123. draggable?: boolean;
  124. treeProps?: Omit<TreeProps, 'value' | 'ref' | 'onChange'>;
  125. showPath?: boolean;
  126. loading?: boolean;
  127. onChange?: (values: Array<string | number>, items: Array<DataItem>) => void;
  128. onSelect?: (item: DataItem) => void;
  129. onDeselect?: (item: DataItem) => void;
  130. onSearch?: (sunInput: string) => void;
  131. renderSourceItem?: (item: RenderSourceItemProps) => React.ReactNode;
  132. renderSelectedItem?: (item: RenderSelectedItemProps) => React.ReactNode;
  133. renderSourcePanel?: (sourcePanelProps: SourcePanelProps) => React.ReactNode;
  134. renderSelectedPanel?: (selectedPanelProps: SelectedPanelProps) => React.ReactNode
  135. }
  136. const prefixcls = cssClasses.PREFIX;
  137. // SortableItem & SortableList should not be assigned inside of the render function
  138. const SortableItem = SortableElement((
  139. (props: DraggableResolvedDataItem) => (props.item.node as React.FC<DraggableResolvedDataItem>)
  140. ));
  141. const SortableList = SortableContainer(({ items }: { items: Array<ResolvedDataItem> }) => (
  142. <div className={`${prefixcls}-right-list`} role="list" aria-label="Selected list">
  143. {items.map((item, index: number) => (
  144. // @ts-ignore skip SortableItem type check
  145. <SortableItem key={item.label} index={index} item={item} />
  146. ))}
  147. </div>
  148. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  149. // @ts-ignore see reasons: https://github.com/clauderic/react-sortable-hoc/issues/206
  150. ), { distance: 10 });
  151. class Transfer extends BaseComponent<TransferProps, TransferState> {
  152. static propTypes = {
  153. style: PropTypes.object,
  154. className: PropTypes.string,
  155. disabled: PropTypes.bool,
  156. dataSource: PropTypes.array,
  157. filter: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
  158. onSearch: PropTypes.func,
  159. inputProps: PropTypes.object,
  160. value: PropTypes.array,
  161. defaultValue: PropTypes.array,
  162. onChange: PropTypes.func,
  163. onSelect: PropTypes.func,
  164. onDeselect: PropTypes.func,
  165. renderSourceItem: PropTypes.func,
  166. renderSelectedItem: PropTypes.func,
  167. loading: PropTypes.bool,
  168. type: PropTypes.oneOf(['list', 'groupList', 'treeList']),
  169. treeProps: PropTypes.object,
  170. showPath: PropTypes.bool,
  171. emptyContent: PropTypes.shape({
  172. search: PropTypes.node,
  173. left: PropTypes.node,
  174. right: PropTypes.node,
  175. }),
  176. renderSourcePanel: PropTypes.func,
  177. renderSelectedPanel: PropTypes.func,
  178. draggable: PropTypes.bool,
  179. };
  180. static defaultProps = {
  181. type: strings.TYPE_LIST,
  182. dataSource: [] as DataSource,
  183. onSearch: noop,
  184. onChange: noop,
  185. onSelect: noop,
  186. onDeselect: noop,
  187. onClear: noop,
  188. defaultValue: [] as Array<string | number>,
  189. emptyContent: {},
  190. showPath: false,
  191. };
  192. _treeRef: Tree = null;
  193. constructor(props: TransferProps) {
  194. super(props);
  195. const { defaultValue = [], dataSource, type } = props;
  196. this.foundation = new TransferFoundation<TransferProps, TransferState>(this.adapter);
  197. this.state = {
  198. data: [],
  199. selectedItems: new Map(),
  200. searchResult: new Set(),
  201. inputValue: '',
  202. };
  203. if (Boolean(dataSource) && isArray(dataSource)) {
  204. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  205. // @ts-ignore Avoid reporting errors this.state.xxx is read-only
  206. this.state.data = _generateDataByType(dataSource, type);
  207. }
  208. if (Boolean(defaultValue) && isArray(defaultValue)) {
  209. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  210. // @ts-ignore Avoid reporting errors this.state.xxx is read-only
  211. this.state.selectedItems = _generateSelectedItems(defaultValue, this.state.data);
  212. }
  213. this.onSelectOrRemove = this.onSelectOrRemove.bind(this);
  214. this.onInputChange = this.onInputChange.bind(this);
  215. this.onSortEnd = this.onSortEnd.bind(this);
  216. }
  217. static getDerivedStateFromProps(props: TransferProps, state: TransferState) {
  218. const { value, dataSource, type, filter } = props;
  219. const mergedState = {} as TransferState;
  220. let newData = state.data;
  221. let newSelectedItems = state.selectedItems;
  222. if (Boolean(dataSource) && Array.isArray(dataSource)) {
  223. newData = _generateDataByType(dataSource, type);
  224. mergedState.data = newData;
  225. }
  226. if (Boolean(value) && Array.isArray(value)) {
  227. newSelectedItems = _generateSelectedItems(value, newData);
  228. mergedState.selectedItems = newSelectedItems;
  229. }
  230. if (!isEqual(state.data, newData)) {
  231. if (typeof state.inputValue === 'string' && state.inputValue !== '') {
  232. const filterFunc = typeof filter === 'function' ?
  233. (item: DataItem) => filter(state.inputValue, item) :
  234. (item: DataItem) => typeof item.label === 'string' && item.label.includes(state.inputValue);
  235. const searchData = newData.filter(filterFunc);
  236. const searchResult = new Set(searchData.map(item => item.key));
  237. mergedState.searchResult = searchResult;
  238. }
  239. }
  240. return isEmpty(mergedState) ? null : mergedState;
  241. }
  242. get adapter(): TransferAdapter<TransferProps, TransferState> {
  243. return {
  244. ...super.adapter,
  245. getSelected: () => new Map(this.state.selectedItems),
  246. updateSelected: selectedItems => {
  247. this.setState({ selectedItems });
  248. },
  249. notifyChange: (values, items) => {
  250. this.props.onChange(values, items);
  251. },
  252. notifySearch: input => {
  253. this.props.onSearch(input);
  254. },
  255. notifySelect: item => {
  256. this.props.onSelect(item);
  257. },
  258. notifyDeselect: item => {
  259. this.props.onDeselect(item);
  260. },
  261. updateInput: input => {
  262. this.setState({ inputValue: input });
  263. },
  264. updateSearchResult: searchResult => {
  265. this.setState({ searchResult });
  266. },
  267. searchTree: keyword => {
  268. this._treeRef && (this._treeRef as any).search(keyword); // TODO check this._treeRef.current?
  269. }
  270. };
  271. }
  272. onInputChange(value: string) {
  273. this.foundation.handleInputChange(value, true);
  274. }
  275. search(value: string) {
  276. // The search method is used to provide the user with a manually triggered search
  277. // Since the method is manually called by the user, setting the second parameter to false does not trigger the onSearch callback to notify the user
  278. this.foundation.handleInputChange(value, false);
  279. }
  280. onSelectOrRemove(item: ResolvedDataItem) {
  281. this.foundation.handleSelectOrRemove(item);
  282. }
  283. onSortEnd(callbackProps: OnSortEndProps) {
  284. this.foundation.handleSortEnd(callbackProps);
  285. }
  286. renderFilter(locale: Locale['Transfer']) {
  287. const { inputProps, filter, disabled } = this.props;
  288. if (typeof filter === 'boolean' && !filter) {
  289. return null;
  290. }
  291. return (
  292. <div role="search" aria-label="Transfer filter" className={`${prefixcls}-filter`}>
  293. <Input
  294. prefix={<IconSearch />}
  295. placeholder={locale.placeholder}
  296. showClear
  297. value={this.state.inputValue}
  298. disabled={disabled}
  299. onChange={this.onInputChange}
  300. {...inputProps}
  301. />
  302. </div>
  303. );
  304. }
  305. renderHeader(headerConfig: HeaderConfig) {
  306. const { disabled } = this.props;
  307. const { totalContent, allContent, onAllClick, type, showButton } = headerConfig;
  308. const headerCls = cls({
  309. [`${prefixcls}-header`]: true,
  310. [`${prefixcls}-right-header`]: type === 'right',
  311. [`${prefixcls}-left-header`]: type === 'left',
  312. });
  313. return (
  314. <div className={headerCls}>
  315. <span className={`${prefixcls}-header-total`}>{totalContent}</span>
  316. {showButton ? (
  317. <Button
  318. theme="borderless"
  319. disabled={disabled}
  320. type="tertiary"
  321. size="small"
  322. className={`${prefixcls}-header-all`}
  323. onClick={onAllClick}
  324. >
  325. {allContent}
  326. </Button>
  327. ) : null}
  328. </div>
  329. );
  330. }
  331. renderLeftItem(item: ResolvedDataItem, index: number) {
  332. const { renderSourceItem, disabled } = this.props;
  333. const { selectedItems } = this.state;
  334. const checked = selectedItems.has(item.key);
  335. if (renderSourceItem) {
  336. return renderSourceItem({ ...item, checked, onChange: () => this.onSelectOrRemove(item) });
  337. }
  338. const leftItemCls = cls({
  339. [`${prefixcls}-item`]: true,
  340. [`${prefixcls}-item-disabled`]: item.disabled,
  341. });
  342. return (
  343. <Checkbox
  344. key={index}
  345. disabled={item.disabled || disabled}
  346. className={leftItemCls}
  347. checked={checked}
  348. role="listitem"
  349. onChange={() => this.onSelectOrRemove(item)}
  350. x-semi-children-alias={`dataSource[${index}].label`}
  351. >
  352. {item.label}
  353. </Checkbox>
  354. );
  355. }
  356. renderLeft(locale: Locale['Transfer']) {
  357. const { data, selectedItems, inputValue, searchResult } = this.state;
  358. const { loading, type, emptyContent, renderSourcePanel, dataSource } = this.props;
  359. const totalToken = locale.total;
  360. const inSearchMode = inputValue !== '';
  361. const showNumber = inSearchMode ? searchResult.size : data.length;
  362. const filterData = inSearchMode ? data.filter(item => searchResult.has(item.key)) : data;
  363. // Whether to select all should be a judgment, whether the filtered data on the left is a subset of the selected items
  364. // For example, the filtered data on the left is 1, 3, 4;
  365. // The selected option is 1,2,3,4, it is true
  366. // The selected option is 2,3,4, then it is false
  367. const leftContainesNotInSelected = Boolean(filterData.find(f => !selectedItems.has(f.key)));
  368. const totalText = totalToken.replace('${total}', `${showNumber}`);
  369. const headerConfig: HeaderConfig = {
  370. totalContent: totalText,
  371. allContent: leftContainesNotInSelected ? locale.selectAll : locale.clearSelectAll,
  372. onAllClick: () => this.foundation.handleAll(leftContainesNotInSelected),
  373. type: 'left',
  374. showButton: type !== strings.TYPE_TREE_TO_LIST,
  375. };
  376. const inputCom = this.renderFilter(locale);
  377. const headerCom = this.renderHeader(headerConfig);
  378. const noMatch = inSearchMode && searchResult.size === 0;
  379. const emptySearch = emptyContent.search ? emptyContent.search : locale.emptySearch;
  380. const emptyLeft = emptyContent.left ? emptyContent.left : locale.emptyLeft;
  381. const emptyDataCom = this.renderEmpty('left', emptyLeft);
  382. const emptySearchCom = this.renderEmpty('left', emptySearch);
  383. const loadingCom = <Spin />;
  384. let content: React.ReactNode = null;
  385. switch (true) {
  386. case loading:
  387. content = loadingCom;
  388. break;
  389. case noMatch:
  390. content = emptySearchCom;
  391. break;
  392. case data.length === 0:
  393. content = emptyDataCom;
  394. break;
  395. case type === strings.TYPE_TREE_TO_LIST:
  396. content = (
  397. <>
  398. {headerCom}
  399. {this.renderLeftTree()}
  400. </>
  401. );
  402. break;
  403. case !noMatch && (type === strings.TYPE_LIST || type === strings.TYPE_GROUP_LIST):
  404. content = (
  405. <>
  406. {headerCom}
  407. {this.renderLeftList(filterData)}
  408. </>
  409. );
  410. break;
  411. default:
  412. content = null;
  413. break;
  414. }
  415. const { values } = this.foundation.getValuesAndItemsFromMap(selectedItems);
  416. const renderProps: SourcePanelProps = {
  417. loading,
  418. noMatch,
  419. filterData,
  420. sourceData: data,
  421. propsDataSource: dataSource,
  422. allChecked: !leftContainesNotInSelected,
  423. showNumber,
  424. inputValue,
  425. selectedItems,
  426. value: values,
  427. onSelect: this.foundation.handleSelect.bind(this.foundation),
  428. onAllClick: () => this.foundation.handleAll(leftContainesNotInSelected),
  429. onSearch: this.onInputChange,
  430. onSelectOrRemove: (item: ResolvedDataItem) => this.onSelectOrRemove(item),
  431. };
  432. if (renderSourcePanel) {
  433. return renderSourcePanel(renderProps);
  434. }
  435. return (
  436. <section className={`${prefixcls}-left`}>
  437. {inputCom}
  438. {content}
  439. </section>
  440. );
  441. }
  442. renderGroupTitle(group: GroupItem, index: number) {
  443. const groupCls = cls(`${prefixcls }-group-title`);
  444. return (
  445. <div className={groupCls} key={`title-${index}`}>
  446. {group.title}
  447. </div>
  448. );
  449. }
  450. renderLeftTree() {
  451. const { selectedItems } = this.state;
  452. const { disabled, dataSource, treeProps } = this.props;
  453. const { values } = this.foundation.getValuesAndItemsFromMap(selectedItems);
  454. const onChange = (value: TreeValue) => {
  455. this.foundation.handleSelect(value);
  456. };
  457. const restTreeProps = omit(treeProps, ['value', 'ref', 'onChange']);
  458. return (
  459. <Tree
  460. disabled={disabled}
  461. treeData={dataSource as any}
  462. multiple
  463. disableStrictly
  464. value={values}
  465. defaultExpandAll
  466. leafOnly
  467. ref={tree => this._treeRef = tree}
  468. filterTreeNode
  469. searchRender={false}
  470. searchStyle={{ padding: 0 }}
  471. style={{ flex: 1, overflow: 'overlay' }}
  472. onChange={onChange}
  473. {...restTreeProps}
  474. />
  475. );
  476. }
  477. renderLeftList(visibileItems: Array<ResolvedDataItem>) {
  478. const content = [] as Array<React.ReactNode>;
  479. const groupStatus = new Map();
  480. visibileItems.forEach((item, index) => {
  481. const parentGroup = item._parent;
  482. const optionContent = this.renderLeftItem(item, index);
  483. if (parentGroup && groupStatus.has(parentGroup.title)) {
  484. // group content already insert
  485. content.push(optionContent);
  486. } else if (parentGroup) {
  487. const groupContent = this.renderGroupTitle(parentGroup, index);
  488. groupStatus.set(parentGroup.title, true);
  489. content.push(groupContent);
  490. content.push(optionContent);
  491. } else {
  492. content.push(optionContent);
  493. }
  494. });
  495. return <div className={`${prefixcls}-left-list`} role="list" aria-label="Option list">{content}</div>;
  496. }
  497. renderRightItem(item: ResolvedDataItem): React.ReactNode {
  498. const { renderSelectedItem, draggable, type, showPath } = this.props;
  499. const onRemove = () => this.foundation.handleSelectOrRemove(item);
  500. const rightItemCls = cls({
  501. [`${prefixcls}-item`]: true,
  502. [`${prefixcls}-right-item`]: true,
  503. [`${prefixcls}-right-item-draggable`]: draggable
  504. });
  505. const shouldShowPath = type === strings.TYPE_TREE_TO_LIST && showPath === true;
  506. const label = shouldShowPath ? this.foundation._generatePath(item) : item.label;
  507. if (renderSelectedItem) {
  508. return renderSelectedItem({ ...item, onRemove, sortableHandle: SortableHandle });
  509. }
  510. const DragHandle = SortableHandle(() => (
  511. <IconHandle role="button" aria-label="Drag and sort" className={`${prefixcls}-right-item-drag-handler`} />
  512. ));
  513. return (
  514. // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
  515. <div role="listitem" className={rightItemCls} key={item.key}>
  516. {draggable ? <DragHandle /> : null}
  517. <div className={`${prefixcls}-right-item-text`}>{label}</div>
  518. <IconClose
  519. onClick={onRemove}
  520. aria-disabled={item.disabled}
  521. className={cls(`${prefixcls}-item-close-icon`, {
  522. [`${prefixcls}-item-close-icon-disabled`]: item.disabled
  523. })}
  524. />
  525. </div>
  526. );
  527. }
  528. renderEmpty(type: string, emptyText: React.ReactNode) {
  529. const emptyCls = cls({
  530. [`${prefixcls}-empty`]: true,
  531. [`${prefixcls}-right-empty`]: type === 'right',
  532. [`${prefixcls}-left-empty`]: type === 'left',
  533. });
  534. return <div aria-label="empty" className={emptyCls}>{emptyText}</div>;
  535. }
  536. renderRightSortableList(selectedData: Array<ResolvedDataItem>) {
  537. const sortableListItems = selectedData.map(item => ({
  538. ...item,
  539. node: this.renderRightItem(item)
  540. }));
  541. // helperClass:add styles to the helper(item being dragged) https://github.com/clauderic/react-sortable-hoc/issues/87
  542. // @ts-ignore skip SortableItem type check
  543. const sortList = <SortableList useDragHandle helperClass={`${prefixcls}-right-item-drag-item-move`} onSortEnd={this.onSortEnd} items={sortableListItems} />;
  544. return sortList;
  545. }
  546. renderRight(locale: Locale['Transfer']) {
  547. const { selectedItems } = this.state;
  548. const { emptyContent, renderSelectedPanel, draggable } = this.props;
  549. const selectedData = [...selectedItems.values()];
  550. // when custom render panel
  551. const renderProps: SelectedPanelProps = {
  552. length: selectedData.length,
  553. selectedData,
  554. onClear: () => this.foundation.handleClear(),
  555. onRemove: item => this.foundation.handleSelectOrRemove(item),
  556. onSortEnd: props => this.onSortEnd(props)
  557. };
  558. if (renderSelectedPanel) {
  559. return renderSelectedPanel(renderProps);
  560. }
  561. const selectedToken = locale.selected;
  562. const selectedText = selectedToken.replace('${total}', `${selectedData.length}`);
  563. const headerConfig = {
  564. totalContent: selectedText,
  565. allContent: locale.clear,
  566. onAllClick: () => this.foundation.handleClear(),
  567. type: 'right',
  568. showButton: Boolean(selectedData.length),
  569. };
  570. const headerCom = this.renderHeader(headerConfig);
  571. const emptyCom = this.renderEmpty('right', emptyContent.right ? emptyContent.right : locale.emptyRight);
  572. const panelCls = `${prefixcls}-right`;
  573. let content = null;
  574. switch (true) {
  575. // when empty
  576. case !selectedData.length:
  577. content = emptyCom;
  578. break;
  579. case selectedData.length && !draggable:
  580. const list = (
  581. <div className={`${prefixcls}-right-list`} role="list" aria-label="Selected list">
  582. {selectedData.map(item => this.renderRightItem({ ...item }))}
  583. </div>
  584. );
  585. content = list;
  586. break;
  587. case selectedData.length && draggable:
  588. content = this.renderRightSortableList(selectedData);
  589. break;
  590. default:
  591. break;
  592. }
  593. return (
  594. <section className={panelCls}>
  595. {headerCom}
  596. {content}
  597. </section>
  598. );
  599. }
  600. render() {
  601. const { className, style, disabled, renderSelectedPanel, renderSourcePanel } = this.props;
  602. const transferCls = cls(prefixcls, className, {
  603. [`${prefixcls}-disabled`]: disabled,
  604. [`${prefixcls}-custom-panel`]: renderSelectedPanel && renderSourcePanel,
  605. });
  606. return (
  607. <LocaleConsumer componentName="Transfer">
  608. {(locale: Locale['Transfer']) => (
  609. <div className={transferCls} style={style}>
  610. {this.renderLeft(locale)}
  611. {this.renderRight(locale)}
  612. </div>
  613. )}
  614. </LocaleConsumer>
  615. );
  616. }
  617. }
  618. export default Transfer;