next-data-kit 9.9.2 → 10.0.0

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.
Files changed (106) hide show
  1. package/MIGRATION.md +43 -0
  2. package/README.md +107 -782
  3. package/dist/index.d.ts +79 -111
  4. package/dist/index.js +98 -205
  5. package/dist/index.js.map +1 -1
  6. package/dist/server.d.ts +121 -89
  7. package/dist/server.js +96 -285
  8. package/dist/server.js.map +1 -1
  9. package/package.json +50 -104
  10. package/registry/r/data-kit.json +58 -0
  11. package/registry/r/registry.json +23 -0
  12. package/dist/action-DCmAhOQa.d.cts +0 -196
  13. package/dist/action-DCmAhOQa.d.ts +0 -196
  14. package/dist/chunk-5TIEIY7M.cjs +0 -393
  15. package/dist/chunk-5TIEIY7M.cjs.map +0 -1
  16. package/dist/chunk-MTJATM72.cjs +0 -2423
  17. package/dist/chunk-MTJATM72.cjs.map +0 -1
  18. package/dist/chunk-O377UO7C.js +0 -2379
  19. package/dist/chunk-O377UO7C.js.map +0 -1
  20. package/dist/chunk-VFSNUXOW.js +0 -382
  21. package/dist/chunk-VFSNUXOW.js.map +0 -1
  22. package/dist/client/components/data-kit-infinity.d.ts +0 -23
  23. package/dist/client/components/data-kit-infinity.d.ts.map +0 -1
  24. package/dist/client/components/data-kit-table.d.ts +0 -34
  25. package/dist/client/components/data-kit-table.d.ts.map +0 -1
  26. package/dist/client/components/data-kit.d.ts +0 -25
  27. package/dist/client/components/data-kit.d.ts.map +0 -1
  28. package/dist/client/components/index.d.ts +0 -4
  29. package/dist/client/components/index.d.ts.map +0 -1
  30. package/dist/client/components/ui/button.d.ts +0 -14
  31. package/dist/client/components/ui/button.d.ts.map +0 -1
  32. package/dist/client/components/ui/checkbox.d.ts +0 -5
  33. package/dist/client/components/ui/checkbox.d.ts.map +0 -1
  34. package/dist/client/components/ui/dropdown-menu.d.ts +0 -28
  35. package/dist/client/components/ui/dropdown-menu.d.ts.map +0 -1
  36. package/dist/client/components/ui/index.d.ts +0 -8
  37. package/dist/client/components/ui/index.d.ts.map +0 -1
  38. package/dist/client/components/ui/pagination.d.ts +0 -14
  39. package/dist/client/components/ui/pagination.d.ts.map +0 -1
  40. package/dist/client/components/ui/popover.d.ts +0 -10
  41. package/dist/client/components/ui/popover.d.ts.map +0 -1
  42. package/dist/client/components/ui/select.d.ts +0 -18
  43. package/dist/client/components/ui/select.d.ts.map +0 -1
  44. package/dist/client/components/ui/table.d.ts +0 -11
  45. package/dist/client/components/ui/table.d.ts.map +0 -1
  46. package/dist/client/context/index.d.ts +0 -22
  47. package/dist/client/context/index.d.ts.map +0 -1
  48. package/dist/client/hooks/index.d.ts +0 -7
  49. package/dist/client/hooks/index.d.ts.map +0 -1
  50. package/dist/client/hooks/useDataKit.d.ts +0 -9
  51. package/dist/client/hooks/useDataKit.d.ts.map +0 -1
  52. package/dist/client/hooks/usePagination.d.ts +0 -18
  53. package/dist/client/hooks/usePagination.d.ts.map +0 -1
  54. package/dist/client/hooks/useSelection.d.ts +0 -13
  55. package/dist/client/hooks/useSelection.d.ts.map +0 -1
  56. package/dist/client/index.d.ts +0 -11
  57. package/dist/client/index.d.ts.map +0 -1
  58. package/dist/client/utils/cn.d.ts +0 -10
  59. package/dist/client/utils/cn.d.ts.map +0 -1
  60. package/dist/client/utils/index.d.ts +0 -60
  61. package/dist/client/utils/index.d.ts.map +0 -1
  62. package/dist/client.cjs +0 -85
  63. package/dist/client.cjs.map +0 -1
  64. package/dist/client.d.cts +0 -62
  65. package/dist/client.d.ts +0 -7
  66. package/dist/client.d.ts.map +0 -1
  67. package/dist/client.js +0 -4
  68. package/dist/client.js.map +0 -1
  69. package/dist/index-DUVfK8q6.d.ts +0 -284
  70. package/dist/index-qXbjvUTB.d.cts +0 -284
  71. package/dist/index.cjs +0 -300
  72. package/dist/index.cjs.map +0 -1
  73. package/dist/index.d.cts +0 -117
  74. package/dist/internal/hooks.cjs +0 -12
  75. package/dist/internal/hooks.cjs.map +0 -1
  76. package/dist/internal/hooks.d.cts +0 -1
  77. package/dist/internal/hooks.d.ts +0 -1
  78. package/dist/internal/hooks.js +0 -3
  79. package/dist/internal/hooks.js.map +0 -1
  80. package/dist/server/utils.d.ts +0 -52
  81. package/dist/server/utils.d.ts.map +0 -1
  82. package/dist/server.cjs +0 -315
  83. package/dist/server.cjs.map +0 -1
  84. package/dist/server.d.cts +0 -99
  85. package/dist/styles.css +0 -2
  86. package/dist/types/client/component.d.ts +0 -129
  87. package/dist/types/client/component.d.ts.map +0 -1
  88. package/dist/types/client/hook.d.ts +0 -116
  89. package/dist/types/client/hook.d.ts.map +0 -1
  90. package/dist/types/client/selectable.d.ts +0 -43
  91. package/dist/types/client/selectable.d.ts.map +0 -1
  92. package/dist/types/index.cjs +0 -4
  93. package/dist/types/index.cjs.map +0 -1
  94. package/dist/types/index.d.cts +0 -291
  95. package/dist/types/index.d.ts +0 -12
  96. package/dist/types/index.d.ts.map +0 -1
  97. package/dist/types/index.js +0 -3
  98. package/dist/types/index.js.map +0 -1
  99. package/dist/types/next-data-kit.d.ts +0 -95
  100. package/dist/types/next-data-kit.d.ts.map +0 -1
  101. package/dist/types/server/action.d.ts +0 -44
  102. package/dist/types/server/action.d.ts.map +0 -1
  103. package/dist/types/server/database/mongo.d.ts +0 -56
  104. package/dist/types/server/database/mongo.d.ts.map +0 -1
  105. package/dist/useDataKit-XFp3_mUc.d.cts +0 -276
  106. package/dist/useDataKit-XFp3_mUc.d.ts +0 -276
