2023-05-06 15:49:37 +08:00
|
|
|
import * as React from 'react';
|
2024-04-08 14:04:08 +08:00
|
|
|
|
2024-08-11 10:58:13 +08:00
|
|
|
import type { AnyObject } from '../../_util/type';
|
2022-06-22 14:57:09 +08:00
|
|
|
import type { GetRowKey, Key } from '../interface';
|
2019-11-15 14:35:25 +08:00
|
|
|
|
2024-08-13 10:34:52 +08:00
|
|
|
interface MapCache<RecordType = AnyObject> {
|
2021-01-28 01:21:58 +08:00
|
|
|
data?: readonly RecordType[];
|
2019-11-15 14:35:25 +08:00
|
|
|
childrenColumnName?: string;
|
|
|
|
kvMap?: Map<Key, RecordType>;
|
2024-06-22 21:59:12 +08:00
|
|
|
getRowKey?: (record: RecordType, index: number) => Key;
|
2019-11-15 14:35:25 +08:00
|
|
|
}
|
|
|
|
|
2024-08-11 10:58:13 +08:00
|
|
|
const useLazyKVMap = <RecordType extends AnyObject = AnyObject>(
|
2021-01-28 01:21:58 +08:00
|
|
|
data: readonly RecordType[],
|
2019-11-15 14:35:25 +08:00
|
|
|
childrenColumnName: string,
|
|
|
|
getRowKey: GetRowKey<RecordType>,
|
2024-08-11 10:58:13 +08:00
|
|
|
) => {
|
2019-11-15 14:35:25 +08:00
|
|
|
const mapCacheRef = React.useRef<MapCache<RecordType>>({});
|
|
|
|
|
|
|
|
function getRecordByKey(key: Key): RecordType {
|
|
|
|
if (
|
|
|
|
!mapCacheRef.current ||
|
|
|
|
mapCacheRef.current.data !== data ||
|
|
|
|
mapCacheRef.current.childrenColumnName !== childrenColumnName ||
|
|
|
|
mapCacheRef.current.getRowKey !== getRowKey
|
|
|
|
) {
|
|
|
|
const kvMap = new Map<Key, RecordType>();
|
|
|
|
|
|
|
|
/* eslint-disable no-inner-declarations */
|
2021-01-28 01:21:58 +08:00
|
|
|
function dig(records: readonly RecordType[]) {
|
2019-11-15 14:35:25 +08:00
|
|
|
records.forEach((record, index) => {
|
|
|
|
const rowKey = getRowKey(record, index);
|
|
|
|
kvMap.set(rowKey, record);
|
|
|
|
|
2020-08-05 22:29:38 +08:00
|
|
|
if (record && typeof record === 'object' && childrenColumnName in record) {
|
2020-02-22 22:19:33 +08:00
|
|
|
dig((record as any)[childrenColumnName] || []);
|
2019-11-15 14:35:25 +08:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
/* eslint-enable */
|
|
|
|
|
|
|
|
dig(data);
|
|
|
|
|
|
|
|
mapCacheRef.current = {
|
|
|
|
data,
|
|
|
|
childrenColumnName,
|
|
|
|
kvMap,
|
|
|
|
getRowKey,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2024-08-11 10:58:13 +08:00
|
|
|
return mapCacheRef.current.kvMap?.get(key)!;
|
2019-11-15 14:35:25 +08:00
|
|
|
}
|
|
|
|
|
2024-08-11 10:58:13 +08:00
|
|
|
return [getRecordByKey] as const;
|
|
|
|
};
|
|
|
|
|
|
|
|
export default useLazyKVMap;
|