refactor: (Transfer) CC => FC (#39958)

* refactor: (Transfer) CC => FC

* add

* fix

* add

* add

* fix

* fix

* add displayName

* add useEffect

* fix

* add useMergedState

* add

* fix

* fix

* fix snap

* rerun

* rerun ci

* rename
This commit is contained in:
lijianan 2023-01-04 15:09:03 +08:00 committed by GitHub
parent a9bab97d92
commit dc2686d7eb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 288 additions and 321 deletions

View File

@ -142,7 +142,6 @@ class ListBody<RecordType extends KeyWiseTransferItem> extends React.Component<
{this.getItems().map(({ renderedEl, renderedText, item }: RenderedItem<RecordType>) => {
const { disabled } = item;
const checked = selectedKeys.includes(item.key);
return (
<ListItem
disabled={globalDisabled || disabled}
@ -159,7 +158,6 @@ class ListBody<RecordType extends KeyWiseTransferItem> extends React.Component<
);
})}
</ul>
{paginationNode}
</>
);

View File

@ -1,8 +1,10 @@
import classNames from 'classnames';
import * as React from 'react';
import React, { useCallback, useContext, useEffect, useState } from 'react';
import type { ChangeEvent, CSSProperties } from 'react';
import type { ConfigConsumerProps, RenderEmptyHandler } from '../config-provider';
import { ConfigConsumer } from '../config-provider';
import { ConfigContext } from '../config-provider';
import defaultRenderEmpty from '../config-provider/defaultRenderEmpty';
import type { FormItemStatusContextProps } from '../form/context';
import { FormItemInputContext } from '../form/context';
import LocaleReceiver from '../locale/LocaleReceiver';
import defaultLocale from '../locale/en_US';
@ -79,8 +81,8 @@ export interface TransferProps<RecordType> {
onChange?: (targetKeys: string[], direction: TransferDirection, moveKeys: string[]) => void;
onSelectChange?: (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => void;
style?: React.CSSProperties;
listStyle?: ((style: ListStyle) => React.CSSProperties) | React.CSSProperties;
operationStyle?: React.CSSProperties;
listStyle?: ((style: ListStyle) => CSSProperties) | CSSProperties;
operationStyle?: CSSProperties;
titles?: React.ReactNode[];
operations?: string[];
showSearch?: boolean;
@ -88,9 +90,7 @@ export interface TransferProps<RecordType> {
locale?: Partial<TransferLocale>;
footer?: (
props: TransferListProps<RecordType>,
info?: {
direction: TransferDirection;
},
info?: { direction: TransferDirection },
) => React.ReactNode;
rowKey?: (record: RecordType) => string;
onSearch?: (direction: TransferDirection, value: string) => void;
@ -103,11 +103,6 @@ export interface TransferProps<RecordType> {
status?: InputStatus;
}
interface TransferState {
sourceSelectedKeys: string[];
targetSelectedKeys: string[];
}
interface TransferFCProps {
prefixCls: string;
className: string;
@ -116,96 +111,113 @@ interface TransferFCProps {
}
const TransferFC: React.FC<TransferFCProps> = (props) => {
const { prefixCls } = props;
const { prefixCls, className, style, children } = props;
const [wrapSSR, hashId] = useStyle(prefixCls);
return wrapSSR(
<div className={classNames(props.className, hashId)} style={props.style}>
{props.children}
<div className={classNames(className, hashId)} style={style}>
{children}
</div>,
);
};
class Transfer<RecordType extends TransferItem = TransferItem> extends React.Component<
TransferProps<RecordType>,
TransferState
> {
// For high-level customized Transfer @dqaria
static List = List;
static Operation = Operation;
static Search = Search;
static getDerivedStateFromProps<T>({
selectedKeys,
targetKeys,
const Transfer = <RecordType extends TransferItem = TransferItem>(
props: TransferProps<RecordType>,
) => {
const {
dataSource = [],
targetKeys = [],
selectedKeys = [],
selectAllLabels = [],
operations = [],
style = {},
listStyle = {},
locale = {},
titles,
className,
disabled,
showSearch = false,
operationStyle,
showSelectAll,
oneWay,
pagination,
status: customStatus,
prefixCls: customizePrefixCls,
filterOption,
render,
footer,
children,
}: TransferProps<T>) {
if (selectedKeys) {
const mergedTargetKeys = targetKeys || [];
return {
sourceSelectedKeys: selectedKeys.filter((key) => !mergedTargetKeys.includes(key)),
targetSelectedKeys: selectedKeys.filter((key) => mergedTargetKeys.includes(key)),
};
}
rowKey,
onScroll,
onChange,
onSearch,
onSelectChange,
} = props;
const [sourceSelectedKeys, setSourceSelectedKeys] = useState<string[]>(
selectedKeys.filter((key) => !targetKeys.includes(key)),
);
const [targetSelectedKeys, setTargetSelectedKeys] = useState<string[]>(
selectedKeys.filter((key) => targetKeys.includes(key)),
);
useEffect(() => {
if (props.selectedKeys) {
setSourceSelectedKeys(() => selectedKeys.filter((key) => !targetKeys.includes(key)));
setTargetSelectedKeys(() => selectedKeys.filter((key) => targetKeys.includes(key)));
}
}, [props.selectedKeys, props.targetKeys]);
if (process.env.NODE_ENV !== 'production') {
warning(
!pagination || !children,
'Transfer',
'`pagination` not support customize render list.',
);
return null;
}
separatedDataSource: {
leftDataSource: RecordType[];
rightDataSource: RecordType[];
} | null = null;
constructor(props: TransferProps<RecordType>) {
super(props);
const { selectedKeys = [], targetKeys = [] } = props;
this.state = {
sourceSelectedKeys: selectedKeys.filter((key) => !targetKeys.includes(key)),
targetSelectedKeys: selectedKeys.filter((key) => targetKeys.includes(key)),
};
}
setStateKeys = (
direction: TransferDirection,
keys: string[] | ((prevKeys: string[]) => string[]),
) => {
const setStateKeys = useCallback(
(direction: TransferDirection, keys: string[] | ((prevKeys: string[]) => string[])) => {
if (direction === 'left') {
this.setState(({ sourceSelectedKeys }) => ({
sourceSelectedKeys: typeof keys === 'function' ? keys(sourceSelectedKeys || []) : keys,
}));
setSourceSelectedKeys((prev) => (typeof keys === 'function' ? keys(prev || []) : keys));
} else {
this.setState(({ targetSelectedKeys }) => ({
targetSelectedKeys: typeof keys === 'function' ? keys(targetSelectedKeys || []) : keys,
}));
setTargetSelectedKeys((prev) => (typeof keys === 'function' ? keys(prev || []) : keys));
}
},
[sourceSelectedKeys, targetSelectedKeys],
);
const handleSelectChange = useCallback(
(direction: TransferDirection, holder: string[]) => {
if (direction === 'left') {
onSelectChange?.(holder, targetSelectedKeys);
} else {
onSelectChange?.(sourceSelectedKeys, holder);
}
},
[sourceSelectedKeys, targetSelectedKeys],
);
const getTitles = (transferLocale: TransferLocale): React.ReactNode[] =>
titles ?? transferLocale.titles ?? [];
const getLocale = (transferLocale: TransferLocale, renderEmpty: RenderEmptyHandler) => ({
...transferLocale,
notFoundContent: renderEmpty('Transfer'),
...locale,
});
const handleLeftScroll = (e: React.SyntheticEvent<HTMLUListElement>) => {
onScroll?.('left', e);
};
getTitles(transferLocale: TransferLocale): React.ReactNode[] {
return this.props.titles ?? transferLocale.titles ?? [];
}
getLocale = (transferLocale: TransferLocale, renderEmpty: RenderEmptyHandler) => {
const { locale = {} } = this.props;
return { ...transferLocale, notFoundContent: renderEmpty('Transfer'), ...locale };
const handleRightScroll = (e: React.SyntheticEvent<HTMLUListElement>) => {
onScroll?.('right', e);
};
moveTo = (direction: TransferDirection) => {
const { targetKeys = [], dataSource = [], onChange } = this.props;
const { sourceSelectedKeys, targetSelectedKeys } = this.state;
const moveTo = (direction: TransferDirection) => {
const moveKeys = direction === 'right' ? sourceSelectedKeys : targetSelectedKeys;
const dataSourceDisabledKeysMap = groupDisabledKeysMap(dataSource);
// filter the disabled options
const newMoveKeys = moveKeys.filter((key) => !dataSourceDisabledKeysMap.has(key));
const newMoveKeysMap = groupKeysMap(newMoveKeys);
@ -217,62 +229,53 @@ class Transfer<RecordType extends TransferItem = TransferItem> extends React.Com
// empty checked keys
const oppositeDirection = direction === 'right' ? 'left' : 'right';
this.setStateKeys(oppositeDirection, []);
this.handleSelectChange(oppositeDirection, []);
setStateKeys(oppositeDirection, []);
handleSelectChange(oppositeDirection, []);
onChange?.(newTargetKeys, direction, newMoveKeys);
};
moveToLeft = () => this.moveTo('left');
const moveToLeft = () => {
moveTo('left');
};
moveToRight = () => this.moveTo('right');
const moveToRight = () => {
moveTo('right');
};
onItemSelectAll = (direction: TransferDirection, selectedKeys: string[], checkAll: boolean) => {
this.setStateKeys(direction, (prevKeys) => {
const onItemSelectAll = (direction: TransferDirection, keys: string[], checkAll: boolean) => {
setStateKeys(direction, (prevKeys) => {
let mergedCheckedKeys: string[] = [];
if (checkAll) {
// Merge current keys with origin key
mergedCheckedKeys = Array.from(new Set<string>([...prevKeys, ...selectedKeys]));
mergedCheckedKeys = Array.from(new Set<string>([...prevKeys, ...keys]));
} else {
const selectedKeysMap = groupKeysMap(selectedKeys);
const selectedKeysMap = groupKeysMap(keys);
// Remove current keys from origin keys
mergedCheckedKeys = prevKeys.filter((key) => !selectedKeysMap.has(key));
}
this.handleSelectChange(direction, mergedCheckedKeys);
handleSelectChange(direction, mergedCheckedKeys);
return mergedCheckedKeys;
});
};
onLeftItemSelectAll = (selectedKeys: string[], checkAll: boolean) =>
this.onItemSelectAll('left', selectedKeys, checkAll);
onRightItemSelectAll = (selectedKeys: string[], checkAll: boolean) =>
this.onItemSelectAll('right', selectedKeys, checkAll);
handleFilter = (direction: TransferDirection, e: React.ChangeEvent<HTMLInputElement>) => {
const { onSearch } = this.props;
const { value } = e.target;
onSearch?.(direction, value);
const onLeftItemSelectAll = (keys: string[], checkAll: boolean) => {
onItemSelectAll('left', keys, checkAll);
};
handleLeftFilter = (e: React.ChangeEvent<HTMLInputElement>) => this.handleFilter('left', e);
handleRightFilter = (e: React.ChangeEvent<HTMLInputElement>) => this.handleFilter('right', e);
handleClear = (direction: TransferDirection) => {
const { onSearch } = this.props;
onSearch?.(direction, '');
const onRightItemSelectAll = (keys: string[], checkAll: boolean) => {
onItemSelectAll('right', keys, checkAll);
};
handleLeftClear = () => this.handleClear('left');
const leftFilter = (e: ChangeEvent<HTMLInputElement>) => onSearch?.('left', e.target.value);
handleRightClear = () => this.handleClear('right');
const rightFilter = (e: ChangeEvent<HTMLInputElement>) => onSearch?.('right', e.target.value);
onItemSelect = (direction: TransferDirection, selectedKey: string, checked: boolean) => {
const { sourceSelectedKeys, targetSelectedKeys } = this.state;
const holder = direction === 'left' ? [...sourceSelectedKeys] : [...targetSelectedKeys];
const handleLeftClear = () => onSearch?.('left', '');
const handleRightClear = () => onSearch?.('right', '');
const onItemSelect = (direction: TransferDirection, selectedKey: string, checked: boolean) => {
const holder = [...(direction === 'left' ? sourceSelectedKeys : targetSelectedKeys)];
const index = holder.indexOf(selectedKey);
if (index > -1) {
holder.splice(index, 1);
@ -280,77 +283,46 @@ class Transfer<RecordType extends TransferItem = TransferItem> extends React.Com
if (checked) {
holder.push(selectedKey);
}
this.handleSelectChange(direction, holder);
if (!this.props.selectedKeys) {
this.setStateKeys(direction, holder);
handleSelectChange(direction, holder);
if (!props.selectedKeys) {
setStateKeys(direction, holder);
}
};
onLeftItemSelect = (selectedKey: string, checked: boolean) =>
this.onItemSelect('left', selectedKey, checked);
const onLeftItemSelect = (selectedKey: string, checked: boolean) => {
onItemSelect('left', selectedKey, checked);
};
onRightItemSelect = (selectedKey: string, checked: boolean) =>
this.onItemSelect('right', selectedKey, checked);
onRightItemRemove = (selectedKeys: string[]) => {
const { targetKeys = [], onChange } = this.props;
this.setStateKeys('right', []);
const onRightItemSelect = (selectedKey: string, checked: boolean) => {
onItemSelect('right', selectedKey, checked);
};
const onRightItemRemove = (keys: string[]) => {
setStateKeys('right', []);
onChange?.(
targetKeys.filter((key) => !selectedKeys.includes(key)),
targetKeys.filter((key) => !keys.includes(key)),
'left',
[...selectedKeys],
[...keys],
);
};
handleScroll = (direction: TransferDirection, e: React.SyntheticEvent<HTMLUListElement>) => {
const { onScroll } = this.props;
onScroll?.(direction, e);
};
handleLeftScroll = (e: React.SyntheticEvent<HTMLUListElement>) => this.handleScroll('left', e);
handleRightScroll = (e: React.SyntheticEvent<HTMLUListElement>) => this.handleScroll('right', e);
handleSelectChange(direction: TransferDirection, holder: string[]) {
const { sourceSelectedKeys, targetSelectedKeys } = this.state;
const { onSelectChange } = this.props;
if (!onSelectChange) {
return;
}
if (direction === 'left') {
onSelectChange(holder, targetSelectedKeys);
} else {
onSelectChange(sourceSelectedKeys, holder);
}
}
// eslint-disable-next-line class-methods-use-this
handleListStyle = (
listStyle: TransferProps<RecordType>['listStyle'],
const handleListStyle = (
listStyles: TransferProps<RecordType>['listStyle'],
direction: TransferDirection,
) => {
if (typeof listStyle === 'function') {
return listStyle({ direction });
): CSSProperties => {
if (typeof listStyles === 'function') {
return listStyles({ direction });
}
return listStyle;
return listStyles || {};
};
separateDataSource() {
const { dataSource = [], rowKey, targetKeys = [] } = this.props;
const separateDataSource = () => {
const leftDataSource: KeyWise<RecordType>[] = [];
const rightDataSource: KeyWise<RecordType>[] = new Array(targetKeys.length);
const targetKeysMap = groupKeysMap(targetKeys);
dataSource.forEach((record: KeyWise<RecordType>) => {
if (rowKey) {
record = {
...record,
key: rowKey(record),
};
record = { ...record, key: rowKey(record) };
}
// rightDataSource should be ordered by targetKeys
// leftDataSource should be ordered by dataSource
@ -360,47 +332,21 @@ class Transfer<RecordType extends TransferItem = TransferItem> extends React.Com
leftDataSource.push(record);
}
});
return {
leftDataSource,
rightDataSource,
return { leftDataSource, rightDataSource };
};
}
render() {
return (
<LocaleReceiver componentName="Transfer" defaultLocale={defaultLocale.Transfer}>
{(contextLocale) => (
<ConfigConsumer>
{({ getPrefixCls, renderEmpty, direction }: ConfigConsumerProps) => (
<FormItemInputContext.Consumer>
{({ hasFeedback, status: contextStatus }) => {
const {
prefixCls: customizePrefixCls,
className,
disabled,
operations = [],
showSearch = false,
footer,
style,
listStyle = {},
operationStyle,
filterOption,
render,
children,
showSelectAll,
oneWay,
pagination,
status: customStatus,
} = this.props;
const configContext = useContext<ConfigConsumerProps>(ConfigContext);
const formItemContext = useContext<FormItemStatusContextProps>(FormItemInputContext);
const { getPrefixCls, renderEmpty, direction } = configContext;
const { hasFeedback, status } = formItemContext;
const prefixCls = getPrefixCls('transfer', customizePrefixCls);
const locale = this.getLocale(contextLocale, renderEmpty || defaultRenderEmpty);
const { sourceSelectedKeys, targetSelectedKeys } = this.state;
const mergedStatus = getMergedStatus(contextStatus, customStatus);
const mergedStatus = getMergedStatus(status, customStatus);
const mergedPagination = !children && pagination;
const { leftDataSource, rightDataSource } = this.separateDataSource();
const { leftDataSource, rightDataSource } = separateDataSource();
const leftActive = targetSelectedKeys.length > 0;
const rightActive = sourceSelectedKeys.length > 0;
@ -415,41 +361,44 @@ class Transfer<RecordType extends TransferItem = TransferItem> extends React.Com
className,
);
const titles = this.getTitles(locale);
const selectAllLabels = this.props.selectAllLabels || [];
return (
<LocaleReceiver componentName="Transfer" defaultLocale={defaultLocale.Transfer}>
{(contextLocale) => {
const listLocale = getLocale(contextLocale, renderEmpty || defaultRenderEmpty);
const [leftTitle, rightTitle] = getTitles(listLocale);
return (
<TransferFC prefixCls={prefixCls} className={cls} style={style}>
<List<KeyWise<RecordType>>
prefixCls={`${prefixCls}-list`}
titleText={titles?.[0]}
titleText={leftTitle}
dataSource={leftDataSource}
filterOption={filterOption}
style={this.handleListStyle(listStyle, 'left')}
style={handleListStyle(listStyle, 'left')}
checkedKeys={sourceSelectedKeys}
handleFilter={this.handleLeftFilter}
handleClear={this.handleLeftClear}
onItemSelect={this.onLeftItemSelect}
onItemSelectAll={this.onLeftItemSelectAll}
handleFilter={leftFilter}
handleClear={handleLeftClear}
onItemSelect={onLeftItemSelect}
onItemSelectAll={onLeftItemSelectAll}
render={render}
showSearch={showSearch}
renderList={children}
footer={footer}
onScroll={this.handleLeftScroll}
onScroll={handleLeftScroll}
disabled={disabled}
direction={direction === 'rtl' ? 'right' : 'left'}
showSelectAll={showSelectAll}
selectAllLabel={selectAllLabels[0]}
pagination={mergedPagination}
{...locale}
{...listLocale}
/>
<Operation
className={`${prefixCls}-operation`}
rightActive={rightActive}
rightArrowText={operations[0]}
moveToRight={this.moveToRight}
moveToRight={moveToRight}
leftActive={leftActive}
leftArrowText={operations[1]}
moveToLeft={this.moveToLeft}
moveToLeft={moveToLeft}
style={operationStyle}
disabled={disabled}
direction={direction}
@ -457,39 +406,42 @@ class Transfer<RecordType extends TransferItem = TransferItem> extends React.Com
/>
<List<KeyWise<RecordType>>
prefixCls={`${prefixCls}-list`}
titleText={titles?.[1]}
titleText={rightTitle}
dataSource={rightDataSource}
filterOption={filterOption}
style={this.handleListStyle(listStyle, 'right')}
style={handleListStyle(listStyle, 'right')}
checkedKeys={targetSelectedKeys}
handleFilter={this.handleRightFilter}
handleClear={this.handleRightClear}
onItemSelect={this.onRightItemSelect}
onItemSelectAll={this.onRightItemSelectAll}
onItemRemove={this.onRightItemRemove}
handleFilter={rightFilter}
handleClear={handleRightClear}
onItemSelect={onRightItemSelect}
onItemSelectAll={onRightItemSelectAll}
onItemRemove={onRightItemRemove}
render={render}
showSearch={showSearch}
renderList={children}
footer={footer}
onScroll={this.handleRightScroll}
onScroll={handleRightScroll}
disabled={disabled}
direction={direction === 'rtl' ? 'left' : 'right'}
showSelectAll={showSelectAll}
selectAllLabel={selectAllLabels[1]}
showRemove={oneWay}
pagination={mergedPagination}
{...locale}
{...listLocale}
/>
</TransferFC>
);
}}
</FormItemInputContext.Consumer>
)}
</ConfigConsumer>
)}
</LocaleReceiver>
);
}
};
if (process.env.NODE_ENV !== 'production') {
Transfer.displayName = 'Transfer';
}
Transfer.List = List;
Transfer.Search = Search;
Transfer.Operation = Operation;
export default Transfer;

View File

@ -428,4 +428,8 @@ const TransferList = <RecordType extends KeyWiseTransferItem>(
);
};
if (process.env.NODE_ENV !== 'production') {
TransferList.displayName = 'TransferList';
}
export default TransferList;

View File

@ -18,7 +18,8 @@ export interface TransferOperationProps {
oneWay?: boolean;
}
const Operation = ({
const Operation: React.FC<TransferOperationProps> = (props) => {
const {
disabled,
moveToLeft,
moveToRight,
@ -30,7 +31,8 @@ const Operation = ({
style,
direction,
oneWay,
}: TransferOperationProps) => (
} = props;
return (
<div className={className} style={style}>
<Button
type="primary"
@ -53,6 +55,11 @@ const Operation = ({
</Button>
)}
</div>
);
);
};
if (process.env.NODE_ENV !== 'production') {
Operation.displayName = 'Operation';
}
export default Operation;

View File

@ -12,7 +12,7 @@ export interface TransferSearchProps {
disabled?: boolean;
}
export default function Search(props: TransferSearchProps) {
const Search: React.FC<TransferSearchProps> = (props) => {
const { placeholder = '', value, prefixCls, disabled, onChange, handleClear } = props;
const handleChange = React.useCallback(
@ -36,4 +36,10 @@ export default function Search(props: TransferSearchProps) {
prefix={<SearchOutlined />}
/>
);
};
if (process.env.NODE_ENV !== 'production') {
Search.displayName = 'Search';
}
export default Search;