package/README.md CHANGED
@@ -1,843 +1,168 @@
1
1
  # next-data-kit
2
2
 
3
- A powerful table utility for server-side pagination, filtering, and sorting with React hooks and components.
3
+ Server-first pagination, filtering and sorting for React tables. You declare a table once on the server, read its state from the URL, and render it with components that live in your own codebase and use your own shadcn theme.
4
4
 
5
- ## Features
5
+ - **Secure by default**: only the filters and sort fields you declare exist. The browser never names a database field.
6
+ - **Server-rendered**: the first page arrives in the HTML; paging, sorting and filtering change the URL, and back, forward and reload just work.
7
+ - **Yours to change**: the UI is a shadcn registry item copied into your project, built on your `table`, `select`, `button` and so on, so it follows your theme and dark mode.
8
+ - **Small**: no runtime dependencies. React, zod and mongoose are the ones your app already has.
6
9
 
7
- - 🚀 **Server-side pagination** - Efficient data fetching with page-based navigation
8
- - 🔍 **Flexible filtering** - Support for regex, exact match, and custom filters
9
- - 📊 **Multi-column sorting** - Sort by multiple columns with customizable order
10
- - ♾️ **Infinite scroll** - DataKitInfinity component with pull-to-refresh support
11
- - ⚛️ **React hooks** - `useDataKit`, `useSelection`, `usePagination` for state management
12
- - 🎨 **Components** - `DataKitTable` for tables, `DataKit` for custom layouts, `DataKitInfinity` for feeds
13
- - 📝 **TypeScript** - Fully typed with generics support
14
- - 🔌 **Framework agnostic** - Works with any database ORM/ODM (Mongoose, Prisma, etc.)
15
- - 📦 **Tree-shakeable** - Import only what you need
10
+ ## How it fits together
16
11
 
17
- ## Installation
12
+ | Layer | Import | What it does |
13
+ |---|---|---|
14
+ | Definition | `next-data-kit/server` | `dataKitDefine` declares the adapter, filters, sorts and page size, then parses the URL and runs the query. |
15
+ | Hook | `next-data-kit` | `useDataKit` holds page, sort, filter, selection and local item edits. |
16
+ | UI | `npx shadcn add @ndk/data-kit` | `DataKitRoot`, `DataKitTable`, `DataKitFilter`, `DataKitPagination`, `DataKitSelection`, `DataKitInfinite`. |
17
+
18
+ ## Install
18
19
 
