-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
useMRT_Effects.ts
77 lines (70 loc) · 2.32 KB
/
useMRT_Effects.ts
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { useEffect, useRef } from 'react';
import { getCanRankRows } from '../column.utils';
import { type MRT_SortingState, type MRT_TableInstance } from '../types';
export const useMRT_Effects = <TData extends Record<string, any> = {}>(
table: MRT_TableInstance<TData>,
) => {
const {
getState,
options: { enablePagination, rowCount },
} = table;
const {
globalFilter,
isFullScreen,
pagination,
sorting,
isLoading,
showSkeletons,
} = getState();
const isMounted = useRef(false);
const initialBodyHeight = useRef<string>();
const previousTop = useRef<number>();
useEffect(() => {
if (typeof window !== 'undefined') {
initialBodyHeight.current = document.body.style.height;
}
}, []);
useEffect(() => {
if (isMounted && typeof window !== 'undefined') {
if (isFullScreen) {
previousTop.current = document.body.getBoundingClientRect().top; //save scroll position
document.body.style.height = '100vh'; //hide page scrollbars when table is in full screen mode
} else {
document.body.style.height = initialBodyHeight.current as string;
if (!previousTop.current) return;
//restore scroll position
window.scrollTo({
top: -1 * (previousTop.current as number),
behavior: 'instant',
});
}
}
isMounted.current = true;
}, [isFullScreen]);
//if page index is out of bounds, set it to the last page
useEffect(() => {
if (!enablePagination || isLoading || showSkeletons) return;
const { pageIndex, pageSize } = pagination;
const totalRowCount =
rowCount ?? table.getPrePaginationRowModel().rows.length;
const firstVisibleRowIndex = pageIndex * pageSize;
if (firstVisibleRowIndex > totalRowCount) {
table.setPageIndex(Math.floor(totalRowCount / pageSize));
}
}, [rowCount, table.getPrePaginationRowModel().rows.length]);
//turn off sort when global filter is looking for ranked results
const appliedSort = useRef<MRT_SortingState>(sorting);
useEffect(() => {
if (sorting.length) {
appliedSort.current = sorting;
}
}, [sorting]);
useEffect(() => {
if (!getCanRankRows(table)) return;
if (globalFilter) {
table.setSorting([]);
} else {
table.setSorting(() => appliedSort.current || []);
}
}, [globalFilter]);
};