2023-06-07 22:54:56 +08:00
|
|
|
import * as React from 'react';
|
2024-03-14 21:14:21 +08:00
|
|
|
import type { TransferKey } from '../interface';
|
2023-06-07 22:54:56 +08:00
|
|
|
|
2024-03-14 21:14:21 +08:00
|
|
|
const EMPTY_KEYS: TransferKey[] = [];
|
2023-06-07 22:54:56 +08:00
|
|
|
|
2024-03-14 21:14:21 +08:00
|
|
|
function filterKeys(keys: TransferKey[], dataKeys: Set<TransferKey>) {
|
2023-06-07 22:54:56 +08:00
|
|
|
const filteredKeys = keys.filter((key) => dataKeys.has(key));
|
|
|
|
return keys.length === filteredKeys.length ? keys : filteredKeys;
|
|
|
|
}
|
|
|
|
|
2024-03-14 21:14:21 +08:00
|
|
|
function flattenKeys(keys: Set<TransferKey>) {
|
2023-06-20 13:41:35 +08:00
|
|
|
return Array.from(keys).join(';');
|
|
|
|
}
|
|
|
|
|
2024-03-14 21:14:21 +08:00
|
|
|
export default function useSelection<T extends { key: TransferKey }>(
|
2023-06-07 22:54:56 +08:00
|
|
|
leftDataSource: T[],
|
|
|
|
rightDataSource: T[],
|
2024-03-14 21:14:21 +08:00
|
|
|
selectedKeys: TransferKey[] = EMPTY_KEYS,
|
2023-06-07 22:54:56 +08:00
|
|
|
): [
|
2024-03-14 21:14:21 +08:00
|
|
|
sourceSelectedKeys: TransferKey[],
|
|
|
|
targetSelectedKeys: TransferKey[],
|
|
|
|
setSourceSelectedKeys: React.Dispatch<React.SetStateAction<TransferKey[]>>,
|
|
|
|
setTargetSelectedKeys: React.Dispatch<React.SetStateAction<TransferKey[]>>,
|
2023-06-07 22:54:56 +08:00
|
|
|
] {
|
|
|
|
// 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));
|
2023-06-20 13:41:35 +08:00
|
|
|
}, [flattenKeys(leftKeys), flattenKeys(rightKeys)]);
|
2023-06-07 22:54:56 +08:00
|
|
|
|
|
|
|
return [
|
|
|
|
// Keys
|
|
|
|
sourceSelectedKeys,
|
|
|
|
targetSelectedKeys,
|
|
|
|
// Updater
|
|
|
|
setSourceSelectedKeys,
|
|
|
|
setTargetSelectedKeys,
|
|
|
|
];
|
|
|
|
}
|