19
20
  ```bash
20
21
  npm install next-data-kit
21
- # or
22
- yarn add next-data-kit
23
- # or
24
- pnpm add next-data-kit
25
- ```
26
-
27
- ## Quick Start
28
-
29
- ### Server-side (Next.js Server Action)
30
-
31
- ```typescript
32
- 'use server';
33
-
34
- import { dataKitServerAction, createSearchFilter } from 'next-data-kit/server';
35
- import type { TDataKitInput } from 'next-data-kit/types';
36
- import UserModel from '@/models/User';
37
-
38
- export async function fetchUsers(input: TDataKitInput) {
39
- return dataKitServerAction({
40
- model: UserModel,
41
- input,
42
- item: async user => ({
43
- id: user._id.toString(),
44
- name: user.name,
45
- email: user.email,
46
- }),
47
- filterCustom: {
48
- search: createSearchFilter(['name', 'email']),
49
- age: value => ({ age: { $gte: value } }),
50
- },
51
- });
52
- }
53
- ```
54
-
55
- ### Input Validation (Optional)
56
-
57
- You can use the built-in Zod schema to validate inputs before processing:
58
-
59
- ```typescript
60
- 'use server';
61
-
62
- ## Styling
63
- Next Data Kit ships with its own Tailwind CSS styles which are **automatically injected** into your application. You do not need to import any CSS files manually.
64
-
65
- ### Prefixing
66
- To prevent class name conflicts with your application, all Next Data Kit utility classes are prefixed with `ndk:`. For example, instead of `flex`, components use `ndk:flex`.
67
-
68
- If you need to override styles or use Data Kit's class names in your own custom components that interact with the library's internal state, remember to use the `ndk:` prefix.
69
-
70
- ### Tailwind Configuration (Optional)
71
- Since styles are injected, you generally don't need to configure your Tailwind setup to be aware of Next Data Kit unless you are building custom components that rely on the library's internal theme variables.
72
- import { dataKitServerAction, dataKitSchemaZod } from 'next-data-kit/server';
73
-
74
- export async function fetchUsers(input: unknown) {
75
- const parsedInput = dataKitSchemaZod.parse(input);
76
-
77
- return dataKitServerAction({
78
- model: UserModel,
79
- input: parsedInput,
80
- item: user => ({ id: user._id.toString(), name: user.name }),
81
- filterCustom: {
82
- search: value => ({ name: { $regex: value, $options: 'i' } }),
83
- role: value => ({ role: value }),
84
- },
85
- });
86
- }
87
- ```
88
-
89
- ### Client-side (DataKitTable Component)
90
-
91
- Ready-to-use table with built-in filtering, sorting, and selection:
92
-
93
- ```tsx
94
- 'use client';
95
-
96
- import { DataKitTable } from 'next-data-kit/client';
97
- import { fetchUsers } from '@/actions/users';
98
-
99
- export function UsersTable() {
100
- return (
101
- <DataKitTable
102
- action={fetchUsers}
103
- limit={{ default: 10 }}
104
- filters={[
105
- { id: 'search', label: 'Search', type: 'TEXT', placeholder: 'Search...' },
106
- {
107
- id: 'role',
108
- label: 'Role',
109
- type: 'SELECT',
110
- dataset: [
111
- { id: 'admin', name: 'admin', label: 'Admin' },
112
- { id: 'user', name: 'user', label: 'User' },
113
- ],
114
- },
115
- ]}
116
- selectable={{
117
- enabled: true,
118
- actions: {
119
- export: {
120
- name: 'Export',
121
- icon: <Download className="mr-2 size-4" />,
122
- function: async items => [true, {}],
123
- },
124
- sep1: { type: 'SEPARATOR' },
125
- delete: {
126
- name: 'Delete Selected',
127
- icon: <Trash className="mr-2 size-4" />,
128
- function: async items => {
129
- await deleteUsers(items.map(i => i.id));
130
- return [true, { deselectAll: true }];
131
- },
132
- },
133
- },
134
- }}
135
- table={[
136
- {
137
- head: <DataKitTable.Head>Name</DataKitTable.Head>,
138
- body: ({ item }) => <DataKitTable.Cell>{item.name}</DataKitTable.Cell>,
139
- sortable: { path: 'name', default: 0 },
140
- },
141
- {
142
- head: <DataKitTable.Head>Email</DataKitTable.Head>,
143
- body: ({ item }) => <DataKitTable.Cell>{item.email}</DataKitTable.Cell>,
144
- },
145
- ]}
146
- sorts={[
147
- { path: '_id', value: -1 }, // Default sort by ID descending (consistent ordering)
148
- ]}
149
- />
150
- );
151
- }
152
- ```
153
-
154
- #### Row State Management
155
-
156
- Use `state` and `setState` for per-row state (e.g., expanded rows, inline editing, loading states).
157
-
158
- > [!NOTE]
159
- > Each row has its own independent state instance. The `state` prop defines the initial value, but each row maintains its own copy. Changing one row's state does not affect other rows.
160
-
161
- ```tsx
162
- 'use client';
163
-
164
- import { DataKitTable } from 'next-data-kit/client';
165
- import { fetchUsers } from '@/actions/users';
166
-
167
- export function UsersTable() {
168
- return (
169
- <DataKitTable
170
- action={fetchUsers}
171
- state={{ isExpanded: false, isEditing: false }}
172
- table={[
173
- {
174
- head: <DataKitTable.Head>Name</DataKitTable.Head>,
175
- body: ({ item, state, setState }) => (
176
- <DataKitTable.Cell>
177
- <div>{state.isEditing ? <input defaultValue={item.name} onBlur={() => setState(s => ({ ...s, isEditing: false }))} /> : <span onClick={() => setState(s => ({ ...s, isEditing: true }))}>{item.name}</span>}</div>
178
- </DataKitTable.Cell>
179
- ),
180
- },
181
- {
182
- head: <DataKitTable.Head>Actions</DataKitTable.Head>,
183
- body: ({ item, state, setState }) => (
184
- <DataKitTable.Cell>
185
- <button onClick={() => setState(s => ({ ...s, isExpanded: !s.isExpanded }))}>{state.isExpanded ? 'Collapse' : 'Expand'}</button>
186
- {state.isExpanded && <div className='mt-2 text-sm'>Details: {item.email}</div>}
187
- </DataKitTable.Cell>
188
- ),
189
- },
190
- ]}
191
- />
192
- );
193
- }
194
- ```
195
-
196
- #### Pagination Modes
197
-
198
- Both `DataKit` and `DataKitTable` support two pagination modes:
199
-
200
- ```tsx
201
- // NUMBER (default) - Full numbered pagination with mobile responsiveness
202
- <DataKitTable
203
- action={fetchUsers}
204
- pagination="NUMBER" // Default - shows page numbers
205
- table={columns}
206
- />
207
-
208
- // SIMPLE - Basic prev/next buttons only
209
- <DataKitTable
210
- action={fetchUsers}
211
- pagination="SIMPLE"
212
- table={columns}
213
- />
214
- ```
215
-
216
- **NUMBER mode features:**
217
-
218
- - Desktop: Shows Previous, page numbers (1, 2, ... 10), Next
219
- - Mobile: Shows prev icon, current page number, next icon
220
- - Automatically adds ellipsis for skipped pages
221
- - Fully responsive with Tailwind CSS
222
-
223
- #### Sorting
224
-
225
- DataKitTable supports two types of sorting:
226
-
227
- **1. Column-based sorting** - Interactive sorting via column headers:
228
-
229
- ```tsx
230
- table={[
231
- {
232
- head: <DataKitTable.Head>Name</DataKitTable.Head>,
233
- body: ({ item }) => <DataKitTable.Cell>{item.name}</DataKitTable.Cell>,
234
- sortable: {
235
- path: 'name', // MongoDB field path
236
- default: 1 // 1 (asc), -1 (desc), or 0 (no default)
237
- }
238
- }
239
- ]}
240
- ```
241
-
242
- **2. Default sorts** - Hidden sorts for consistent ordering:
243
-
244
- ```tsx
245
- <DataKitTable
246
- action={fetchUsers}
247
- table={columns}
248
- sorts={[
249
- { path: '_id', value: -1 } // Sort by ID descending (tie-breaker)
250
- ]}
251
- />
252
22
  ```
