mirror of
https://gitee.com/ant-design/ant-design.git
synced 2024-12-16 01:41:02 +08:00
47f30ee266
* fix: transfer error when reset data in some cases * fix: lint * fix: error * DX: improvement * fix: code style * fix: code style * chore: update grammar * chore: update * chore: update * refactor: keys sync logic * chore: clean up --------- Co-authored-by: 洋 <hetongyang@bytedance.com> Co-authored-by: 二货机器人 <smith3816@gmail.com>
58 lines
1.7 KiB
TypeScript
58 lines
1.7 KiB
TypeScript
import * as React from 'react';
|
|
|
|
const EMPTY_KEYS: string[] = [];
|
|
|
|
function filterKeys(keys: string[], dataKeys: Set<string>) {
|
|
const filteredKeys = keys.filter((key) => dataKeys.has(key));
|
|
return keys.length === filteredKeys.length ? keys : filteredKeys;
|
|
}
|
|
|
|
export default function useSelection<T extends { key: string }>(
|
|
leftDataSource: T[],
|
|
rightDataSource: T[],
|
|
selectedKeys: string[] = EMPTY_KEYS,
|
|
): [
|
|
sourceSelectedKeys: string[],
|
|
targetSelectedKeys: string[],
|
|
setSourceSelectedKeys: React.Dispatch<React.SetStateAction<string[]>>,
|
|
setTargetSelectedKeys: React.Dispatch<React.SetStateAction<string[]>>,
|
|
] {
|
|
// Prepare `dataSource` keys
|
|
const [leftKeys, rightKeys] = React.useMemo(
|
|
() => [
|
|
new Set(leftDataSource.map((src) => src.key)),
|
|
new Set(rightDataSource.map((src) => src.key)),
|
|
],
|
|
[leftDataSource, rightDataSource],
|
|
);
|
|
|
|
// Selected Keys
|
|
const [sourceSelectedKeys, setSourceSelectedKeys] = React.useState(() =>
|
|
filterKeys(selectedKeys, leftKeys),
|
|
);
|
|
const [targetSelectedKeys, setTargetSelectedKeys] = React.useState(() =>
|
|
filterKeys(selectedKeys, rightKeys),
|
|
);
|
|
|
|
// Fill selected keys
|
|
React.useEffect(() => {
|
|
setSourceSelectedKeys(filterKeys(selectedKeys, leftKeys));
|
|
setTargetSelectedKeys(filterKeys(selectedKeys, rightKeys));
|
|
}, [selectedKeys]);
|
|
|
|
// Reset when data changed
|
|
React.useEffect(() => {
|
|
setSourceSelectedKeys(filterKeys(sourceSelectedKeys, leftKeys));
|
|
setTargetSelectedKeys(filterKeys(targetSelectedKeys, rightKeys));
|
|
}, [leftKeys, rightKeys]);
|
|
|
|
return [
|
|
// Keys
|
|
sourceSelectedKeys,
|
|
targetSelectedKeys,
|
|
// Updater
|
|
setSourceSelectedKeys,
|
|
setTargetSelectedKeys,
|
|
];
|
|
}
|