@@ -3,11 +3,83 @@ import type {
33 SortedTablePaginatorProps ,
44} from '../@types/ui-react-dom/index.js' ;
55import { mathMin } from '../common/other.ts' ;
6- import { useCallbackOrUndefined } from './common.tsx' ;
6+ import { useCallbackOrUndefined } from './common/hooks.tsx' ;
7+
8+ import type { ComponentType , ReactNode } from 'react' ;
9+ import type { Id } from '../@types/index.js' ;
10+ import { useCallback , useMemo , useState } from '../common/react.ts' ;
11+ import { HandleSort , SortAndOffset } from './common/index.tsx' ;
712
813const LEFT_ARROW = '\u2190' ;
914const RIGHT_ARROW = '\u2192' ;
1015
16+ export const useSortingAndPagination = (
17+ cellId : Id | undefined ,
18+ descending = false ,
19+ sortOnClick : boolean | undefined ,
20+ offset = 0 ,
21+ limit : number | undefined ,
22+ total : number ,
23+ paginator : boolean | ComponentType < SortedTablePaginatorProps > ,
24+ onChange ?: ( sortAndOffset : SortAndOffset ) => void ,
25+ ) : [
26+ sortAndOffset : SortAndOffset ,
27+ handleSort : HandleSort ,
28+ paginatorComponent : ReactNode | undefined ,
29+ ] => {
30+ const [ [ currentCellId , currentDescending , currentOffset ] , setState ] =
31+ useState < SortAndOffset > ( [ cellId , descending , offset ] ) ;
32+ const setStateAndChange = useCallback (
33+ ( sortAndOffset : SortAndOffset ) => {
34+ setState ( sortAndOffset ) ;
35+ onChange ?.( sortAndOffset ) ;
36+ } ,
37+ [ onChange ] ,
38+ ) ;
39+ const handleSort = useCallbackOrUndefined (
40+ ( cellId : Id | undefined ) =>
41+ setStateAndChange ( [
42+ cellId ,
43+ cellId == currentCellId ? ! currentDescending : false ,
44+ currentOffset ,
45+ ] ) ,
46+ [ setStateAndChange , currentCellId , currentDescending , currentOffset ] ,
47+ sortOnClick ,
48+ ) ;
49+ const handleChangeOffset = useCallback (
50+ ( offset : number ) =>
51+ setStateAndChange ( [ currentCellId , currentDescending , offset ] ) ,
52+ [ setStateAndChange , currentCellId , currentDescending ] ,
53+ ) ;
54+ const PaginatorComponent =
55+ paginator === true
56+ ? SortedTablePaginator
57+ : ( paginator as ComponentType < SortedTablePaginatorProps > ) ;
58+ return [
59+ [ currentCellId , currentDescending , currentOffset ] ,
60+ handleSort ,
61+ useMemo (
62+ ( ) =>
63+ paginator === false ? null : (
64+ < PaginatorComponent
65+ offset = { currentOffset }
66+ limit = { limit }
67+ total = { total }
68+ onChange = { handleChangeOffset }
69+ />
70+ ) ,
71+ [
72+ paginator ,
73+ PaginatorComponent ,
74+ currentOffset ,
75+ limit ,
76+ total ,
77+ handleChangeOffset ,
78+ ] ,
79+ ) ,
80+ ] ;
81+ } ;
82+
1183export const SortedTablePaginator : typeof SortedTablePaginatorDecl = ( {
1284 onChange,
1385 total,
0 commit comments