253
23
 
254
- **Sort priority and ordering:**
24
+ Peers: `react` 19, `react-dom` 19, `zod` 4, and `mongoose` 8–9 if you use the Mongoose adapter.
255
25
 
256
- MongoDB processes sorts in order. Column sorts take priority over default sorts:
26
+ Add the registry to `components.json`, then add the components:
257
27
 
258
- ```tsx
259
- <DataKitTable
260
- table={[
261
- {
262
- head: <DataKitTable.Head>Priority</DataKitTable.Head>,
263
- body: ({ item }) => <DataKitTable.Cell>{item.priority}</DataKitTable.Cell>,
264
- sortable: { path: 'priority', default: -1 } // Sort #1: High priority first
265
- }
266
- ]}
267
- sorts={[
268
- { path: 'createdAt', value: -1 }, // Sort #2: Newest within same priority
269
- { path: '_id', value: -1 } // Sort #3: Consistent ordering
270
- ]}
271
- />
272
- // Result: sorts = [{ path: 'priority', value: -1 }, { path: 'createdAt', value: -1 }, { path: '_id', value: -1 }]
28
+ ```json
29
+ { "registries": { "@ndk": "https://unpkg.com/next-data-kit@10/registry/r/{name}.json" } }
273
30
  ```
274
31
 
275
- **Dynamic Limit Options:**
276
-
277
- When you set a custom limit, it's automatically added to the dropdown:
278
-
279
- ```tsx
280
- <DataKitTable
281
- action={fetchUsers}
282
- limit={{ default: 15 }} // 15 will appear in dropdown alongside 10, 25, 50, 100
283
- table={columns}
284
- />
285
-
286
- // Works with any custom value
287
- <DataKit
288
- action={fetchUsers}
289
- limit={{ default: 30 }} // Dropdown will show: 10, 25, 30, 50, 100
290
- >
291
- {dataKit => /* ... */}
292
- </DataKit>
32
+ ```bash
33
+ npx shadcn add @ndk/data-kit
293
34
  ```
294
35
 
295
- ### Client-side (DataKitInfinity Component - Infinite Scroll)
36
+ The files land in `components/ui/ndk/data-kit/`. If shadcn asks to overwrite a component you already have (`table`, `select`, …), answer **No** so your customizations stay.
296
37
 
297
- Use `DataKitInfinity` for infinite scrolling feeds, chat interfaces, or any content that loads more as you scroll. No pagination controls - content loads automatically.
38
+ ## 1. Declare the table (server)
298
39
 
299
- ```tsx
300
- 'use client';
40
+ ```ts
41
+ import { z } from 'zod';
42
+ import { adapterMongoose, dataKitDefine, filterSearch } from 'next-data-kit/server';
301
43
 
