2023-06-07 22:54:56 +08:00
|
|
|
import * as React from 'react';
|
2023-12-25 15:30:08 +08:00
|
|
|
|
2023-06-07 22:54:56 +08:00
|
|
|
import type { KeyWise, TransferProps } from '..';
|
|
|
|
import { groupKeysMap } from '../../_util/transKeys';
|
2023-12-25 15:30:08 +08:00
|
|
|
import type { AnyObject } from '../../_util/type';
|
2023-06-07 22:54:56 +08:00
|
|
|
|
2023-12-25 15:30:08 +08:00
|
|
|
const useData = <RecordType extends AnyObject>(
|
2023-06-07 22:54:56 +08:00
|
|
|
dataSource?: RecordType[],
|
|
|
|
rowKey?: TransferProps<RecordType>['rowKey'],
|
2023-06-09 15:44:25 +08:00
|
|
|
targetKeys?: string[],
|
2023-12-25 15:30:08 +08:00
|
|
|
) => {
|
2023-06-07 22:54:56 +08:00
|
|
|
const mergedDataSource = React.useMemo(
|
|
|
|
() =>
|
|
|
|
(dataSource || []).map((record: KeyWise<RecordType>) => {
|
|
|
|
if (rowKey) {
|
|
|
|
record = { ...record, key: rowKey(record) };
|
|
|
|
}
|
|
|
|
return record;
|
|
|
|
}),
|
|
|
|
[dataSource, rowKey],
|
|
|
|
);
|
|
|
|
|
|
|
|
const [leftDataSource, rightDataSource] = React.useMemo(() => {
|
|
|
|
const leftData: KeyWise<RecordType>[] = [];
|
2023-06-09 15:44:25 +08:00
|
|
|
const rightData: KeyWise<RecordType>[] = new Array((targetKeys || []).length);
|
|
|
|
const targetKeysMap = groupKeysMap(targetKeys || []);
|
2023-06-07 22:54:56 +08:00
|
|
|
mergedDataSource.forEach((record: KeyWise<RecordType>) => {
|
|
|
|
// rightData should be ordered by targetKeys
|
|
|
|
// leftData should be ordered by dataSource
|
|
|
|
if (targetKeysMap.has(record.key)) {
|
|
|
|
rightData[targetKeysMap.get(record.key)!] = record;
|
|
|
|
} else {
|
|
|
|
leftData.push(record);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return [leftData, rightData] as const;
|
|
|
|
}, [mergedDataSource, targetKeys, rowKey]);
|
|
|
|
|
|
|
|
return [mergedDataSource, leftDataSource, rightDataSource];
|
2023-12-25 15:30:08 +08:00
|
|
|
};
|
2023-06-09 15:44:25 +08:00
|
|
|
|
|
|
|
export default useData;
|