@eml-payments/ui-kit 1.7.8 → 1.7.9

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.
@@ -0,0 +1,479 @@
1
+ import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useCallback, useEffect, useMemo, useState } from 'react';
3
+ import { Table } from './Table';
4
+ import { SearchInput } from '../SearchInput';
5
+ import { useLocation } from 'react-router-dom';
6
+ const CurrentUrl = () => {
7
+ const location = useLocation();
8
+ return _jsxs("div", { children: ["Current URL: ", location.search] });
9
+ };
10
+ const data = Array.from({ length: 10 }).map((_, i) => ({
11
+ id: `user-${i + 1}`,
12
+ name: `User ${i + 1}`,
13
+ email: `user${i + 1}@example.com`,
14
+ role: i % 2 === 0 ? 'Admin' : 'User',
15
+ }));
16
+ const disabledIds = new Set(['user-1', 'user-2', 'user-3']);
17
+ const columns = [
18
+ {
19
+ accessorKey: 'id',
20
+ header: 'ID',
21
+ flex: 1,
22
+ },
23
+ {
24
+ accessorKey: 'name',
25
+ header: 'Name',
26
+ flex: 1,
27
+ },
28
+ {
29
+ accessorKey: 'email',
30
+ header: 'Email',
31
+ cell: ({ row }) => (_jsx("a", { href: `mailto:${row.original.email}`, className: "text-blue-600 underline", children: row.original.email })),
32
+ flex: 1,
33
+ },
34
+ {
35
+ accessorKey: 'role',
36
+ header: 'Role',
37
+ cell: ({ row }) => {
38
+ const role = row.original.role;
39
+ return _jsx("span", { className: role === 'Admin' ? 'text-red-500 font-bold' : '', children: role });
40
+ },
41
+ flex: 1,
42
+ },
43
+ ];
44
+ const meta = {
45
+ title: 'UIKit/Table',
46
+ component: Table,
47
+ tags: ['autodocs'],
48
+ render: () => _jsx(Table, { id: "example-table", data: data, columns: columns }),
49
+ };
50
+ export default meta;
51
+ export const Basic = {
52
+ render: () => _jsx(Table, { id: "example-table", data: data, columns: columns }),
53
+ };
54
+ export const NoRows = {
55
+ render: () => _jsx(Table, { id: "example-table", data: [], columns: columns }),
56
+ };
57
+ export const LoadingWithSkeleton = {
58
+ render: () => _jsx(Table, { id: "example-table", data: [], columns: columns, isLoading: true, showSkeletonRows: true, rowsPerPage: 5 }),
59
+ };
60
+ export const ClientPagination = {
61
+ render: () => _jsx(Table, { id: "example-table", data: data, columns: columns, paginationMode: "client", rowsPerPage: 5 }),
62
+ };
63
+ const fetchServerData = (pageIndex, pageSize, query) => {
64
+ return new Promise((resolve) => {
65
+ setTimeout(() => {
66
+ const start = pageIndex * pageSize;
67
+ const data = Array.from({ length: pageSize }).map((_, i) => {
68
+ const id = start + i + 1;
69
+ return {
70
+ id: `user-${id}`,
71
+ name: `User ${id}`,
72
+ email: `user${id}@example.com`,
73
+ role: id % 2 === 0 ? 'Admin' : 'User',
74
+ };
75
+ });
76
+ const filteredData = query
77
+ ? data.filter((row) => row.name.toLowerCase().includes(query.toLowerCase()))
78
+ : data;
79
+ resolve(filteredData);
80
+ }, 500);
81
+ });
82
+ };
83
+ export const ServerSidePagination = {
84
+ render: () => {
85
+ const [data, setData] = useState([]);
86
+ const [isLoading, setIsLoading] = useState(false);
87
+ const fetchData = useCallback(async (pageIndex, pageSize) => {
88
+ setIsLoading(true);
89
+ const results = await fetchServerData(pageIndex, pageSize);
90
+ setData(results);
91
+ setIsLoading(false);
92
+ }, []);
93
+ return (_jsx(Table, { id: "server-table", data: data, columns: columns, paginationMode: "server", totalServerRows: 100, onRefetch: fetchData, isLoading: isLoading }));
94
+ },
95
+ };
96
+ const handleSelectionChange = (selectedRowIds) => {
97
+ console.log('Selected Row IDs:', selectedRowIds);
98
+ // Update your state or perform actions based on selected rows
99
+ };
100
+ export const WithCheckboxSelection = {
101
+ render: () => (_jsx(Table, { id: "example-table", data: data, columns: columns, checkboxSelection: true, checkboxPosition: "start", paginationMode: "client", onSelectionChange: handleSelectionChange })),
102
+ };
103
+ export const WithDisabledSelection = {
104
+ render: () => (_jsx(Table, { id: "example-table", data: data, columns: columns, checkboxSelection: true, checkboxPosition: "start", enableRowSelection: (row) => row.original.role !== 'Admin' })),
105
+ };
106
+ export const WithSingleRowSelection = {
107
+ render: () => (_jsx(Table, { id: "example-table", data: data, columns: columns, checkboxSelection: true, isMultiRowSelection: false })),
108
+ };
109
+ export const WithDefaultRowsSelected = {
110
+ render: () => (_jsx(Table, { id: "example-table", data: data, columns: columns, checkboxSelection: true, selectedRowIds: ['user-1', 'user-3'] })),
111
+ };
112
+ export const FlexColumnWidths = {
113
+ render: () => {
114
+ const testColumns = [
115
+ { accessorKey: 'id', header: 'ID', flex: 1 },
116
+ { accessorKey: 'name', header: 'Name', flex: 2 },
117
+ { accessorKey: 'email', header: 'Email', flex: 3 },
118
+ { accessorKey: 'role', header: 'Role', flex: 1 },
119
+ ];
120
+ return (_jsx(Table, { id: "example-table", data: data, columns: testColumns, paginationMode: "client", checkboxSelection: false, rowsPerPage: 5 }));
121
+ },
122
+ };
123
+ export const WithControlledSorting = {
124
+ render: () => {
125
+ const [sorting, setSorting] = useState([{ id: 'name', desc: true }]);
126
+ return (_jsx(Table, { id: "example-table", data: data, columns: columns, checkboxSelection: true, paginationMode: "client", sorting: sorting, onSortingChange: setSorting, rowsPerPage: 5 }));
127
+ },
128
+ };
129
+ export const WithRowActionsDropdown = {
130
+ render: () => {
131
+ const getOptions = (user) => [
132
+ {
133
+ label: 'Edit',
134
+ onClick: () => alert(`Edit ${user.name}`),
135
+ },
136
+ {
137
+ label: 'Delete',
138
+ onClick: () => alert(`Delete ${user.name}`),
139
+ },
140
+ ];
141
+ return (_jsx(Table, { id: "example-table", data: data, columns: columns, tableActionsDropdown: {
142
+ getOptions,
143
+ structure: 'default',
144
+ menuAlignment: 'end',
145
+ } }));
146
+ },
147
+ };
148
+ export const WithPartiallyDisabledRowActionsDropdown = {
149
+ render: () => {
150
+ const getOptions = (user) => [
151
+ {
152
+ label: 'Edit',
153
+ onClick: () => alert(`Edit ${user.name}`),
154
+ },
155
+ {
156
+ label: 'Delete',
157
+ onClick: () => alert(`Delete ${user.name}`),
158
+ },
159
+ ];
160
+ return (_jsx(Table, { id: "example-table", data: data, columns: columns, tableActionsDropdown: {
161
+ getOptions,
162
+ structure: 'default',
163
+ menuAlignment: 'end',
164
+ isDisabled: (row) => disabledIds.has(row.id),
165
+ } }));
166
+ },
167
+ };
168
+ export const WithDisabledRowActionsDropdownItem = {
169
+ render: () => {
170
+ const getOptions = (user) => [
171
+ {
172
+ label: 'Edit',
173
+ onClick: () => alert(`Edit ${user.name}`),
174
+ },
175
+ {
176
+ label: 'Delete',
177
+ onClick: () => alert(`Delete ${user.name}`),
178
+ disabled: user.role === 'Admin',
179
+ },
180
+ ];
181
+ return (_jsx(Table, { id: "example-table", data: data, columns: columns, tableActionsDropdown: {
182
+ getOptions,
183
+ structure: 'default',
184
+ menuAlignment: 'end',
185
+ } }));
186
+ },
187
+ };
188
+ export const WithRowClickHandler = {
189
+ render: () => {
190
+ return (_jsx(Table, { id: "clickable-rows-table", data: data, columns: columns, isRowClickable: (row) => row.role !== 'Admin', onRowClick: (row) => {
191
+ console.log('Row clicked:', row);
192
+ alert(`Clicked on ${row.name}`);
193
+ } }));
194
+ },
195
+ };
196
+ export const WithHiddenHeader = {
197
+ render: () => _jsx(Table, { id: "header-hidden-table", data: data, columns: columns, showHeader: false }),
198
+ };
199
+ const dates = [
200
+ new Date().toISOString(),
201
+ new Date(Date.now() + 86400000).toISOString(),
202
+ new Date(Date.now() + 2 * 86400000).toISOString(),
203
+ ];
204
+ const groupingData = Array.from({ length: 5 }).map((_, i) => ({
205
+ id: `user-${i + 1}`,
206
+ date: dates[i % dates.length],
207
+ name: `User ${i + 1}`,
208
+ amount: Math.floor(Math.random() * 1000) + 100,
209
+ }));
210
+ const groupingColumns = [
211
+ {
212
+ accessorKey: 'name',
213
+ header: 'Name',
214
+ flex: 1,
215
+ },
216
+ {
217
+ accessorKey: 'amount',
218
+ header: 'Amount',
219
+ cell: ({ row }) => (_jsxs("span", { style: { textAlign: 'right', display: 'block' }, children: ["$", row.original.amount.toFixed(2)] })),
220
+ flex: 1,
221
+ },
222
+ {
223
+ accessorKey: 'date',
224
+ header: 'Last Updated',
225
+ flex: 1,
226
+ enableGrouping: true,
227
+ getGroupingValue: (row) => new Date(row.date).toLocaleDateString('en-GB'),
228
+ meta: {
229
+ bgColor: '#f5f5f5',
230
+ },
231
+ },
232
+ ];
233
+ export const GroupedByDate = {
234
+ render: () => (_jsx(Table, { id: "header-hidden-table", data: groupingData, columns: groupingColumns, showHeader: false, grouping: ['date'] })),
235
+ };
236
+ function useSearch(data, selector, minChars = 3) {
237
+ const [query, setQuery] = useState('');
238
+ const isSearchActive = query.trim().length >= minChars;
239
+ const filteredData = useMemo(() => {
240
+ if (!isSearchActive)
241
+ return data;
242
+ const lowerQuery = query.toLowerCase();
243
+ return data.filter((item) => selector(item).toLowerCase().includes(lowerQuery));
244
+ }, [query, isSearchActive, data, selector]);
245
+ return { query, setQuery, filteredData, isSearchActive };
246
+ }
247
+ export const WithSearch = {
248
+ render: () => {
249
+ const { setQuery, filteredData, isSearchActive } = useSearch(data, (user) => user.name);
250
+ return (_jsxs("div", { className: "space-y-4", children: [_jsx("div", { style: { width: '300px' }, children: _jsx(SearchInput, { onSearch: (q) => setQuery(q), onClear: () => setQuery(''), placeholder: "Search by name..." }) }), _jsx(Table, { id: "search-table", data: filteredData, columns: columns, isSearchActive: isSearchActive })] }));
251
+ },
252
+ };
253
+ export const ServerSideSearch = {
254
+ render: () => {
255
+ const [data, setData] = useState([]);
256
+ const [isLoading, setIsLoading] = useState(false);
257
+ const [query, setQuery] = useState('');
258
+ const fetchData = useCallback(async (pageIndex, pageSize) => {
259
+ setIsLoading(true);
260
+ const results = await fetchServerData(pageIndex, pageSize, query);
261
+ setData(results);
262
+ setIsLoading(false);
263
+ }, [query]);
264
+ useEffect(() => {
265
+ fetchData(0, 10);
266
+ }, [fetchData]);
267
+ return (_jsxs("div", { className: "space-y-4", children: [_jsx("div", { style: { width: '300px' }, children: _jsx(SearchInput, { onSearch: (q) => setQuery(q), onClear: () => setQuery(''), placeholder: "Search users..." }) }), _jsx(Table, { id: "server-search-table", data: data, columns: columns, paginationMode: "server", totalServerRows: 100, onRefetch: fetchData, isLoading: isLoading, isSearchActive: query.trim().length >= 3 })] }));
268
+ },
269
+ };
270
+ // Note: Does not update state search params
271
+ export const ClientPaginationWithQueryParams = {
272
+ args: {
273
+ initialPageNo: 2,
274
+ initialPageSize: 5,
275
+ },
276
+ decorators: [
277
+ (Story, context) => {
278
+ const { initialPageNo, initialPageSize } = context.args;
279
+ const query = `?clients_pageNo=${initialPageNo}&clients_pageSize=${initialPageSize}`;
280
+ window.history.replaceState({}, '', query);
281
+ return _jsx(Story, {});
282
+ },
283
+ ],
284
+ render: () => (_jsxs(_Fragment, { children: [_jsx(CurrentUrl, {}), _jsx(Table, { id: "clients", data: data, columns: columns, paginationMode: "client", showHeader: true })] })),
285
+ };
286
+ // Note: Does not update state search params
287
+ export const ServerPaginationWithQueryParams = {
288
+ args: {
289
+ initialPageNo: 2,
290
+ initialPageSize: 5,
291
+ },
292
+ decorators: [
293
+ (Story, context) => {
294
+ const { initialPageNo, initialPageSize } = context.args;
295
+ const query = `?clients_pageNo=${initialPageNo}&clients_pageSize=${initialPageSize}`;
296
+ window.history.replaceState({}, '', query);
297
+ return _jsx(Story, {});
298
+ },
299
+ ],
300
+ render: () => {
301
+ const [data, setData] = useState([]);
302
+ const [isLoading, setIsLoading] = useState(false);
303
+ const fetchData = useCallback(async (pageIndex, pageSize) => {
304
+ setIsLoading(true);
305
+ const results = await fetchServerData(pageIndex, pageSize);
306
+ setData(results);
307
+ setIsLoading(false);
308
+ }, []);
309
+ return (_jsxs(_Fragment, { children: [_jsx(CurrentUrl, {}), _jsx(Table, { id: "clients", data: data, columns: columns, paginationMode: "server", totalServerRows: 100, onRefetch: fetchData, isLoading: isLoading, showHeader: true })] }));
310
+ },
311
+ };
312
+ // Note: Does not update state search params
313
+ export const TwoTablesWithQueryParams = {
314
+ args: {
315
+ clientsInitialPageNo: 2,
316
+ clientsInitialPageSize: 5,
317
+ usersInitialPageNo: 3,
318
+ usersInitialPageSize: 10,
319
+ },
320
+ decorators: [
321
+ (Story, context) => {
322
+ const { clientsInitialPageNo, clientsInitialPageSize, usersInitialPageNo, usersInitialPageSize } = context.args;
323
+ const query = `?clients_pageNo=${clientsInitialPageNo}&clients_pageSize=${clientsInitialPageSize}&users_pageNo=${usersInitialPageNo}&users_pageSize=${usersInitialPageSize}`;
324
+ window.history.replaceState({}, '', query);
325
+ return _jsx(Story, {});
326
+ },
327
+ ],
328
+ render: () => {
329
+ const [usersData, setUsersData] = useState([]);
330
+ const [isLoadingUsers, setIsLoadingUsers] = useState(false);
331
+ const fetchUsersData = useCallback(async (pageIndex, pageSize) => {
332
+ setIsLoadingUsers(true);
333
+ const results = await fetchServerData(pageIndex, pageSize);
334
+ setUsersData(results);
335
+ setIsLoadingUsers(false);
336
+ }, []);
337
+ return (_jsxs(_Fragment, { children: [_jsx(CurrentUrl, {}), _jsxs("div", { style: { display: 'flex', gap: '2rem' }, children: [_jsx(Table, { id: "clients", data: data, columns: columns, paginationMode: "client", showHeader: true }), _jsx(Table, { id: "users", data: usersData, columns: columns, paginationMode: "server", totalServerRows: 100, onRefetch: fetchUsersData, isLoading: isLoadingUsers, showHeader: true })] })] }));
338
+ },
339
+ };
340
+ function fetchInfiniteUsers(limit, offset = 0) {
341
+ const start = offset * limit;
342
+ const rows = Array.from({ length: limit }).map((_, i) => {
343
+ const idx = start + i + 1;
344
+ return {
345
+ id: `user-${idx}`,
346
+ name: `User ${idx}`,
347
+ email: `user${idx}@example.com`,
348
+ role: idx % 2 === 0 ? 'Admin' : 'User',
349
+ };
350
+ });
351
+ return new Promise((resolve) => {
352
+ setTimeout(() => {
353
+ const nextOffset = offset + 1;
354
+ const maxPages = Math.ceil(100 / limit);
355
+ const hasMore = nextOffset < maxPages;
356
+ resolve({ rows, nextOffset, hasMore });
357
+ }, 300);
358
+ });
359
+ }
360
+ export const InfiniteScrollVirtualized = {
361
+ name: 'Infinite Scroll — Virtualized',
362
+ render: () => {
363
+ const [rows, setRows] = useState([]);
364
+ const [nextOffset, setNextOffset] = useState(0);
365
+ const [hasNextPage, setHasNextPage] = useState(true);
366
+ const [isFetchingNextPage, setIsFetchingNextPage] = useState(false);
367
+ useEffect(() => {
368
+ (async () => {
369
+ setIsFetchingNextPage(true);
370
+ const res = await fetchInfiniteUsers(20, 0);
371
+ setRows(res.rows);
372
+ setNextOffset(res.nextOffset);
373
+ setHasNextPage(res.hasMore);
374
+ setIsFetchingNextPage(false);
375
+ })();
376
+ }, []);
377
+ const fetchNextPage = useCallback(async () => {
378
+ if (isFetchingNextPage || !hasNextPage)
379
+ return;
380
+ setIsFetchingNextPage(true);
381
+ const res = await fetchInfiniteUsers(20, nextOffset);
382
+ setRows((prev) => [...prev, ...res.rows]);
383
+ setNextOffset(res.nextOffset);
384
+ setHasNextPage(res.hasMore);
385
+ setIsFetchingNextPage(false);
386
+ }, [isFetchingNextPage, hasNextPage, nextOffset]);
387
+ return (_jsx("div", { children: _jsx(Table, { id: "infinite-virtualized", height: 500, data: rows, columns: columns, showHeader: true, infiniteScroll: {
388
+ enabled: true,
389
+ hasNextPage,
390
+ isFetchingNextPage,
391
+ fetchNextPage,
392
+ }, virtualization: {
393
+ enabled: true,
394
+ rowEstimate: 48,
395
+ overscan: 6,
396
+ } }) }));
397
+ },
398
+ };
399
+ export const InfiniteScrollNonVirtual = {
400
+ name: 'Infinite Scroll — Non-virtual',
401
+ render: () => {
402
+ const [rows, setRows] = useState([]);
403
+ const [nextOffset, setNextOffset] = useState(0);
404
+ const [hasNextPage, setHasNextPage] = useState(true);
405
+ const [isFetchingNextPage, setIsFetchingNextPage] = useState(false);
406
+ useEffect(() => {
407
+ (async () => {
408
+ setIsFetchingNextPage(true);
409
+ const res = await fetchInfiniteUsers(20, 0);
410
+ setRows(res.rows);
411
+ setNextOffset(res.nextOffset);
412
+ setHasNextPage(res.hasMore);
413
+ setIsFetchingNextPage(false);
414
+ })();
415
+ }, []);
416
+ const fetchNextPage = useCallback(async () => {
417
+ if (isFetchingNextPage || !hasNextPage)
418
+ return;
419
+ setIsFetchingNextPage(true);
420
+ const res = await fetchInfiniteUsers(20, nextOffset);
421
+ setRows((prev) => [...prev, ...res.rows]);
422
+ setNextOffset(res.nextOffset);
423
+ setHasNextPage(res.hasMore);
424
+ setIsFetchingNextPage(false);
425
+ }, [isFetchingNextPage, hasNextPage, nextOffset]);
426
+ return (_jsx("div", { children: _jsx(Table, { id: "infinite-nonvirtual", height: "80vh", data: rows, columns: columns, showHeader: true, infiniteScroll: {
427
+ enabled: true,
428
+ hasNextPage,
429
+ isFetchingNextPage,
430
+ fetchNextPage,
431
+ rootMarginPx: 300,
432
+ }, virtualization: {
433
+ enabled: false,
434
+ } }) }));
435
+ },
436
+ };
437
+ export const NoRowsInfiniteScrollNonVirtual = {
438
+ name: 'Empty State — Infinite Scroll (Non-virtual)',
439
+ render: () => {
440
+ const [rows] = useState([]);
441
+ const [hasNextPage] = useState(false);
442
+ const [isFetchingNextPage] = useState(false);
443
+ const fetchNextPage = useCallback(async () => {
444
+ // no-op: truly empty scenario
445
+ return;
446
+ }, []);
447
+ return (_jsx("div", { children: _jsx(Table, { id: "no-rows-infinite-nonvirtual", height: 500, data: rows, columns: columns, showHeader: true, isSearchActive: false, isLoading: false, noRowsMessage: "No rows to display", infiniteScroll: {
448
+ enabled: true,
449
+ hasNextPage,
450
+ isFetchingNextPage,
451
+ fetchNextPage,
452
+ rootMarginPx: 300,
453
+ }, virtualization: {
454
+ enabled: false,
455
+ } }) }));
456
+ },
457
+ };
458
+ export const NoRowsInfiniteScrollVirtualized = {
459
+ name: 'Empty State — Infinite Scroll (Virtualized)',
460
+ render: () => {
461
+ const [rows] = useState([]);
462
+ const [hasNextPage] = useState(false);
463
+ const [isFetchingNextPage] = useState(false);
464
+ const fetchNextPage = useCallback(async () => {
465
+ // no-op: truly empty scenario
466
+ return;
467
+ }, []);
468
+ return (_jsx("div", { children: _jsx(Table, { id: "no-rows-infinite-virtualized", height: 500, data: rows, columns: columns, showHeader: true, isSearchActive: false, isLoading: false, noRowsMessage: "No rows to display", infiniteScroll: {
469
+ enabled: true,
470
+ hasNextPage,
471
+ isFetchingNextPage,
472
+ fetchNextPage,
473
+ }, virtualization: {
474
+ enabled: true,
475
+ rowEstimate: 48,
476
+ overscan: 6,
477
+ } }) }));
478
+ },
479
+ };
@@ -0,0 +1,29 @@
1
+ import type { RefObject } from 'react';
2
+ import type { Virtualizer } from '@tanstack/react-virtual';
3
+ import type { InfiniteScrollOptions, VirtualizationOptions } from '../Table.types';
4
+ type PageEnvelope<T> = {
5
+ rows: T[];
6
+ };
7
+ export interface UseInfiniteScrollingParams<T extends {
8
+ id: string;
9
+ }> {
10
+ dataPages?: PageEnvelope<T>[] | undefined;
11
+ flatData?: T[] | undefined;
12
+ infiniteScroll?: InfiniteScrollOptions;
13
+ virtualization?: VirtualizationOptions;
14
+ parentScrollRef: RefObject<HTMLDivElement | null>;
15
+ loaderRef?: RefObject<HTMLElement | null>;
16
+ }
17
+ export interface UseInfiniteScrollingReturn<T extends {
18
+ id: string;
19
+ }> {
20
+ allRows: T[];
21
+ virtualizationEnabled: boolean;
22
+ rowVirtualizer?: Virtualizer<HTMLDivElement, Element>;
23
+ hasNextPage: boolean;
24
+ isFetchingNextPage: boolean;
25
+ }
26
+ export declare function useInfiniteScrolling<T extends {
27
+ id: string;
28
+ }>(params: UseInfiniteScrollingParams<T>): UseInfiniteScrollingReturn<T>;
29
+ export {};
@@ -0,0 +1,96 @@
1
+ import { useEffect, useMemo, useRef } from 'react';
2
+ import { useVirtualizer } from '@tanstack/react-virtual';
3
+ export function useInfiniteScrolling(params) {
4
+ var _a;
5
+ const { dataPages, flatData, infiniteScroll, virtualization, parentScrollRef, loaderRef } = params;
6
+ const isInfinite = !!(infiniteScroll === null || infiniteScroll === void 0 ? void 0 : infiniteScroll.enabled);
7
+ const hasNextPage = !!(infiniteScroll === null || infiniteScroll === void 0 ? void 0 : infiniteScroll.hasNextPage);
8
+ const isFetchingNextPage = !!(infiniteScroll === null || infiniteScroll === void 0 ? void 0 : infiniteScroll.isFetchingNextPage);
9
+ const fetchNextPage = infiniteScroll === null || infiniteScroll === void 0 ? void 0 : infiniteScroll.fetchNextPage;
10
+ const allRows = useMemo(() => {
11
+ if (isInfinite && Array.isArray(dataPages)) {
12
+ const byId = new Map();
13
+ for (const p of dataPages) {
14
+ for (const r of p.rows) {
15
+ byId.set(String(r.id), r);
16
+ }
17
+ }
18
+ return Array.from(byId.values());
19
+ }
20
+ return flatData !== null && flatData !== void 0 ? flatData : [];
21
+ }, [isInfinite, dataPages, flatData]);
22
+ const virtualizationEnabled = !!(virtualization === null || virtualization === void 0 ? void 0 : virtualization.enabled);
23
+ const rowVirtualizer = useVirtualizer({
24
+ count: allRows.length + (isInfinite && hasNextPage ? 1 : 0),
25
+ getScrollElement: () => parentScrollRef.current,
26
+ estimateSize: () => { var _a; return (_a = virtualization === null || virtualization === void 0 ? void 0 : virtualization.rowEstimate) !== null && _a !== void 0 ? _a : 48; },
27
+ overscan: (_a = virtualization === null || virtualization === void 0 ? void 0 : virtualization.overscan) !== null && _a !== void 0 ? _a : 6,
28
+ });
29
+ const loadLockRef = useRef(false);
30
+ const virtualItems = rowVirtualizer.getVirtualItems();
31
+ const lastVirtualIndex = virtualItems.length ? virtualItems[virtualItems.length - 1].index : -1;
32
+ const loaderIndex = allRows.length;
33
+ useEffect(() => {
34
+ if (!virtualizationEnabled || !isInfinite)
35
+ return;
36
+ if (!fetchNextPage || !hasNextPage || isFetchingNextPage)
37
+ return;
38
+ if (allRows.length === 0)
39
+ return;
40
+ if (lastVirtualIndex < loaderIndex || loadLockRef.current)
41
+ return;
42
+ loadLockRef.current = true;
43
+ Promise.resolve(fetchNextPage()).finally(() => {
44
+ loadLockRef.current = false;
45
+ });
46
+ }, [
47
+ virtualizationEnabled,
48
+ isInfinite,
49
+ hasNextPage,
50
+ isFetchingNextPage,
51
+ fetchNextPage,
52
+ lastVirtualIndex,
53
+ loaderIndex,
54
+ allRows.length,
55
+ ]);
56
+ useEffect(() => {
57
+ var _a, _b;
58
+ if (!isInfinite || virtualizationEnabled)
59
+ return;
60
+ if (!(loaderRef === null || loaderRef === void 0 ? void 0 : loaderRef.current) || !fetchNextPage)
61
+ return;
62
+ const rootMargin = `${(_a = infiniteScroll === null || infiniteScroll === void 0 ? void 0 : infiniteScroll.rootMarginPx) !== null && _a !== void 0 ? _a : 300}px`;
63
+ const observer = new IntersectionObserver((entries) => {
64
+ const entry = entries[0];
65
+ if (entry.isIntersecting && hasNextPage && !isFetchingNextPage) {
66
+ fetchNextPage();
67
+ }
68
+ }, {
69
+ root: (_b = parentScrollRef.current) !== null && _b !== void 0 ? _b : null,
70
+ rootMargin: `0px 0px ${rootMargin} 0px`,
71
+ threshold: 0.01,
72
+ });
73
+ const el = loaderRef.current;
74
+ observer.observe(el);
75
+ return () => {
76
+ observer.unobserve(el);
77
+ observer.disconnect();
78
+ };
79
+ }, [
80
+ isInfinite,
81
+ virtualizationEnabled,
82
+ hasNextPage,
83
+ isFetchingNextPage,
84
+ fetchNextPage,
85
+ infiniteScroll === null || infiniteScroll === void 0 ? void 0 : infiniteScroll.rootMarginPx,
86
+ parentScrollRef,
87
+ loaderRef,
88
+ ]);
89
+ return {
90
+ allRows,
91
+ virtualizationEnabled,
92
+ rowVirtualizer,
93
+ hasNextPage,
94
+ isFetchingNextPage,
95
+ };
96
+ }
@@ -0,0 +1,16 @@
1
+ import type { Table } from '@tanstack/react-table';
2
+ import { PaginationMode } from '../Table.types';
3
+ interface UsePaginationControllerOptions<T> {
4
+ table: Table<T>;
5
+ paginationMode: PaginationMode;
6
+ onRefetch?: (pageIndex: number, pageSize: number) => void;
7
+ }
8
+ export declare function usePaginationController<T>({ table, paginationMode, onRefetch }: UsePaginationControllerOptions<T>): {
9
+ pageIndex: number;
10
+ pageSize: number;
11
+ canNextPage: boolean;
12
+ canPrevPage: boolean;
13
+ onNextPage: () => void;
14
+ onPrevPage: () => void;
15
+ };
16
+ export {};
@@ -0,0 +1,30 @@
1
+ import { useCallback, useEffect, useMemo } from 'react';
2
+ export function usePaginationController({ table, paginationMode, onRefetch }) {
3
+ const { pageIndex, pageSize } = table.getState().pagination;
4
+ const canNextPage = table.getCanNextPage();
5
+ const canPrevPage = table.getCanPreviousPage();
6
+ const onNextPage = useCallback(() => {
7
+ if (canNextPage) {
8
+ table.nextPage();
9
+ }
10
+ }, [canNextPage, table]);
11
+ const onPrevPage = useCallback(() => {
12
+ if (canPrevPage) {
13
+ table.previousPage();
14
+ }
15
+ }, [canPrevPage, table]);
16
+ // Only refetch in server mode
17
+ useEffect(() => {
18
+ if (paginationMode === 'server' && onRefetch) {
19
+ onRefetch(pageIndex, pageSize);
20
+ }
21
+ }, [paginationMode, pageIndex, pageSize, onRefetch]);
22
+ return useMemo(() => ({
23
+ pageIndex,
24
+ pageSize,
25
+ canNextPage,
26
+ canPrevPage,
27
+ onNextPage,
28
+ onPrevPage,
29
+ }), [pageIndex, pageSize, canNextPage, canPrevPage, onNextPage, onPrevPage]);
30
+ }
@@ -0,0 +1,26 @@
1
+ import { type SortingState } from '@tanstack/react-table';
2
+ import type { TableProps } from '../Table.types';
3
+ export declare function useTableController<T extends {
4
+ id: string;
5
+ }>({ id, height, data, columns, checkboxSelection, checkboxPosition, paginationMode, sorting, onSortingChange, onSelectionChange, enableRowSelection, rowsPerPage, isMultiRowSelection, selectedRowIds, rowIdKey, totalServerRows, onRefetch, showHeader, grouping, infiniteScroll, virtualization, }: TableProps<T>): {
6
+ pageIndex: number;
7
+ pageSize: number;
8
+ canNextPage: boolean;
9
+ canPrevPage: boolean;
10
+ onNextPage: () => void;
11
+ onPrevPage: () => void;
12
+ table: import("@tanstack/table-core").Table<T>;
13
+ height: string | number | undefined;
14
+ showHeader: boolean;
15
+ grouping: string[] | undefined;
16
+ setPageSize: import("react").Dispatch<import("react").SetStateAction<number>>;
17
+ setPageIndex: import("react").Dispatch<import("react").SetStateAction<number>>;
18
+ sorting: SortingState;
19
+ virtualizationEnabled: boolean;
20
+ rowVirtualizer: import("@tanstack/virtual-core").Virtualizer<HTMLDivElement, Element> | undefined;
21
+ hasNextPage: boolean;
22
+ parentScrollRef: import("react").MutableRefObject<HTMLDivElement | null>;
23
+ loaderRef: import("react").MutableRefObject<HTMLTableRowElement | null>;
24
+ infiniteScroll: import("..").InfiniteScrollOptions | undefined;
25
+ virtualization: import("..").VirtualizationOptions | undefined;
26
+ };