302
- import { DataKitInfinity } from 'next-data-kit/client';
303
- import { fetchMessages } from '@/actions/messages';
304
-
305
- export function MessagesFeed() {
306
- return (
307
- <DataKitInfinity action={fetchMessages} limit={{ default: 20 }} filters={[{ id: 'search', label: 'Search', type: 'TEXT' }]}>
308
- {dataKit => (
309
- <div className='space-y-4'>
310
- {dataKit.items.map(message => (
311
- <div key={message.id} className='rounded-lg border p-4'>
312
- <p className='font-medium'>{message.author}</p>
313
- <p>{message.content}</p>
314
- </div>
315
- ))}
316
- {!dataKit.state.hasNextPage && dataKit.items.length > 0 && <p className='text-center text-muted-foreground'>You're all set</p>}
317
- {dataKit.state.isLoading && <p className='text-center text-muted-foreground'>Loading...</p>}
318
- </div>
319
- )}
320
- </DataKitInfinity>
321
- );
322
- }
44
+ export const kitUser = dataKitDefine({
45
+ adapter: adapterMongoose({ model: ModelUser }),
46
+ // ** Optional: always applied, never read from the request
47
+ scope: (props: { context: { teamId: string } }) => ({ teamId: props.context.teamId }),
48
+ filter: {
49
+ search: filterSearch({ field: ['name', 'email'] }),
50
+ role: { schema: z.enum(['admin', 'user']), query: (props) => ({ role: props.value }) },
51
+ active: { schema: z.stringbool(), query: (props) => ({ active: props.value }) },
52
+ },
53
+ sort: { field: ['name', 'createdAt'], default: [{ field: 'createdAt', direction: 'desc' }] },
54
+ page: { size: { default: 20, max: 100 } },
55
+ item: (props) => ({ id: String(props.document._id), name: props.document.name, email: props.document.email }),
56
+ });
323
57
  ```
324
58
 
325
- ### Client-side (DataKit Component - Custom Layout)
59
+ - Each filter has a zod `schema`. URL values arrive as strings, so use coercing schemas (`z.coerce.number()`, `z.stringbool()`).
60
+ - A filter's `query` may be async, for example to look up ids in another collection first.
61
+ - `item` must return plain JSON with a string `id`. In development a warning is logged when it doesn't.
62
+ - An `_id` tie-break is added to every Mongoose sort, so ties stay in a stable order.
326
63
 
327
- Use `DataKit` for grids, cards, or any custom layout. It provides toolbar/pagination but lets you render content:
64
+ | Option | Default | Notes |
65
+ |---|---|---|
66
+ | `adapter` | required | `adapterMongoose({ model, hydrate? })`, `adapterMemory({ items })`, or your own function. |
67
+ | `scope` | none | Server-only query, from `context`. |
68
+ | `filter` | `{}` | Undeclared keys are dropped. |
69
+ | `sort.field` | `[]` | Allowed sort fields; anything else falls back to `sort.default`. |
70
+ | `page.size` | `20` / max `100` | Larger requests are capped at `max`. |
328
71
 
329
- ```tsx
330
- 'use client';
331
-
332
- import { DataKit } from 'next-data-kit/client';
333
- import { fetchUsers } from '@/actions/users';
334
-
335
- export function UsersGrid() {
336
- return (
337
- <DataKit action={fetchUsers} limit={{ default: 12 }} filters={[{ id: 'search', label: 'Search', type: 'TEXT' }]}>
338
- {dataKit => (
339
- <div className='grid grid-cols-4 gap-4'>
340
- {dataKit.items.map(user => (
341
- <div key={user.id} className='rounded-lg border p-4'>
342
- <h3>{user.name}</h3>
343
- <p>{user.email}</p>
344
- </div>
345
- ))}
346
- </div>
347
- )}
348
- </DataKit>
349
- );
350
- }
351
- ```
352
-
353
- **Manual mode** - handle loading/empty states yourself:
72
+ ## 2. Render the page (Next.js server component)
354
73
 
355
74
  ```tsx
356
- <DataKit action={fetchUsers} manual>
357
- {dataKit => (
358
- <>
359
- {dataKit.state.isLoading && <Spinner />}
360
- {dataKit.items.map(user => (
361
- <Card key={user.id} user={user} />
362
- ))}
363
- </>
364
- )}
365
- </DataKit>
75
+ const Page = async (props: { searchParams: Promise<Record<string, string | string[] | undefined>> }) => {
76
+ const input = kitUser.parse({ searchParams: await props.searchParams });
77
+ return <ViewUser initial={await kitUser.query({ input, context: { teamId } })} />;
78
+ };
366
79
  ```
367
80
 
368
- ### Client-side (useDataKit Hook)
81
+ `parse` never throws: invalid values fall back to the defaults, and a page past the end shows the last page.
369
82
 
370
- For fully custom implementations:
83
+ ## 3. The view (client)
371
84
 
372
85
  ```tsx
373
86
  'use client';
374
87
 
375
- import { useDataKit } from 'next-data-kit/client';
376
- import { fetchUsers } from '@/actions/users';
377
-
378
- export function UsersTable() {
379
- const {
380
- items,
381
- page,
382
- total,
383
- state: { isLoading },
384
- actions: { setPage, setFilter, setSort, refresh },
385
- } = useDataKit({
386
- action: fetchUsers,
387
- initial: {
388
- limit: 10,
389
- },
390
- });
391
-
392
- return (
393
- <div>
394
- <input placeholder='Search...' onChange={e => setFilter('search', e.target.value)} />
395
-
396
- {isLoading ? (
397
- <p>Loading...</p>
398
- ) : (
399
- <table>
400
- <thead>
401
- <tr>
402
- <th onClick={() => setSort('name', 1)}>Name</th>
403
- <th onClick={() => setSort('email', 1)}>Email</th>
404
- </tr>
405
- </thead>
406
- <tbody>
407
- {items.map(user => (
408
- <tr key={user.id}>
409
- <td>{user.name}</td>
410
- <td>{user.email}</td>
411
- </tr>
412
- ))}
413
- </tbody>
414
- </table>
415
- )}
416
-
417
- <button disabled={page === 1} onClick={() => setPage(page - 1)}>
418
- Previous
419
- </button>
420
- <span>Page {page}</span>
421
- <button onClick={() => setPage(page + 1)}>Next</button>
422
- </div>
423
- );
424
- }
425
- ```
426
-
427
- ## API Reference
428
-
429
- ### Server
430
-
431
- #### `dataKitServerAction(options)`
432
-
433
- Main server function for handling table data fetching.
434
-
435
- **With Mongoose Model** (auto-infers document type):
436
-
437
- ```typescript
438
- dataKitServerAction({
439
- model: UserModel, // Mongoose model
440
- input: TDataKitInput,
441
- item: user => ({ ... }), // user is typed from model
442
- filterCustom?: { ... }, // Custom filter handlers
443
- filter?: { ... } | (input) => query, // Base filter (object or function)
444
- defaultSort?: { ... },
445
- maxLimit?: number, // Default: 100
446
- queryAllowed?: string[], // Whitelist for query fields
447
- filterAllowed?: string[], // Auto-derived from filterCustom
448
- sortAllowed?: string[], // Whitelist for sortable fields
449
- });
450
- ```
451
-
452
- **Filter Options:**
453
-
454
- ```typescript
455
- // As a plain object (static base filter)
456
- filter: { isActive: true, deletedAt: null }
457
-
458
- // As a function (dynamic filter based on input)
459
- filter: (filterInput) => ({
460
- organizationId: filterInput?.orgId,
461
- isActive: true
462
- })
463
- ```
464
-
465
- **With Custom Adapter** (for testing or non-mongoose):
466
-
467
- ```typescript
468
- import { adapterMemory } from 'next-data-kit/server';
469
-
470
- dataKitServerAction({
471
- adapter: adapterMemory(items), // or custom adapter
472
- input: TDataKitInput,
473
- item: item => ({ ... }),
474
- maxLimit?: number,
475
- queryAllowed?: string[],
476
- filterAllowed?: string[],
477
- sortAllowed?: string[],
478
- });
479
- ```
480
-
481
- ### Security & Filtering
482
-
483
- **Three security whitelists:**
484
-
485
- 1. **`filterCustom`** - User-facing filters (search, dropdowns, etc.)
486
- - Client `filters` prop → validated against `filterCustom` keys
487
- - Only defined keys are allowed (throws error otherwise)
488
-
489
- 2. **`queryAllowed`** - Direct field matching (fixed filters)
490
- - Explicit whitelist required
491
- - Use for: `{ active: true }`, user-specific queries
492
-
493
- 3. **`sortAllowed`** - Sortable fields whitelist
494
- - Prevents sorting on arbitrary/sensitive fields
495
- - Recommended for production security
496
-
497
- ```typescript
498
- dataKitServerAction({
499
- model: UserModel,
500
- input,
501
- item: u => u,
502
- filterCustom: {
503
- search: createSearchFilter(['name', 'email']),
504
- role: value => ({ role: value }),
505
- },
506
- queryAllowed: ['organizationId', 'active'],
507
- sortAllowed: ['name', 'email', 'createdAt'], // Only allow sorting these fields
508
- });
509
- ```
510
-
511
- ### Error Handling
512
-
513
- Errors are automatically displayed in `DataKitTable` or available via `state.error` in `useDataKit`.
514
-
515
- ```tsx
516
- const {
517
- state: { error },
518
- } = useDataKit({ action: fetchUsers });
519
- if (error) return <div>Error: {error.message}</div>;
520
- ```
521
-
522
- #### Custom Filters
523
-
524
- ```typescript
525
- import { createSearchFilter, escapeRegex } from 'next-data-kit/server';
526
-
527
- filterCustom: {
528
- // Use built-in helper
529
- search: createSearchFilter(['name', 'email', 'phone']),
530
-
531
- // Or implement custom logic
532
- priceRange: (value: { min: number; max: number }) => ({
533
- price: { $gte: value.min, $lte: value.max },
534
- }),
535
- }
88
+ import { DataKitFilter } from '@/components/ui/ndk/data-kit/filter';
89
+ import { DataKitPagination } from '@/components/ui/ndk/data-kit/pagination';
90
+ import { DataKitRoot } from '@/components/ui/ndk/data-kit/root';
91
+ import { DataKitTable } from '@/components/ui/ndk/data-kit/table';
92
+
93
+ export const ViewUser = (props: { initial: TDataKitResult<TUser> }) => (
94
+ <DataKitRoot initial={props.initial}>
95
+ <DataKitFilter name="search" type="text" />
96
+ <DataKitFilter name="role" type="select" options={[{ value: 'admin', label: 'Admin' }, { value: 'user', label: 'User' }]} />
97
+ <DataKitTable<TUser>
98
+ selectable
99
+ columns={[
100
+ { id: 'name', head: 'Name', sort: 'name', cell: ({ item }) => item.name },
101
+ { id: 'email', head: 'Email', cell: ({ item }) => item.email },
102
+ ]}
103
+ />
104
+ <DataKitPagination sizes={[10, 20, 50]} />
105
+ </DataKitRoot>
106
+ );
536
107
  ```
537
108
 
538
- #### Filter Flow
109
+ Every part takes a `labels` prop with English defaults, so pass your own translations. `DataKitRoot` also accepts `children={(kit) => …}` for your own controls, and `useDataKitRoot()` gives any child the same state.
539
110
 
540
- Match client filter `id` with server `filterCustom` key:
111
+ ## Client-side fetching and infinite scroll
541
112
 
542
- ```tsx
543
- // Client
544
- <DataKitTable filters={[{ id: 'priceRange', label: 'Price', type: 'TEXT' }]} />
113
+ To fetch without navigating, pass your own server action. **Check auth in it**: a server action is a public endpoint.
545
114
 
546
- // Server
547
- filterCustom: {
548
- priceRange: value => ({ price: { $lte: Number(value) } }),
549
- }
115
+ ```ts
116
+ 'use server';
550
117
 
551
- // Or use programmatically
552
- const { actions: { setFilter } } = useDataKit({ ... });
553
- setFilter('priceRange', 100);
118
+ export const aUserList = async (input: unknown) => {
119
+ const session = await auth();
120
+ return kitUser.query({ input: kitUser.schema.parse(input), context: { teamId: session.teamId } });
121
+ };
554
122
  ```
555
123
 
556
- ### Client
557
-
558
- #### `<DataKitTable>` Component
559
-
560
- Full-featured table component with built-in UI.
561
-
562
- | Prop | Type | Description |
563
- | ----------------- | ---------------------------- | --------------------------------------- |
564
- | `action` | `(input) => Promise<Result>` | Server action function |
565
- | `table` | `Column[]` | Column definitions |
566
- | `filters` | `FilterItem[]` | Filter configurations |
567
- | `selectable` | `{ enabled, actions? }` | Selection & bulk actions |
568
- | `limit` | `{ default: number }` | Items per page (auto-added to dropdown) |
569
- | `sorts` | `{ path, value }[]` | Default sorts (hidden fields like `_id`)|
570
- | `defaultSort` | `TSortEntry[]` | Initial sort configuration |
571
- | `pagination` | `'SIMPLE' \| 'NUMBER'` | Pagination mode (default: `'NUMBER'`) |
572
- | `controller` | `Ref<Controller>` | External control ref |
573
- | `className` | `string` | Container class |
574
- | `bordered` | `boolean \| 'rounded'` | Border style |
575
- | `refetchInterval` | `number` | Auto-refresh interval (ms) |
576
-
577
- **Controller Ref:**
578
-
579
- The `controller` prop allows external manipulation of the table. Pass a ref and access these methods:
580
-
581
124
  ```tsx
582
- import { useRef } from 'react';
583
- import { DataKitTable } from 'next-data-kit/client';
584
- import type { TDataKitController } from 'next-data-kit/types';
585
-
586
- function MyTable() {
587
- const controllerRef = useRef<TDataKitController<User> | null>(null);
588
-
589
- const handleAddUser = () => {
590
- controllerRef.current?.itemPush({ id: '123', name: 'New User' }, 0);
591
- };
592
-
593
- const handleUpdateUser = () => {
594
- // Update by index
595
- controllerRef.current?.itemUpdate({ index: 0, data: { name: 'Updated Name' } });
596
- // Or update by id
597
- controllerRef.current?.itemUpdate({ id: '123', data: { name: 'Updated Name' } });
598
- };
599
-
600
- const handleDeleteUser = () => {
601
- // Delete by index
602
- controllerRef.current?.itemDelete({ index: 0 });
603
- // Or delete by id
604
- controllerRef.current?.itemDelete({ id: '123' });
605
- };
606
-
607
- return <DataKitTable action={fetchUsers} controller={controllerRef} table={columns} />;
608
- }
609
- ```
610
-
611
- Available methods:
612
- - `itemPush(item, position?)` - Add new item (0 = start, 1 = end)
613
- - `itemUpdate(props)` - Update item by index or id with partial data
614
- - `itemDelete(props)` - Delete item by index or id
615
- - `refetchData()` - Refresh table data from server
616
- - `deleteBulk(items)` - Delete multiple items
617
- - `getSelectedItems()` - Get currently selected items
618
- - `clearSelection()` - Clear all selections
619
-
620
-
621
- #### `<DataKit>` Component
622
-
623
- Headless component for custom layouts (grids, cards, etc).
624
-
625
- | Prop | Type | Description |
626
- | ------------- | ---------------------------- | --------------------------------------- |
627
- | `action` | `(input) => Promise<Result>` | Server action function |
628
- | `filters` | `FilterItem[]` | Filter configurations |
629
- | `limit` | `{ default: number }` | Items per page (auto-added to dropdown) |
630
- | `defaultSort` | `TSortEntry[]` | Initial sort configuration |
631
- | `pagination` | `'SIMPLE' \| 'NUMBER'` | Pagination mode (default: `'NUMBER'`) |
632
- | `manual` | `boolean` | Skip loading/empty state handling |
633
- | `children` | `(dataKit) => ReactNode` | Render function |
634
-
635
- #### `<DataKitInfinity>` Component
636
-
637
- Infinite scroll component for feeds, chat interfaces, and dynamic content loading.
638
-
639
- | Prop | Type | Description |
640
- | ------------- | ----------------------------- | ------------------------------------------ |
641
- | `action` | `(input) => Promise<Result>` | Server action function |
642
- | `filters` | `FilterItem[]` | Filter configurations |
643
- | `limit` | `{ default: number }` | Items per page (default: 10) |
644
- | `defaultSort` | `TSortEntry[]` | Initial sort configuration |
645
- | `manual` | `boolean` | Skip loading/empty state handling |
646
- | `autoFetch` | `boolean` | Auto-fetch on mount (default: true) |
647
- | `debounce` | `number` | Filter debounce in ms (default: 300) |
648
- | `memory` | `'memory' \| 'search-params'` | Memory management mode (default: 'memory') |
649
- | `className` | `string` | Container class |
650
- | `children` | `(dataKit) => ReactNode` | Render function with accumulated items |
651
-
652
- **Features:**
653
-
654
- - Automatically accumulates items across pages as user scrolls
655
- - Uses `react-intersection-observer` for efficient scroll detection
656
- - Built-in toolbar with filters and manual refresh
657
- - Access to `state.hasNextPage` for end-of-list detection
658
-
659
- #### `useDataKit(options)`
660
-
661
- React hook for managing next-data-kit state.
662
-
663
- ```typescript
664
- interface TUseDataKitOptions<T, R> {
665
- action: (input: TDataKitInput<T>) => Promise<TDataKitResult<R>>;
666
- initial?: {
667
- page?: number;
668
- limit?: number;
669
- sorts?: TSortEntry[];
670
- filter?: Record<string, unknown>;
671
- query?: Record<string, unknown>;
672
- };
673
- // ** Filter items with configuration
674
- filters?: {
675
- id: string;
676
- configuration?: {
677
- type: 'REGEX' | 'EXACT';
678
- field?: string;
679
- };
680
- }[];
681
- onSuccess?: (result: TDataKitResult<R>) => void;
682
- onError?: (error: Error) => void;
683
- autoFetch?: boolean;
684
- }
685
- ```
686
-
687
- Returns:
688
-
689
- - `items` - Current page items
690
- - `page` - Current page number
691
- - `limit` - Items per page
692
- - `total` - Total document count
693
- - `sorts` - Current sort configuration
694
- - `filter` - Current filter values
695
- - `state`
696
- - `isLoading` - Loading state
697
- - `error` - Error state
698
- - `hasNextPage` - Whether more pages exist (page \* limit < total)
699
- - `actions`
700
- - `setPage(page)` - Go to a specific page
701
- - `setLimit(limit)` - Set items per page
702
- - `setSort(path, value)` - Set sort for a column
703
- - `setFilter(key, value)` - Set a filter value
704
- - `clearFilters()` - Clear all filters
705
- - `refresh()` - Refresh the table data
706
- - `reset()` - Reset to initial state
707
- - `setItems(items)` - Replace all items
708
- - `setItemAt(index, item)` - Replace item at index
709
- - `itemUpdate(props)` - Update item by index or id with partial data
710
- - By index: `itemUpdate({ index: 0, data: { name: 'New Name' } })`
711
- - By id: `itemUpdate({ id: '123', data: { name: 'New Name' } })`
712
- - `deleteItemAt(index)` - Delete item at index
713
- - `itemDelete(props)` - Delete item by index or id
714
- - By index: `itemDelete({ index: 0 })`
715
- - By id: `itemDelete({ id: '123' })`
716
- - `itemPush(item, position)` - Add item (position: 0 = start, 1 = end)
717
- - `deleteBulk(items)` - Delete multiple items
718
-
719
- #### `useSelection<T>()`
720
-
721
- React hook for managing table row selection.
722
-
723
- ```typescript
724
- const { selectedIds, toggle, selectAll, deselectAll, isSelected, getSelectedArray } = useSelection<string>();
125
+ <DataKitRoot initial={initial} source={{ fetch: aUserList }} append>
126
+ {(kit) => kit.items.map((item) => <Card key={item.id} item={item} />)}
127
+ <DataKitInfinite />
128
+ </DataKitRoot>
725
129
  ```
726
130
 
727
- #### `usePagination(options)`
131
+ With `source.fetch`, add `url: true` to keep the state in the URL, or leave it out to keep it in memory.
728
132
 
729
- React hook for calculating pagination state.
133
+ ## The hook
730
134
 
731
- ```typescript
732
- const { pages, hasNextPage, hasPrevPage, totalPages } = usePagination({
733
- page: 1,
734
- limit: 10,
735
- total: 100,
736
- });
135
+ ```ts
136
+ const kit = useDataKit({ initial, source: { navigate, refresh } | { fetch, url? }, key?, append?, refetch?: { intervalMs } });
137
+ // kit.items · kit.total · kit.page.{number,size,count} · kit.sort · kit.filter · kit.state.{isPending,error}
138
+ // kit.set.{page,size,sort,filter} · kit.refresh() · kit.reset()
139
+ // kit.item.{push,update,remove} · kit.selection.{ids,has,toggle,all,clear}
737
140
  ```
738
141
 
739
- ## Types
142
+ `key` prefixes the URL params (`?user.page=2&user.sort=name.asc`), so two tables on one page don't collide.
740
143
 
741
- ### Filter Types (Discriminated Union)
144
+ ## URL format
742
145
 
743
- ```typescript
744
- // TEXT - text input
745
- { id: "name", label: "Name", type: "TEXT", placeholder?: "..." }
146
+ `?page=2&size=20&sort=name.asc,createdAt.desc&search=ada&role=admin`. `urlEncode` and `urlDecode` are exported if you build links yourself.
746
147
 
747
- // SELECT - dropdown (dataset required!)
748
- { id: "role", label: "Role", type: "SELECT", dataset: [{ id, name, label }] }
148
+ ## FAQ
749
149
 
750
- // BOOLEAN - toggle switch
751
- { id: "active", label: "Active", type: "BOOLEAN" }
752
- ```
150
+ ### Is it safe to expose sort and filter in the URL?
753
151
 
754
- ### `TDataKitInput<T>`
755
-
756
- ```typescript
757
- interface TDataKitInput<T = unknown> {
758
- action?: 'FETCH';
759
- page?: number;
760
- limit?: number;
761
- sort?: TSortOptions<T>;
762
- sorts?: TSortEntry[];
763
- query?: Record<string, unknown>;
764
- filter?: Record<string, unknown>;
765
- // ** Filter items with configuration
766
- filters?: {
767
- id: string;
768
- configuration?: {
769
- type: 'REGEX' | 'EXACT';
770
- field?: string;
771
- };
772
- }[];
773
- }
774
- ```
152
+ Yes. The server accepts only declared filter keys and sort fields, validates every value with its zod schema, and caps the page size. Undeclared keys are dropped before the adapter runs.
775
153
 
776
- ### `TDataKitResult<R>`
154
+ ### Does it need Next.js?
777
155
 
778
- ```typescript
779
- interface TDataKitResult<R> {
780
- type: 'ITEMS';
781
- items: R[];
782
- documentTotal: number;
783
- }
784
- ```
156
+ The core and the hook don't import Next.js. The registry components use `next/navigation` for the default URL source; in another framework, pass `source={{ fetch }}` or edit the copied `root.tsx`.
785
157
 
786
- ### `TFilterConfig`
158
+ ### How do I use it without Mongoose?
787
159
 
788
- ```typescript
789
- interface TFilterConfig {
790
- [key: string]: {
791
- type: 'REGEX' | 'EXACT';
792
- field?: string;
793
- };
794
- }
795
- ```
796
-
797
- ## Custom Adapters
798
-
799
- Use custom adapters for non-mongoose databases or testing:
160
+ Write an adapter: a function that receives `{ filter, sort, skip, limit }` and returns `{ items, total }`. Your filters' `query` functions return whatever your adapter understands.
800
161
 
801
- ```typescript
802
- import { adapterMemory } from 'next-data-kit/server';
803
- import type { TDataKitAdapter } from 'next-data-kit/types';
162
+ ### How do I upgrade from 9.x?
804
163
 
805
- // Built-in memory adapter (great for testing)
806
- const adapter = adapterMemory(items);
807
-
808
- // Or create a custom adapter
809
- const myAdapter: TDataKitAdapter<MyDocument> = async ({ filter, sorts, limit, skip }) => {
810
- const items = await myDb.query({ filter, limit, skip });
811
- const total = await myDb.count(filter);
812
- return { items, total };
813
- };
814
-
815
- dataKitServerAction({
816
- adapter: myAdapter,
817
- input,
818
- item: doc => ({ ... }),
819
- });
820
- ```
164
+ See [MIGRATION.md](./MIGRATION.md).
821
165
 
822
166
  ## License
823
167
 
824
- MIT © muhgholy
825
-
826
- ## Dev Playground (Next.js + MongoDB)
827
-
828
- This repo includes a real Next.js playground demonstrating all features with MongoDB.
829
-
830
- ### Run Playground
831
-
832
- ```bash
833
- cd playground
834
- npm install
835
- npm run seed # Seed MongoDB with sample data
836
- npm run dev # Start Next.js dev server
837
- ```
838
-
839
- Then open: http://localhost:3000
840
-
841
- **Prerequisites**: MongoDB running on `mongodb://localhost:27017`
842
-
843
- See [playground/README.md](playground/README.md) for details.
168
+ MIT