-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathuse-selection.ts
More file actions
84 lines (73 loc) · 2.42 KB
/
use-selection.ts
File metadata and controls
84 lines (73 loc) · 2.42 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import type { OnChangeFn, RowSelectionState } from "@tanstack/react-table";
import { useCallback, useEffect, useMemo, useRef } from "react";
type QueryRows = {
rows: Record<string, unknown>[];
};
import { useActiveTableDelete } from "./use-active-table-delete";
import { usePagination } from "./use-pagination";
import { useTableUiState } from "./use-table-ui-state";
export function useSelection(data: QueryRows | undefined) {
const { paginationState } = usePagination();
const { mutate } = useActiveTableDelete();
const { scopeKey, tableUiState, updateTableUiState } = useTableUiState();
const rowSelectionState = useMemo(
() => tableUiState?.rowSelectionState ?? {},
[tableUiState?.rowSelectionState],
);
const isSelecting = Object.keys(rowSelectionState).length !== 0;
const previousScopeRef = useRef(scopeKey);
const previousPageIndexRef = useRef(paginationState.pageIndex);
const previousPageSizeRef = useRef(paginationState.pageSize);
useEffect(() => {
const scopeChanged = previousScopeRef.current !== scopeKey;
const pageChanged =
previousPageIndexRef.current !== paginationState.pageIndex;
const pageSizeChanged =
previousPageSizeRef.current !== paginationState.pageSize;
previousScopeRef.current = scopeKey;
previousPageIndexRef.current = paginationState.pageIndex;
previousPageSizeRef.current = paginationState.pageSize;
if (
!scopeKey ||
(!scopeChanged && !pageChanged && !pageSizeChanged) ||
Object.keys(rowSelectionState).length === 0
) {
return;
}
updateTableUiState((draft) => {
draft.rowSelectionState = {};
});
}, [
paginationState.pageIndex,
paginationState.pageSize,
rowSelectionState,
scopeKey,
updateTableUiState,
]);
const setRowSelectionState = useCallback<OnChangeFn<RowSelectionState>>(
(updater) => {
updateTableUiState((draft) => {
const previous = draft.rowSelectionState ?? {};
draft.rowSelectionState =
typeof updater === "function" ? updater(previous) : updater;
});
},
[updateTableUiState],
);
function deleteSelection() {
const rows = data?.rows.filter((row) => {
return rowSelectionState[row.__ps_rowid as string];
});
mutate(rows ?? [], {
onSuccess() {
setRowSelectionState({});
},
});
}
return {
deleteSelection,
setRowSelectionState,
rowSelectionState,
isSelecting,
};
}