-
-
Notifications
You must be signed in to change notification settings - Fork 619
Expand file tree
/
Copy pathuseStickyOffsets.ts
More file actions
54 lines (43 loc) · 1.48 KB
/
useStickyOffsets.ts
File metadata and controls
54 lines (43 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { useMemo } from 'react';
import type { ColumnType, StickyOffsets } from '../interface';
/**
* Get sticky column offset width
* @param colWidths - Column widths array
* @param flattenColumns - Flattened columns
* @param rowContext - Optional row context for dynamic colSpan calculation
*/
function useStickyOffsets<RecordType>(
colWidths: number[],
flattenColumns: readonly ColumnType<RecordType>[],
rowContext?: { record: RecordType; rowIndex: number },
) {
const stickyOffsets: StickyOffsets = useMemo(() => {
const columnCount = flattenColumns.length;
const getOffsets = (startIndex: number, endIndex: number, offset: number) => {
const offsets: number[] = [];
let total = 0;
for (let i = startIndex; i !== endIndex; i += offset) {
const column = flattenColumns[i];
offsets.push(total);
let colSpan = 1;
if (rowContext) {
const cellProps = column.onCell?.(rowContext.record, rowContext.rowIndex) || {};
colSpan = cellProps.colSpan ?? 1;
}
if (column.fixed && colSpan !== 0) {
total += colWidths[i] || 0;
}
}
return offsets;
};
const startOffsets = getOffsets(0, columnCount, 1);
const endOffsets = getOffsets(columnCount - 1, -1, -1).reverse();
return {
start: startOffsets,
end: endOffsets,
widths: colWidths,
};
}, [colWidths, flattenColumns, rowContext]);
return stickyOffsets;
}
export default useStickyOffsets;