@checkstack/ui 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -0
- package/package.json +1 -1
- package/src/components/PaginatedList.tsx +35 -20
- package/src/hooks/usePagination.ts +80 -163
- package/src/hooks/usePagination.e2e.ts +0 -275
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,70 @@
|
|
|
1
1
|
# @checkstack/ui
|
|
2
2
|
|
|
3
|
+
## 0.2.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [4eed42d]
|
|
8
|
+
- @checkstack/frontend-api@0.3.0
|
|
9
|
+
|
|
10
|
+
## 0.2.1
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- 7a23261: ## TanStack Query Integration
|
|
15
|
+
|
|
16
|
+
Migrated all frontend components to use `usePluginClient` hook with TanStack Query integration, replacing the legacy `forPlugin()` pattern.
|
|
17
|
+
|
|
18
|
+
### New Features
|
|
19
|
+
|
|
20
|
+
- **`usePluginClient` hook**: Provides type-safe access to plugin APIs with `.useQuery()` and `.useMutation()` methods
|
|
21
|
+
- **Automatic request deduplication**: Multiple components requesting the same data share a single network request
|
|
22
|
+
- **Built-in caching**: Configurable stale time and cache duration per query
|
|
23
|
+
- **Loading/error states**: TanStack Query provides `isLoading`, `error`, `isRefetching` states automatically
|
|
24
|
+
- **Background refetching**: Stale data is automatically refreshed when components mount
|
|
25
|
+
|
|
26
|
+
### Contract Changes
|
|
27
|
+
|
|
28
|
+
All RPC contracts now require `operationType: "query"` or `operationType: "mutation"` metadata:
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
const getItems = proc()
|
|
32
|
+
.meta({ operationType: "query", access: [access.read] })
|
|
33
|
+
.output(z.array(itemSchema))
|
|
34
|
+
.query();
|
|
35
|
+
|
|
36
|
+
const createItem = proc()
|
|
37
|
+
.meta({ operationType: "mutation", access: [access.manage] })
|
|
38
|
+
.input(createItemSchema)
|
|
39
|
+
.output(itemSchema)
|
|
40
|
+
.mutation();
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Migration
|
|
44
|
+
|
|
45
|
+
```typescript
|
|
46
|
+
// Before (forPlugin pattern)
|
|
47
|
+
const api = useApi(myPluginApiRef);
|
|
48
|
+
const [items, setItems] = useState<Item[]>([]);
|
|
49
|
+
useEffect(() => {
|
|
50
|
+
api.getItems().then(setItems);
|
|
51
|
+
}, [api]);
|
|
52
|
+
|
|
53
|
+
// After (usePluginClient pattern)
|
|
54
|
+
const client = usePluginClient(MyPluginApi);
|
|
55
|
+
const { data: items, isLoading } = client.getItems.useQuery({});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Bug Fixes
|
|
59
|
+
|
|
60
|
+
- Fixed `rpc.test.ts` test setup for middleware type inference
|
|
61
|
+
- Fixed `SearchDialog` to use `setQuery` instead of deprecated `search` method
|
|
62
|
+
- Fixed null→undefined warnings in notification and queue frontends
|
|
63
|
+
|
|
64
|
+
- Updated dependencies [7a23261]
|
|
65
|
+
- @checkstack/frontend-api@0.2.0
|
|
66
|
+
- @checkstack/common@0.3.0
|
|
67
|
+
|
|
3
68
|
## 0.2.0
|
|
4
69
|
|
|
5
70
|
### Minor Changes
|
package/package.json
CHANGED
|
@@ -1,14 +1,24 @@
|
|
|
1
1
|
import * as React from "react";
|
|
2
|
-
import {
|
|
3
|
-
usePagination,
|
|
4
|
-
type UsePaginationOptions,
|
|
5
|
-
type PaginationState,
|
|
6
|
-
} from "../hooks/usePagination";
|
|
2
|
+
import { type PaginationState } from "../hooks/usePagination";
|
|
7
3
|
import { Pagination } from "./Pagination";
|
|
8
4
|
import { cn } from "../utils";
|
|
9
5
|
|
|
10
|
-
export interface PaginatedListProps<
|
|
11
|
-
|
|
6
|
+
export interface PaginatedListProps<TItem> {
|
|
7
|
+
/**
|
|
8
|
+
* Items to display
|
|
9
|
+
*/
|
|
10
|
+
items: TItem[];
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Loading state
|
|
14
|
+
*/
|
|
15
|
+
loading: boolean;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Pagination state from usePagination hook
|
|
19
|
+
*/
|
|
20
|
+
pagination: PaginationState;
|
|
21
|
+
|
|
12
22
|
/**
|
|
13
23
|
* Render function for the items
|
|
14
24
|
*/
|
|
@@ -64,23 +74,31 @@ export interface PaginatedListProps<TResponse, TItem, TExtraParams = object>
|
|
|
64
74
|
}
|
|
65
75
|
|
|
66
76
|
/**
|
|
67
|
-
*
|
|
77
|
+
* Paginated list component for rendering paginated data.
|
|
78
|
+
* Use with usePagination() hook and TanStack Query.
|
|
68
79
|
*
|
|
69
80
|
* @example
|
|
70
81
|
* ```tsx
|
|
82
|
+
* const pagination = usePagination({ defaultLimit: 20 });
|
|
83
|
+
* const { data, isLoading } = notificationClient.getNotifications.useQuery({
|
|
84
|
+
* limit: pagination.limit,
|
|
85
|
+
* offset: pagination.offset,
|
|
86
|
+
* });
|
|
87
|
+
* usePaginationSync(pagination, data?.total);
|
|
88
|
+
*
|
|
71
89
|
* <PaginatedList
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
* extraParams={{ unreadOnly: true }}
|
|
90
|
+
* items={data?.notifications ?? []}
|
|
91
|
+
* loading={isLoading}
|
|
92
|
+
* pagination={pagination}
|
|
76
93
|
* >
|
|
77
|
-
* {(items
|
|
78
|
-
* loading ? null : items.map((item) => <Card key={item.id} {...item} />)
|
|
79
|
-
* }
|
|
94
|
+
* {(items) => items.map((item) => <Card key={item.id} {...item} />)}
|
|
80
95
|
* </PaginatedList>
|
|
81
96
|
* ```
|
|
82
97
|
*/
|
|
83
|
-
export function PaginatedList<
|
|
98
|
+
export function PaginatedList<TItem>({
|
|
99
|
+
items,
|
|
100
|
+
loading,
|
|
101
|
+
pagination,
|
|
84
102
|
children,
|
|
85
103
|
showLoadingSpinner = true,
|
|
86
104
|
emptyContent,
|
|
@@ -90,10 +108,7 @@ export function PaginatedList<TResponse, TItem, TExtraParams = object>({
|
|
|
90
108
|
pageSizes,
|
|
91
109
|
className,
|
|
92
110
|
paginationClassName,
|
|
93
|
-
|
|
94
|
-
}: PaginatedListProps<TResponse, TItem, TExtraParams>) {
|
|
95
|
-
const { items, loading, pagination } = usePagination(paginationOptions);
|
|
96
|
-
|
|
111
|
+
}: PaginatedListProps<TItem>) {
|
|
97
112
|
const showEmpty = !loading && items.length === 0 && emptyContent;
|
|
98
113
|
|
|
99
114
|
return (
|
|
@@ -1,66 +1,17 @@
|
|
|
1
|
-
import { useState,
|
|
1
|
+
import { useState, useCallback, useMemo, useEffect } from "react";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* Pagination
|
|
5
|
-
|
|
6
|
-
export interface PaginationParams {
|
|
7
|
-
limit: number;
|
|
8
|
-
offset: number;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Options for usePagination hook
|
|
13
|
-
*/
|
|
14
|
-
export interface UsePaginationOptions<TResponse, TItem, TExtraParams = object> {
|
|
15
|
-
/**
|
|
16
|
-
* Fetch function that receives pagination + extra params and returns response
|
|
17
|
-
*/
|
|
18
|
-
fetchFn: (params: PaginationParams & TExtraParams) => Promise<TResponse>;
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Extract items array from the response
|
|
22
|
-
*/
|
|
23
|
-
getItems: (response: TResponse) => TItem[];
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Extract total count from the response
|
|
27
|
-
*/
|
|
28
|
-
getTotal: (response: TResponse) => number;
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Extra parameters to pass to fetchFn (merged with pagination params)
|
|
32
|
-
* Changes to this object will trigger a refetch
|
|
33
|
-
*/
|
|
34
|
-
extraParams?: TExtraParams;
|
|
35
|
-
|
|
36
|
-
/**
|
|
37
|
-
* Initial page number (1-indexed)
|
|
38
|
-
* @default 1
|
|
39
|
-
*/
|
|
40
|
-
defaultPage?: number;
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Items per page
|
|
44
|
-
* @default 10
|
|
45
|
-
*/
|
|
46
|
-
defaultLimit?: number;
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* Whether to fetch on mount
|
|
50
|
-
* @default true
|
|
51
|
-
*/
|
|
52
|
-
fetchOnMount?: boolean;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* Pagination state returned by usePagination hook
|
|
4
|
+
* Pagination state and controls.
|
|
5
|
+
* Used with TanStack Query's useQuery hook for paginated data.
|
|
57
6
|
*/
|
|
58
7
|
export interface PaginationState {
|
|
59
8
|
/** Current page (1-indexed) */
|
|
60
9
|
page: number;
|
|
61
10
|
/** Items per page */
|
|
62
11
|
limit: number;
|
|
63
|
-
/**
|
|
12
|
+
/** Offset for query (calculated from page and limit) */
|
|
13
|
+
offset: number;
|
|
14
|
+
/** Total number of items (set via setTotal) */
|
|
64
15
|
total: number;
|
|
65
16
|
/** Total number of pages */
|
|
66
17
|
totalPages: number;
|
|
@@ -72,130 +23,74 @@ export interface PaginationState {
|
|
|
72
23
|
setPage: (page: number) => void;
|
|
73
24
|
/** Change items per page (resets to page 1) */
|
|
74
25
|
setLimit: (limit: number) => void;
|
|
26
|
+
/** Update total count from query response */
|
|
27
|
+
setTotal: (total: number) => void;
|
|
75
28
|
/** Go to next page */
|
|
76
29
|
nextPage: () => void;
|
|
77
30
|
/** Go to previous page */
|
|
78
31
|
prevPage: () => void;
|
|
79
|
-
/** Refresh current page (shows loading state) */
|
|
80
|
-
refetch: () => void;
|
|
81
|
-
/** Refresh current page silently (no loading state, prevents UI flicker) */
|
|
82
|
-
silentRefetch: () => void;
|
|
83
32
|
}
|
|
84
33
|
|
|
85
34
|
/**
|
|
86
|
-
*
|
|
35
|
+
* Options for usePagination hook.
|
|
87
36
|
*/
|
|
88
|
-
export interface
|
|
89
|
-
/**
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
|
|
37
|
+
export interface UsePaginationOptions {
|
|
38
|
+
/**
|
|
39
|
+
* Initial page number (1-indexed)
|
|
40
|
+
* @default 1
|
|
41
|
+
*/
|
|
42
|
+
defaultPage?: number;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Items per page
|
|
46
|
+
* @default 10
|
|
47
|
+
*/
|
|
48
|
+
defaultLimit?: number;
|
|
97
49
|
}
|
|
98
50
|
|
|
99
51
|
/**
|
|
100
|
-
* Hook for managing
|
|
52
|
+
* Hook for managing pagination state to use with TanStack Query.
|
|
53
|
+
*
|
|
54
|
+
* This hook manages page/limit state and provides computed offset for queries.
|
|
55
|
+
* Use with useQuery to build paginated data fetching.
|
|
101
56
|
*
|
|
102
57
|
* @example
|
|
103
58
|
* ```tsx
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
59
|
+
* // Simple usage with usePluginClient
|
|
60
|
+
* const pagination = usePagination({ defaultLimit: 20 });
|
|
61
|
+
*
|
|
62
|
+
* const { data, isLoading } = notificationClient.getNotifications.useQuery({
|
|
63
|
+
* limit: pagination.limit,
|
|
64
|
+
* offset: pagination.offset,
|
|
65
|
+
* unreadOnly: true,
|
|
109
66
|
* });
|
|
110
67
|
*
|
|
68
|
+
* // Update total when data changes
|
|
69
|
+
* useEffect(() => {
|
|
70
|
+
* if (data) pagination.setTotal(data.total);
|
|
71
|
+
* }, [data, pagination]);
|
|
72
|
+
*
|
|
111
73
|
* return (
|
|
112
74
|
* <>
|
|
113
|
-
* {
|
|
114
|
-
* <Pagination {...pagination} />
|
|
75
|
+
* {data?.notifications.map(n => <Notification key={n.id} {...n} />)}
|
|
76
|
+
* <Pagination {...pagination} loading={isLoading} />
|
|
115
77
|
* </>
|
|
116
78
|
* );
|
|
117
79
|
* ```
|
|
118
80
|
*/
|
|
119
|
-
export function usePagination
|
|
120
|
-
fetchFn,
|
|
121
|
-
getItems,
|
|
122
|
-
getTotal,
|
|
123
|
-
extraParams,
|
|
81
|
+
export function usePagination({
|
|
124
82
|
defaultPage = 1,
|
|
125
83
|
defaultLimit = 10,
|
|
126
|
-
|
|
127
|
-
}: UsePaginationOptions<
|
|
128
|
-
TResponse,
|
|
129
|
-
TItem,
|
|
130
|
-
TExtraParams
|
|
131
|
-
>): UsePaginationResult<TItem> {
|
|
132
|
-
const [items, setItems] = useState<TItem[]>([]);
|
|
133
|
-
const [loading, setLoading] = useState(fetchOnMount);
|
|
134
|
-
const [error, setError] = useState<Error>();
|
|
84
|
+
}: UsePaginationOptions = {}): PaginationState {
|
|
135
85
|
const [page, setPageState] = useState(defaultPage);
|
|
136
86
|
const [limit, setLimitState] = useState(defaultLimit);
|
|
137
|
-
const [total,
|
|
138
|
-
|
|
139
|
-
// Use refs for callback functions to avoid re-creating fetchData when they change
|
|
140
|
-
// This is better DX - callers don't need to memoize their functions
|
|
141
|
-
const fetchFnRef = useRef(fetchFn);
|
|
142
|
-
const getItemsRef = useRef(getItems);
|
|
143
|
-
const getTotalRef = useRef(getTotal);
|
|
144
|
-
const extraParamsRef = useRef(extraParams);
|
|
145
|
-
|
|
146
|
-
// Update refs when functions change
|
|
147
|
-
fetchFnRef.current = fetchFn;
|
|
148
|
-
getItemsRef.current = getItems;
|
|
149
|
-
getTotalRef.current = getTotal;
|
|
150
|
-
extraParamsRef.current = extraParams;
|
|
151
|
-
|
|
152
|
-
// Memoize extraParams to detect changes
|
|
153
|
-
const extraParamsKey = useMemo(
|
|
154
|
-
() => JSON.stringify(extraParams ?? {}),
|
|
155
|
-
[extraParams]
|
|
156
|
-
);
|
|
87
|
+
const [total, setTotalState] = useState(0);
|
|
157
88
|
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
}
|
|
163
|
-
setError(undefined);
|
|
164
|
-
|
|
165
|
-
try {
|
|
166
|
-
const offset = (page - 1) * limit;
|
|
167
|
-
const params = {
|
|
168
|
-
limit,
|
|
169
|
-
offset,
|
|
170
|
-
...extraParamsRef.current,
|
|
171
|
-
} as PaginationParams & TExtraParams;
|
|
172
|
-
|
|
173
|
-
const response = await fetchFnRef.current(params);
|
|
174
|
-
setItems(getItemsRef.current(response));
|
|
175
|
-
setTotal(getTotalRef.current(response));
|
|
176
|
-
} catch (error_) {
|
|
177
|
-
setError(error_ instanceof Error ? error_ : new Error(String(error_)));
|
|
178
|
-
setItems([]);
|
|
179
|
-
} finally {
|
|
180
|
-
setLoading(false);
|
|
181
|
-
}
|
|
182
|
-
},
|
|
183
|
-
[page, limit, extraParamsKey]
|
|
89
|
+
const offset = useMemo(() => (page - 1) * limit, [page, limit]);
|
|
90
|
+
const totalPages = useMemo(
|
|
91
|
+
() => Math.max(1, Math.ceil(total / limit)),
|
|
92
|
+
[total, limit]
|
|
184
93
|
);
|
|
185
|
-
|
|
186
|
-
// Fetch on mount and when dependencies change
|
|
187
|
-
useEffect(() => {
|
|
188
|
-
if (fetchOnMount || page !== defaultPage || limit !== defaultLimit) {
|
|
189
|
-
void fetchData(true);
|
|
190
|
-
}
|
|
191
|
-
}, [fetchData, fetchOnMount, page, limit, defaultPage, defaultLimit]);
|
|
192
|
-
|
|
193
|
-
// Reset to page 1 when extraParams change
|
|
194
|
-
useEffect(() => {
|
|
195
|
-
setPageState(1);
|
|
196
|
-
}, [extraParamsKey]);
|
|
197
|
-
|
|
198
|
-
const totalPages = Math.max(1, Math.ceil(total / limit));
|
|
199
94
|
const hasNext = page < totalPages;
|
|
200
95
|
const hasPrev = page > 1;
|
|
201
96
|
|
|
@@ -208,6 +103,10 @@ export function usePagination<TResponse, TItem, TExtraParams = object>({
|
|
|
208
103
|
setPageState(1); // Reset to first page when limit changes
|
|
209
104
|
}, []);
|
|
210
105
|
|
|
106
|
+
const setTotal = useCallback((newTotal: number) => {
|
|
107
|
+
setTotalState(newTotal);
|
|
108
|
+
}, []);
|
|
109
|
+
|
|
211
110
|
const nextPage = useCallback(() => {
|
|
212
111
|
if (hasNext) {
|
|
213
112
|
setPageState((p) => p + 1);
|
|
@@ -220,28 +119,46 @@ export function usePagination<TResponse, TItem, TExtraParams = object>({
|
|
|
220
119
|
}
|
|
221
120
|
}, [hasPrev]);
|
|
222
121
|
|
|
223
|
-
|
|
224
|
-
void fetchData(true);
|
|
225
|
-
}, [fetchData]);
|
|
226
|
-
|
|
227
|
-
const silentRefetch = useCallback(() => {
|
|
228
|
-
void fetchData(false);
|
|
229
|
-
}, [fetchData]);
|
|
230
|
-
|
|
231
|
-
const pagination: PaginationState = {
|
|
122
|
+
return {
|
|
232
123
|
page,
|
|
233
124
|
limit,
|
|
125
|
+
offset,
|
|
234
126
|
total,
|
|
235
127
|
totalPages,
|
|
236
128
|
hasNext,
|
|
237
129
|
hasPrev,
|
|
238
130
|
setPage,
|
|
239
131
|
setLimit,
|
|
132
|
+
setTotal,
|
|
240
133
|
nextPage,
|
|
241
134
|
prevPage,
|
|
242
|
-
refetch,
|
|
243
|
-
silentRefetch,
|
|
244
135
|
};
|
|
136
|
+
}
|
|
245
137
|
|
|
246
|
-
|
|
138
|
+
/**
|
|
139
|
+
* Helper hook to sync query total with pagination state.
|
|
140
|
+
* Use this to automatically update pagination.total when query data changes.
|
|
141
|
+
*
|
|
142
|
+
* @example
|
|
143
|
+
* ```tsx
|
|
144
|
+
* const pagination = usePagination({ defaultLimit: 20 });
|
|
145
|
+
*
|
|
146
|
+
* const { data, isLoading } = notificationClient.getNotifications.useQuery({
|
|
147
|
+
* limit: pagination.limit,
|
|
148
|
+
* offset: pagination.offset,
|
|
149
|
+
* });
|
|
150
|
+
*
|
|
151
|
+
* // Auto-sync total from response
|
|
152
|
+
* usePaginationSync(pagination, data?.total);
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
155
|
+
export function usePaginationSync(
|
|
156
|
+
pagination: PaginationState,
|
|
157
|
+
total: number | undefined
|
|
158
|
+
): void {
|
|
159
|
+
useEffect(() => {
|
|
160
|
+
if (total !== undefined) {
|
|
161
|
+
pagination.setTotal(total);
|
|
162
|
+
}
|
|
163
|
+
}, [total, pagination]);
|
|
247
164
|
}
|
|
@@ -1,275 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect, mock } from "bun:test";
|
|
2
|
-
import { renderHook, act } from "@checkstack/test-utils-frontend";
|
|
3
|
-
import { usePagination } from "./usePagination";
|
|
4
|
-
|
|
5
|
-
describe("usePagination", () => {
|
|
6
|
-
// Create a deferred promise for controlled async testing
|
|
7
|
-
interface MockResponse {
|
|
8
|
-
items: { id: string; name: string }[];
|
|
9
|
-
total: number;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
const createControlledMock = () => {
|
|
13
|
-
let resolvePromise: ((value: MockResponse) => void) | null = null;
|
|
14
|
-
const mockFn = mock(
|
|
15
|
-
({
|
|
16
|
-
limit,
|
|
17
|
-
offset,
|
|
18
|
-
}: {
|
|
19
|
-
limit: number;
|
|
20
|
-
offset: number;
|
|
21
|
-
}): Promise<MockResponse> => {
|
|
22
|
-
return new Promise((resolve) => {
|
|
23
|
-
resolvePromise = resolve;
|
|
24
|
-
// Auto-resolve after a microtask to simulate instant response
|
|
25
|
-
queueMicrotask(() => {
|
|
26
|
-
resolve({
|
|
27
|
-
items: Array.from(
|
|
28
|
-
{ length: Math.min(limit, 100 - offset) },
|
|
29
|
-
(_, i) => ({
|
|
30
|
-
id: `item-${offset + i}`,
|
|
31
|
-
name: `Item ${offset + i}`,
|
|
32
|
-
})
|
|
33
|
-
),
|
|
34
|
-
total: 100,
|
|
35
|
-
});
|
|
36
|
-
});
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
);
|
|
40
|
-
return { mockFn, getResolver: () => resolvePromise };
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
// Simple sync mock for tests that don't need controlled timing
|
|
44
|
-
const createSyncMock = () =>
|
|
45
|
-
mock(({ limit, offset }: { limit: number; offset: number }) =>
|
|
46
|
-
Promise.resolve({
|
|
47
|
-
items: Array.from(
|
|
48
|
-
{ length: Math.min(limit, 100 - offset) },
|
|
49
|
-
(_, i) => ({
|
|
50
|
-
id: `item-${offset + i}`,
|
|
51
|
-
name: `Item ${offset + i}`,
|
|
52
|
-
})
|
|
53
|
-
),
|
|
54
|
-
total: 100,
|
|
55
|
-
})
|
|
56
|
-
);
|
|
57
|
-
|
|
58
|
-
it("should initialize with correct defaults", () => {
|
|
59
|
-
const mockFetchFn = createSyncMock();
|
|
60
|
-
|
|
61
|
-
const { result } = renderHook(() =>
|
|
62
|
-
usePagination({
|
|
63
|
-
fetchFn: mockFetchFn,
|
|
64
|
-
getItems: (r) => r.items,
|
|
65
|
-
getTotal: (r) => r.total,
|
|
66
|
-
fetchOnMount: false,
|
|
67
|
-
})
|
|
68
|
-
);
|
|
69
|
-
|
|
70
|
-
expect(result.current.loading).toBe(false);
|
|
71
|
-
expect(result.current.items).toEqual([]);
|
|
72
|
-
expect(result.current.pagination.page).toBe(1);
|
|
73
|
-
expect(result.current.pagination.limit).toBe(10);
|
|
74
|
-
expect(result.current.pagination.total).toBe(0);
|
|
75
|
-
expect(result.current.pagination.totalPages).toBe(1);
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
it("should not fetch on mount when fetchOnMount is false", () => {
|
|
79
|
-
const mockFetchFn = createSyncMock();
|
|
80
|
-
|
|
81
|
-
renderHook(() =>
|
|
82
|
-
usePagination({
|
|
83
|
-
fetchFn: mockFetchFn,
|
|
84
|
-
getItems: (r) => r.items,
|
|
85
|
-
getTotal: (r) => r.total,
|
|
86
|
-
fetchOnMount: false,
|
|
87
|
-
})
|
|
88
|
-
);
|
|
89
|
-
|
|
90
|
-
expect(mockFetchFn).not.toHaveBeenCalled();
|
|
91
|
-
});
|
|
92
|
-
|
|
93
|
-
it("should start loading immediately when fetchOnMount is true", () => {
|
|
94
|
-
const mockFetchFn = createSyncMock();
|
|
95
|
-
|
|
96
|
-
const { result } = renderHook(() =>
|
|
97
|
-
usePagination({
|
|
98
|
-
fetchFn: mockFetchFn,
|
|
99
|
-
getItems: (r) => r.items,
|
|
100
|
-
getTotal: (r) => r.total,
|
|
101
|
-
defaultLimit: 10,
|
|
102
|
-
})
|
|
103
|
-
);
|
|
104
|
-
|
|
105
|
-
// Should be loading immediately after render
|
|
106
|
-
expect(result.current.loading).toBe(true);
|
|
107
|
-
expect(mockFetchFn).toHaveBeenCalledWith({ limit: 10, offset: 0 });
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
it("should call fetch with correct params on mount", async () => {
|
|
111
|
-
const { mockFn } = createControlledMock();
|
|
112
|
-
|
|
113
|
-
renderHook(() =>
|
|
114
|
-
usePagination({
|
|
115
|
-
fetchFn: mockFn,
|
|
116
|
-
getItems: (r) => r.items,
|
|
117
|
-
getTotal: (r) => r.total,
|
|
118
|
-
defaultLimit: 20,
|
|
119
|
-
})
|
|
120
|
-
);
|
|
121
|
-
|
|
122
|
-
expect(mockFn).toHaveBeenCalledWith({ limit: 20, offset: 0 });
|
|
123
|
-
});
|
|
124
|
-
|
|
125
|
-
it("should pass extra params to fetch function", async () => {
|
|
126
|
-
const { mockFn } = createControlledMock();
|
|
127
|
-
|
|
128
|
-
renderHook(() =>
|
|
129
|
-
usePagination({
|
|
130
|
-
fetchFn: mockFn,
|
|
131
|
-
getItems: (r) => r.items,
|
|
132
|
-
getTotal: (r) => r.total,
|
|
133
|
-
defaultLimit: 10,
|
|
134
|
-
extraParams: { unreadOnly: true, category: "alerts" },
|
|
135
|
-
})
|
|
136
|
-
);
|
|
137
|
-
|
|
138
|
-
expect(mockFn).toHaveBeenCalledWith({
|
|
139
|
-
limit: 10,
|
|
140
|
-
offset: 0,
|
|
141
|
-
unreadOnly: true,
|
|
142
|
-
category: "alerts",
|
|
143
|
-
});
|
|
144
|
-
});
|
|
145
|
-
|
|
146
|
-
it("should update page when setPage is called", async () => {
|
|
147
|
-
const mockFetchFn = createSyncMock();
|
|
148
|
-
|
|
149
|
-
const { result } = renderHook(() =>
|
|
150
|
-
usePagination({
|
|
151
|
-
fetchFn: mockFetchFn,
|
|
152
|
-
getItems: (r) => r.items,
|
|
153
|
-
getTotal: (r) => r.total,
|
|
154
|
-
fetchOnMount: false,
|
|
155
|
-
})
|
|
156
|
-
);
|
|
157
|
-
|
|
158
|
-
act(() => {
|
|
159
|
-
result.current.pagination.setPage(5);
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
expect(result.current.pagination.page).toBe(5);
|
|
163
|
-
// Should trigger fetch with correct offset
|
|
164
|
-
expect(mockFetchFn).toHaveBeenCalledWith({ limit: 10, offset: 40 });
|
|
165
|
-
});
|
|
166
|
-
|
|
167
|
-
it("should update limit and reset to page 1 when setLimit is called", async () => {
|
|
168
|
-
const mockFetchFn = createSyncMock();
|
|
169
|
-
|
|
170
|
-
const { result } = renderHook(() =>
|
|
171
|
-
usePagination({
|
|
172
|
-
fetchFn: mockFetchFn,
|
|
173
|
-
getItems: (r) => r.items,
|
|
174
|
-
getTotal: (r) => r.total,
|
|
175
|
-
fetchOnMount: false,
|
|
176
|
-
})
|
|
177
|
-
);
|
|
178
|
-
|
|
179
|
-
// First go to page 3
|
|
180
|
-
act(() => {
|
|
181
|
-
result.current.pagination.setPage(3);
|
|
182
|
-
});
|
|
183
|
-
|
|
184
|
-
expect(result.current.pagination.page).toBe(3);
|
|
185
|
-
|
|
186
|
-
// Then change limit
|
|
187
|
-
act(() => {
|
|
188
|
-
result.current.pagination.setLimit(25);
|
|
189
|
-
});
|
|
190
|
-
|
|
191
|
-
// Should reset to page 1
|
|
192
|
-
expect(result.current.pagination.page).toBe(1);
|
|
193
|
-
expect(result.current.pagination.limit).toBe(25);
|
|
194
|
-
// Should fetch with new limit at offset 0
|
|
195
|
-
expect(mockFetchFn).toHaveBeenLastCalledWith({ limit: 25, offset: 0 });
|
|
196
|
-
});
|
|
197
|
-
|
|
198
|
-
it("should call nextPage correctly", async () => {
|
|
199
|
-
const mockFetchFn = createSyncMock();
|
|
200
|
-
|
|
201
|
-
const { result } = renderHook(() =>
|
|
202
|
-
usePagination({
|
|
203
|
-
fetchFn: mockFetchFn,
|
|
204
|
-
getItems: (r) => r.items,
|
|
205
|
-
getTotal: (r) => r.total,
|
|
206
|
-
fetchOnMount: false,
|
|
207
|
-
})
|
|
208
|
-
);
|
|
209
|
-
|
|
210
|
-
// First set page to 1 (which triggers fetch that sets total)
|
|
211
|
-
act(() => {
|
|
212
|
-
result.current.pagination.setPage(1);
|
|
213
|
-
});
|
|
214
|
-
|
|
215
|
-
// After fetch completes, hasNext should be calculated based on total
|
|
216
|
-
// Since our mock returns total: 100 and limit: 10, hasNext should be true
|
|
217
|
-
// We need to manually set up the condition where hasNext is true
|
|
218
|
-
// For now, test that nextPage at least calls the function - even if hasNext blocks it
|
|
219
|
-
const callsBefore = mockFetchFn.mock.calls.length;
|
|
220
|
-
|
|
221
|
-
act(() => {
|
|
222
|
-
result.current.pagination.nextPage();
|
|
223
|
-
});
|
|
224
|
-
|
|
225
|
-
// nextPage should attempt to increment page (if hasNext allows)
|
|
226
|
-
// The actual behavior depends on whether fetchData has completed
|
|
227
|
-
// Since we can't await async in happy-dom, just verify the method doesn't throw
|
|
228
|
-
expect(mockFetchFn.mock.calls.length).toBeGreaterThanOrEqual(callsBefore);
|
|
229
|
-
});
|
|
230
|
-
|
|
231
|
-
it("should call prevPage correctly", async () => {
|
|
232
|
-
const mockFetchFn = createSyncMock();
|
|
233
|
-
|
|
234
|
-
const { result } = renderHook(() =>
|
|
235
|
-
usePagination({
|
|
236
|
-
fetchFn: mockFetchFn,
|
|
237
|
-
getItems: (r) => r.items,
|
|
238
|
-
getTotal: (r) => r.total,
|
|
239
|
-
fetchOnMount: false,
|
|
240
|
-
})
|
|
241
|
-
);
|
|
242
|
-
|
|
243
|
-
// Go to page 3 first
|
|
244
|
-
act(() => {
|
|
245
|
-
result.current.pagination.setPage(3);
|
|
246
|
-
});
|
|
247
|
-
|
|
248
|
-
act(() => {
|
|
249
|
-
result.current.pagination.prevPage();
|
|
250
|
-
});
|
|
251
|
-
|
|
252
|
-
expect(result.current.pagination.page).toBe(2);
|
|
253
|
-
});
|
|
254
|
-
|
|
255
|
-
it("should trigger refetch when refetch is called", async () => {
|
|
256
|
-
const mockFetchFn = createSyncMock();
|
|
257
|
-
|
|
258
|
-
const { result } = renderHook(() =>
|
|
259
|
-
usePagination({
|
|
260
|
-
fetchFn: mockFetchFn,
|
|
261
|
-
getItems: (r) => r.items,
|
|
262
|
-
getTotal: (r) => r.total,
|
|
263
|
-
fetchOnMount: false,
|
|
264
|
-
})
|
|
265
|
-
);
|
|
266
|
-
|
|
267
|
-
const initialCallCount = mockFetchFn.mock.calls.length;
|
|
268
|
-
|
|
269
|
-
act(() => {
|
|
270
|
-
result.current.pagination.refetch();
|
|
271
|
-
});
|
|
272
|
-
|
|
273
|
-
expect(mockFetchFn.mock.calls.length).toBeGreaterThan(initialCallCount);
|
|
274
|
-
});
|
|
275
|
-
});
|