next-data-kit 9.9.2 → 11.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.
- package/MIGRATION.md +75 -0
- package/README.md +289 -698
- package/dist/chunk-5D747NEB.js +12 -0
- package/dist/chunk-5D747NEB.js.map +1 -0
- package/dist/index.d.ts +109 -110
- package/dist/index.js +109 -205
- package/dist/index.js.map +1 -1
- package/dist/server/drizzle.d.ts +11 -0
- package/dist/server/drizzle.js +39 -0
- package/dist/server/drizzle.js.map +1 -0
- package/dist/server.d.ts +273 -88
- package/dist/server.js +269 -282
- package/dist/server.js.map +1 -1
- package/dist/source--l-z9HHB.d.ts +60 -0
- package/package.json +75 -107
- package/registry/r/data-kit.json +74 -0
- package/registry/r/registry.json +72 -0
- package/dist/action-DCmAhOQa.d.cts +0 -196
- package/dist/action-DCmAhOQa.d.ts +0 -196
- package/dist/chunk-5TIEIY7M.cjs +0 -393
- package/dist/chunk-5TIEIY7M.cjs.map +0 -1
- package/dist/chunk-MTJATM72.cjs +0 -2423
- package/dist/chunk-MTJATM72.cjs.map +0 -1
- package/dist/chunk-O377UO7C.js +0 -2379
- package/dist/chunk-O377UO7C.js.map +0 -1
- package/dist/chunk-VFSNUXOW.js +0 -382
- package/dist/chunk-VFSNUXOW.js.map +0 -1
- package/dist/client/components/data-kit-infinity.d.ts +0 -23
- package/dist/client/components/data-kit-infinity.d.ts.map +0 -1
- package/dist/client/components/data-kit-table.d.ts +0 -34
- package/dist/client/components/data-kit-table.d.ts.map +0 -1
- package/dist/client/components/data-kit.d.ts +0 -25
- package/dist/client/components/data-kit.d.ts.map +0 -1
- package/dist/client/components/index.d.ts +0 -4
- package/dist/client/components/index.d.ts.map +0 -1
- package/dist/client/components/ui/button.d.ts +0 -14
- package/dist/client/components/ui/button.d.ts.map +0 -1
- package/dist/client/components/ui/checkbox.d.ts +0 -5
- package/dist/client/components/ui/checkbox.d.ts.map +0 -1
- package/dist/client/components/ui/dropdown-menu.d.ts +0 -28
- package/dist/client/components/ui/dropdown-menu.d.ts.map +0 -1
- package/dist/client/components/ui/index.d.ts +0 -8
- package/dist/client/components/ui/index.d.ts.map +0 -1
- package/dist/client/components/ui/pagination.d.ts +0 -14
- package/dist/client/components/ui/pagination.d.ts.map +0 -1
- package/dist/client/components/ui/popover.d.ts +0 -10
- package/dist/client/components/ui/popover.d.ts.map +0 -1
- package/dist/client/components/ui/select.d.ts +0 -18
- package/dist/client/components/ui/select.d.ts.map +0 -1
- package/dist/client/components/ui/table.d.ts +0 -11
- package/dist/client/components/ui/table.d.ts.map +0 -1
- package/dist/client/context/index.d.ts +0 -22
- package/dist/client/context/index.d.ts.map +0 -1
- package/dist/client/hooks/index.d.ts +0 -7
- package/dist/client/hooks/index.d.ts.map +0 -1
- package/dist/client/hooks/useDataKit.d.ts +0 -9
- package/dist/client/hooks/useDataKit.d.ts.map +0 -1
- package/dist/client/hooks/usePagination.d.ts +0 -18
- package/dist/client/hooks/usePagination.d.ts.map +0 -1
- package/dist/client/hooks/useSelection.d.ts +0 -13
- package/dist/client/hooks/useSelection.d.ts.map +0 -1
- package/dist/client/index.d.ts +0 -11
- package/dist/client/index.d.ts.map +0 -1
- package/dist/client/utils/cn.d.ts +0 -10
- package/dist/client/utils/cn.d.ts.map +0 -1
- package/dist/client/utils/index.d.ts +0 -60
- package/dist/client/utils/index.d.ts.map +0 -1
- package/dist/client.cjs +0 -85
- package/dist/client.cjs.map +0 -1
- package/dist/client.d.cts +0 -62
- package/dist/client.d.ts +0 -7
- package/dist/client.d.ts.map +0 -1
- package/dist/client.js +0 -4
- package/dist/client.js.map +0 -1
- package/dist/index-DUVfK8q6.d.ts +0 -284
- package/dist/index-qXbjvUTB.d.cts +0 -284
- package/dist/index.cjs +0 -300
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -117
- package/dist/internal/hooks.cjs +0 -12
- package/dist/internal/hooks.cjs.map +0 -1
- package/dist/internal/hooks.d.cts +0 -1
- package/dist/internal/hooks.d.ts +0 -1
- package/dist/internal/hooks.js +0 -3
- package/dist/internal/hooks.js.map +0 -1
- package/dist/server/utils.d.ts +0 -52
- package/dist/server/utils.d.ts.map +0 -1
- package/dist/server.cjs +0 -315
- package/dist/server.cjs.map +0 -1
- package/dist/server.d.cts +0 -99
- package/dist/styles.css +0 -2
- package/dist/types/client/component.d.ts +0 -129
- package/dist/types/client/component.d.ts.map +0 -1
- package/dist/types/client/hook.d.ts +0 -116
- package/dist/types/client/hook.d.ts.map +0 -1
- package/dist/types/client/selectable.d.ts +0 -43
- package/dist/types/client/selectable.d.ts.map +0 -1
- package/dist/types/index.cjs +0 -4
- package/dist/types/index.cjs.map +0 -1
- package/dist/types/index.d.cts +0 -291
- package/dist/types/index.d.ts +0 -12
- package/dist/types/index.d.ts.map +0 -1
- package/dist/types/index.js +0 -3
- package/dist/types/index.js.map +0 -1
- package/dist/types/next-data-kit.d.ts +0 -95
- package/dist/types/next-data-kit.d.ts.map +0 -1
- package/dist/types/server/action.d.ts +0 -44
- package/dist/types/server/action.d.ts.map +0 -1
- package/dist/types/server/database/mongo.d.ts +0 -56
- package/dist/types/server/database/mongo.d.ts.map +0 -1
- package/dist/useDataKit-XFp3_mUc.d.cts +0 -276
- package/dist/useDataKit-XFp3_mUc.d.ts +0 -276
package/README.md
CHANGED
|
@@ -1,843 +1,434 @@
|
|
|
1
1
|
# next-data-kit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Server-driven data tables for React and Next.js: **one server function, one component.** You declare which columns can be filtered and sorted; the URL holds the table's state; the toolbar builds itself; any database plugs in.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
// ** server
|
|
7
|
+
export const tableUser = dataKit({
|
|
8
|
+
source: sourceMongoose({ model: ModelUser }),
|
|
9
|
+
column: {
|
|
10
|
+
name: { filter: 'text', sort: true },
|
|
11
|
+
role: { filter: 'multiSelect', option: ['admin', 'user'] },
|
|
12
|
+
createdAt: { filter: 'dateRange', preset: ['7d', '30d'], sort: true },
|
|
13
|
+
},
|
|
14
|
+
search: ['name', 'email'],
|
|
15
|
+
row: (props) => ({ id: String(props.row._id), name: props.row.name, role: props.row.role }),
|
|
16
|
+
});
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
// ** client
|
|
21
|
+
<DataKit data={data} columns={[{ accessorKey: 'name', header: 'Name' }, { accessorKey: 'role', header: 'Role' }]} />
|
|
22
|
+
```
|
|
4
23
|
|
|
5
|
-
|
|
24
|
+
- **Secure by default**: only declared columns can be filtered or sorted, values are validated and capped, and the browser never names a database field.
|
|
25
|
+
- **Familiar**: columns are [TanStack Table](https://tanstack.com/table) `ColumnDef`s; filters use the variants of the shadcn data-table (`text`, `select`, `multiSelect`, `range`, `dateRange`, …); sources work like Refine data providers.
|
|
26
|
+
- **Any data source**: Mongoose, Prisma, Drizzle (any SQL dialect), REST and in-memory built in; a new database is one `sourceDefine` call.
|
|
27
|
+
- **Server-rendered**: the first page is in the HTML; paging, sorting and filtering change the URL, so reload, back and shared links just work.
|
|
28
|
+
- **Yours to change**: the UI is a shadcn registry item copied into your project, on your own components and theme.
|
|
29
|
+
- **Small**: no runtime dependencies (about 1.3 kB client, 3 kB server, brotli).
|
|
6
30
|
|
|
7
|
-
|
|
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
|
|
31
|
+
## Contents
|
|
16
32
|
|
|
17
|
-
|
|
33
|
+
- [Install](#install)
|
|
34
|
+
- [Quick start](#quick-start)
|
|
35
|
+
- [Guides](#guides): [filters](#filters) · [search](#search) · [sorting](#sorting) · [page size and counting](#page-size-and-counting) · [scope and auth](#scope-and-auth) · [custom filters](#custom-filters) · [the row shape](#the-row-shape) · [selection and bulk actions](#selection-and-bulk-actions) · [row actions](#row-actions) · [your own controls](#your-own-controls) · [your own layout](#your-own-layout) · [infinite scroll](#infinite-scroll) · [several tables on one page](#several-tables-on-one-page) · [exports](#exports) · [translations](#translations) · [React Compiler](#react-compiler)
|
|
36
|
+
- [Sources](#sources): [Mongoose](#mongoose) · [Prisma](#prisma) · [Drizzle](#drizzle) · [REST](#rest) · [memory](#memory) · [your own](#your-own-source)
|
|
37
|
+
- [Reference](#reference)
|
|
38
|
+
- [FAQ](#faq)
|
|
39
|
+
- [Migrating](#migrating)
|
|
40
|
+
|
|
41
|
+
## Install
|
|
18
42
|
|
|
19
43
|
```bash
|
|
20
44
|
npm install next-data-kit
|
|
21
|
-
# or
|
|
22
|
-
yarn add next-data-kit
|
|
23
|
-
# or
|
|
24
|
-
pnpm add next-data-kit
|
|
25
45
|
```
|
|
26
46
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
### Server-side (Next.js Server Action)
|
|
47
|
+
Peers: `react` 19, `react-dom` 19, `zod` 4; `mongoose` 8–9 or `drizzle-orm` only if you use those sources.
|
|
30
48
|
|
|
31
|
-
|
|
32
|
-
'use server';
|
|
49
|
+
Add the registry to `components.json`, then the components:
|
|
33
50
|
|
|
34
|
-
|
|
35
|
-
|
|
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
|
-
}
|
|
51
|
+
```json
|
|
52
|
+
{ "registries": { "@ndk": "https://unpkg.com/next-data-kit@11/registry/r/{name}.json" } }
|
|
53
53
|
```
|
|
54
54
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
55
|
+
```bash
|
|
56
|
+
npx shadcn add @ndk/data-kit
|
|
57
|
+
```
|
|
58
58
|
|
|
59
|
-
|
|
60
|
-
'use server';
|
|
59
|
+
That adds `components/ui/ndk/data-kit/` plus any shadcn component it needs that you don't have yet (`table`, `popover`, `command`, `calendar`, …) and `@tanstack/react-table` 8. If shadcn asks to overwrite one of your components, answer **No**. Works with shadcn's Radix and Base UI styles.
|
|
61
60
|
|
|
62
|
-
##
|
|
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.
|
|
61
|
+
## Quick start
|
|
64
62
|
|
|
65
|
-
|
|
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`.
|
|
63
|
+
**1. Declare the table** once, on the server (`controllers/user.ts`):
|
|
67
64
|
|
|
68
|
-
|
|
65
|
+
```ts
|
|
66
|
+
import { dataKit, sourceMongoose } from 'next-data-kit/server';
|
|
69
67
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
68
|
+
export const tableUser = dataKit({
|
|
69
|
+
source: sourceMongoose({ model: ModelUser }),
|
|
70
|
+
column: {
|
|
71
|
+
name: { filter: 'text', sort: true },
|
|
72
|
+
email: { sort: true },
|
|
73
|
+
role: { filter: 'multiSelect', option: ['admin', 'user', 'guest'] },
|
|
74
|
+
age: { filter: 'range', sort: true },
|
|
75
|
+
active: { filter: 'boolean' },
|
|
76
|
+
createdAt: { filter: 'dateRange', preset: ['7d', '30d'], sort: true },
|
|
77
|
+
},
|
|
78
|
+
search: ['name', 'email'],
|
|
79
|
+
sort: 'createdAt.desc',
|
|
80
|
+
page: { size: 20 },
|
|
81
|
+
row: (props) => ({ id: String(props.row._id), name: props.row.name, email: props.row.email, role: props.row.role, age: props.row.age, active: props.row.active }),
|
|
82
|
+
});
|
|
83
|
+
```
|
|
73
84
|
|
|
74
|
-
|
|
75
|
-
const parsedInput = dataKitSchemaZod.parse(input);
|
|
85
|
+
**2. Query it in the page** (server component):
|
|
76
86
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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
|
+
```tsx
|
|
88
|
+
const Page = async (props: { searchParams: Promise<Record<string, string | string[] | undefined>> }) => <ViewUser data={await tableUser.query({ searchParams: await props.searchParams })} />;
|
|
89
|
+
export default Page;
|
|
87
90
|
```
|
|
88
91
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
Ready-to-use table with built-in filtering, sorting, and selection:
|
|
92
|
+
**3. Render it** (client component):
|
|
92
93
|
|
|
93
94
|
```tsx
|
|
94
95
|
'use client';
|
|
95
96
|
|
|
96
|
-
import {
|
|
97
|
-
import {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
-
}
|
|
97
|
+
import type { ColumnDef } from '@tanstack/react-table';
|
|
98
|
+
import type { TDataKitDataOf, TDataKitRow } from 'next-data-kit/server';
|
|
99
|
+
import { DataKit } from '@/components/ui/ndk/data-kit/data-kit';
|
|
100
|
+
import type { tableUser } from '@/controllers/user';
|
|
101
|
+
|
|
102
|
+
const columns: ColumnDef<TDataKitRow<typeof tableUser>>[] = [
|
|
103
|
+
{ accessorKey: 'name', header: 'Name' },
|
|
104
|
+
{ accessorKey: 'email', header: 'Email' },
|
|
105
|
+
{ accessorKey: 'role', header: 'Role', meta: { option: { admin: 'Admin', user: 'User', guest: 'Guest' } } },
|
|
106
|
+
];
|
|
107
|
+
|
|
108
|
+
export const ViewUser = (props: { data: TDataKitDataOf<typeof tableUser> }) => <DataKit data={props.data} columns={columns} sizes={[10, 20, 50]} />;
|
|
152
109
|
```
|
|
153
110
|
|
|
154
|
-
|
|
111
|
+
That's the whole table: search box and one filter per declared column, sortable headers (`aria-sort`), pagination with real links, page sizes. A column's `id` (its `accessorKey` by default) is its server column key; that's how headers know they can sort and filters find their labels.
|
|
155
112
|
|
|
156
|
-
|
|
113
|
+
## Guides
|
|
157
114
|
|
|
158
|
-
|
|
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.
|
|
115
|
+
### Filters
|
|
160
116
|
|
|
161
|
-
|
|
162
|
-
'use client';
|
|
117
|
+
Each column's `filter` is a variant. The variant fixes the operator, the URL encoding and the toolbar control, so the client never chooses how to query:
|
|
163
118
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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
|
-
```
|
|
119
|
+
| Variant | URL | Condition | Toolbar |
|
|
120
|
+
|---|---|---|---|
|
|
121
|
+
| `text` | `?name=ada` | contains (case-insensitive) | input |
|
|
122
|
+
| `number` | `?age=30` | equals | number input |
|
|
123
|
+
| `range` | `?age=18-30`, `?age=18-`, `?age=-30` | between / ≥ / ≤ | min–max inputs |
|
|
124
|
+
| `select` | `?role=admin` | equals one of `option` | single-choice list |
|
|
125
|
+
| `multiSelect` | `?role=admin,user` | in `option` | multi-choice list |
|
|
126
|
+
| `boolean` | `?active=true` | equals | yes / no |
|
|
127
|
+
| `date` | `?createdAt=<ms>-<ms>` | between (that day) | calendar |
|
|
128
|
+
| `dateRange` | `?createdAt=<ms>-<ms>` or `?createdAt=7d` | between, or since a `preset` | presets + calendar |
|
|
195
129
|
|
|
196
|
-
|
|
130
|
+
- Dates are sent as the browser's own day boundaries, so the server never guesses a time zone. `preset: ['7d', '24h']` stays relative in a shared link.
|
|
131
|
+
- `option` can be a function, resolved per request, e.g. ids from another table: `option: async () => (await ModelCollection.find()).map((row) => row.id)`. Name the values on the client with `meta.option` on the column.
|
|
132
|
+
- A different database field than the key: `username: { field: 'username.data', filter: 'text' }`.
|
|
133
|
+
- Filterable from the URL but not shown in the toolbar (a link from another page): `hidden: true`.
|
|
134
|
+
- Invalid values are dropped as if unset; text is capped at 200 characters and lists at 100 values.
|
|
135
|
+
- In the toolbar, an active filter moves to the front, gets a solid border and shows its value as a badge; its ⓧ clears just that filter, and **Reset** clears them all.
|
|
197
136
|
|
|
198
|
-
|
|
137
|
+
### Search
|
|
199
138
|
|
|
200
|
-
|
|
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
|
-
/>
|
|
139
|
+
`search: ['name', 'email']` adds a search box (`?search=`) that matches any of those columns. They can be columns without a filter of their own.
|
|
207
140
|
|
|
208
|
-
|
|
209
|
-
<DataKitTable
|
|
210
|
-
action={fetchUsers}
|
|
211
|
-
pagination="SIMPLE"
|
|
212
|
-
table={columns}
|
|
213
|
-
/>
|
|
214
|
-
```
|
|
141
|
+
### Sorting
|
|
215
142
|
|
|
216
|
-
|
|
143
|
+
Columns with `sort: true` get a sortable header (ascending → descending → off). `sort: 'createdAt.desc'` (or a list) is the default. Anything else in `?sort=` falls back to it. Sources add a unique tie-break, so equal values keep a stable order across pages.
|
|
217
144
|
|
|
218
|
-
|
|
219
|
-
- Mobile: Shows prev icon, current page number, next icon
|
|
220
|
-
- Automatically adds ellipsis for skipped pages
|
|
221
|
-
- Fully responsive with Tailwind CSS
|
|
145
|
+
### Page size and counting
|
|
222
146
|
|
|
223
|
-
|
|
147
|
+
`page: { size: 20 }` (the max defaults to 100) or `page: { size: { default: 25, max: 25 } }`. `<DataKit sizes={[10, 25, 50]} />` adds a rows-per-page select. A page past the end shows the last one.
|
|
224
148
|
|
|
225
|
-
|
|
149
|
+
Counting every match costs a query. `page: { count: 'none' }` skips it: `total` is `null` and pagination shows previous / next only.
|
|
226
150
|
|
|
227
|
-
|
|
151
|
+
### Scope and auth
|
|
228
152
|
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
path: 'name', // MongoDB field path
|
|
236
|
-
default: 1 // 1 (asc), -1 (desc), or 0 (no default)
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
]}
|
|
153
|
+
`scope` is always applied and never read from the request: tenants, owners, soft deletes. It gets the `context` you pass to `query`:
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
scope: (props: { context: { teamId: string } }) => ({ teamId: props.context.teamId, deletedAt: null }),
|
|
157
|
+
// ** page.tsx — check auth as usual, then:
|
|
158
|
+
await tableInvoice.query({ searchParams, context: { teamId: session.teamId } });
|
|
240
159
|
```
|
|
241
160
|
|
|
242
|
-
|
|
161
|
+
It returns field → value pairs (each an equality) or a list of conditions.
|
|
243
162
|
|
|
244
|
-
|
|
245
|
-
<DataKitTable
|
|
246
|
-
action={fetchUsers}
|
|
247
|
-
table={columns}
|
|
248
|
-
sorts={[
|
|
249
|
-
{ path: '_id', value: -1 } // Sort by ID descending (tie-breaker)
|
|
250
|
-
]}
|
|
251
|
-
/>
|
|
252
|
-
```
|
|
163
|
+
### Custom filters
|
|
253
164
|
|
|
254
|
-
|
|
165
|
+
When a variant's condition isn't the one you need, keep the variant (it still drives the toolbar and validation) and give it a `query` that returns your source's native condition:
|
|
255
166
|
|
|
256
|
-
|
|
167
|
+
```ts
|
|
168
|
+
type: { filter: 'select', option: ['user', 'admin'], query: (props) => (props.value === 'admin' ? { type: 'admin' } : { type: { $ne: 'admin' } }) },
|
|
169
|
+
status: { filter: 'select', option: ['online'], query: async () => ({ _id: { $in: await ModelSession.distinct('userId', { expiresAt: { $gt: new Date() } }) } }) },
|
|
170
|
+
```
|
|
257
171
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
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 }]
|
|
172
|
+
For a filter with no toolbar control at all, `filterCustom` takes a zod schema and types `value` from it:
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
user: { filter: filterCustom({ schema: z.string().regex(/^[a-f\d]{24}$/i), query: (props) => ({ userId: props.value }) }) },
|
|
273
176
|
```
|
|
274
177
|
|
|
275
|
-
|
|
178
|
+
### The row shape
|
|
276
179
|
|
|
277
|
-
|
|
180
|
+
`row` maps one database row to what the browser gets: plain JSON with a string `id`, nothing secret. Load less with `select` on the source (`sourceMongoose({ model, select: '-password' })`). In development a warning shows when a row has no string `id` or carries an `ObjectId`. Reuse the types with `TDataKitRow<typeof tableUser>` and `TDataKitDataOf<typeof tableUser>`.
|
|
278
181
|
|
|
279
|
-
|
|
280
|
-
<DataKitTable
|
|
281
|
-
action={fetchUsers}
|
|
282
|
-
limit={{ default: 15 }} // 15 will appear in dropdown alongside 10, 25, 50, 100
|
|
283
|
-
table={columns}
|
|
284
|
-
/>
|
|
182
|
+
### Selection and bulk actions
|
|
285
183
|
|
|
286
|
-
|
|
184
|
+
```tsx
|
|
287
185
|
<DataKit
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
{
|
|
292
|
-
|
|
186
|
+
data={data}
|
|
187
|
+
columns={columns}
|
|
188
|
+
selectable={(user) => user.id !== currentUserId} // ** or `true`
|
|
189
|
+
actions={(selection) => <Button onClick={() => aUsersDelete({ ids: selection.rows.map((row) => row.id) }).then(selection.clear)}>Delete</Button>}
|
|
190
|
+
/>
|
|
293
191
|
```
|
|
294
192
|
|
|
295
|
-
|
|
193
|
+
While rows are selected, an action bar floats at the bottom of the screen (so it's in reach however far you scroll) with the count, a clear button and your actions. It's a labelled `role="toolbar"` rendered in a portal, the count is announced to screen readers, and **Escape** clears the selection. Rows that disappear (deleted, filtered out) leave the selection on their own. For your own layout, render `<DataKitActionBar table={table}>…</DataKitActionBar>`.
|
|
296
194
|
|
|
297
|
-
|
|
195
|
+
### Row actions
|
|
298
196
|
|
|
299
|
-
|
|
300
|
-
'use client';
|
|
197
|
+
Cells are ordinary TanStack cells: put a dropdown in one. After a server action changes data, `revalidatePath` (or `router.refresh()`) re-renders the page and the table takes the new `data`. `row={{ onClick: ({ row }) => open(row) }}` makes whole rows clickable; stop propagation in cells that hold their own buttons. `meta: { className }` styles a column's header and cells.
|
|
301
198
|
|
|
302
|
-
|
|
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
|
-
}
|
|
323
|
-
```
|
|
324
|
-
|
|
325
|
-
### Client-side (DataKit Component - Custom Layout)
|
|
199
|
+
### Your own controls
|
|
326
200
|
|
|
327
|
-
|
|
201
|
+
`controls` adds anything to the end of the toolbar; a falsy value renders nothing:
|
|
328
202
|
|
|
329
203
|
```tsx
|
|
330
|
-
|
|
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
|
-
}
|
|
204
|
+
<DataKit data={data} columns={columns} controls={data.filter.user && <Link href="?">One user only ✕</Link>} />
|
|
351
205
|
```
|
|
352
206
|
|
|
353
|
-
|
|
207
|
+
`toolbar={false}` and `pagination={false}` hide those parts (e.g. a "latest 5" card).
|
|
208
|
+
|
|
209
|
+
### Your own layout
|
|
210
|
+
|
|
211
|
+
`useDataKitTable` gives you the TanStack `table`; the parts take it:
|
|
354
212
|
|
|
355
213
|
```tsx
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
)}
|
|
365
|
-
</DataKit>
|
|
214
|
+
const table = useDataKitTable({ data, columns });
|
|
215
|
+
return (
|
|
216
|
+
<Fragment>
|
|
217
|
+
<DataKitToolbar table={table} />
|
|
218
|
+
<div className="grid grid-cols-3 gap-4">{table.getRowModel().rows.map((row) => <Card key={row.id} user={row.original} />)}</div>
|
|
219
|
+
<DataKitPagination table={table} />
|
|
220
|
+
</Fragment>
|
|
221
|
+
);
|
|
366
222
|
```
|
|
367
223
|
|
|
368
|
-
|
|
224
|
+
The kit is on `table.options.meta.dataKit` (`set.filter`, `set.sort`, `reset`, `row.update`, `selection`, …).
|
|
369
225
|
|
|
370
|
-
|
|
226
|
+
### Infinite scroll
|
|
371
227
|
|
|
372
|
-
|
|
373
|
-
'use client';
|
|
228
|
+
Infinite scroll fetches from the browser, so it needs a server action. **Check auth in it**: a server action is a public endpoint.
|
|
374
229
|
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
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
|
-
});
|
|
230
|
+
```ts
|
|
231
|
+
'use server';
|
|
232
|
+
export const aUserList = async (input: unknown) => tableUser.query({ input, context: await authContext() });
|
|
233
|
+
```
|
|
391
234
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
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
|
-
}
|
|
235
|
+
```tsx
|
|
236
|
+
const table = useDataKitTable({ data, columns: [], source: { fetch: aUserList }, append: true });
|
|
237
|
+
// ** …render table.getRowModel().rows, then:
|
|
238
|
+
<DataKitInfinite table={table} />
|
|
425
239
|
```
|
|
426
240
|
|
|
427
|
-
|
|
241
|
+
Answers that arrive out of order are dropped. `source: { fetch, url: true }` keeps the state in the URL too.
|
|
428
242
|
|
|
429
|
-
###
|
|
243
|
+
### Several tables on one page
|
|
430
244
|
|
|
431
|
-
|
|
245
|
+
```tsx
|
|
246
|
+
const users = await tableUser.query({ searchParams, key: 'user' });
|
|
247
|
+
const logs = await tableLog.query({ searchParams, key: 'log' });
|
|
248
|
+
// ** view: ?user.page=2&log.sort=createdAt.desc
|
|
249
|
+
<DataKit data={users} dataKey="user" columns={…} />
|
|
250
|
+
<DataKit data={logs} dataKey="log" columns={…} />
|
|
251
|
+
```
|
|
432
252
|
|
|
433
|
-
|
|
253
|
+
### Exports
|
|
434
254
|
|
|
435
|
-
|
|
255
|
+
Reuse the definition with a server-only page size (it ignores `max`):
|
|
436
256
|
|
|
437
|
-
```
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
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
|
|
257
|
+
```ts
|
|
258
|
+
export const aUsersExport = action.schema(tableUser.schema).action(async ({ parsedInput }) => {
|
|
259
|
+
const { rows } = await tableUser.query({ input: { ...parsedInput, page: { number: 1, size: parsedInput.page.size } }, page: { size: 10_000 } });
|
|
260
|
+
// ** …build the CSV
|
|
449
261
|
});
|
|
450
262
|
```
|
|
451
263
|
|
|
452
|
-
|
|
264
|
+
### Translations
|
|
453
265
|
|
|
454
|
-
|
|
455
|
-
// As a plain object (static base filter)
|
|
456
|
-
filter: { isActive: true, deletedAt: null }
|
|
266
|
+
Set every label once, near the root (for example inside your i18n provider):
|
|
457
267
|
|
|
458
|
-
|
|
459
|
-
filter: (
|
|
460
|
-
organizationId: filterInput?.orgId,
|
|
461
|
-
isActive: true
|
|
462
|
-
})
|
|
268
|
+
```tsx
|
|
269
|
+
<DataKitLabelsProvider labels={{ pagination: { previous: t('previous'), next: t('next') }, filter: { reset: t('reset') }, date: { preset: (value) => t('lastDays', { days: value.slice(0, -1) }) } }}>{children}</DataKitLabelsProvider>
|
|
463
270
|
```
|
|
464
271
|
|
|
465
|
-
|
|
272
|
+
`<DataKit labels={…}>` overrides them for one table, e.g. `pagination.summary` or `table.empty`. Column and option names come from your columns (`header`, `meta.label`, `meta.option`).
|
|
466
273
|
|
|
467
|
-
|
|
468
|
-
import { adapterMemory } from 'next-data-kit/server';
|
|
274
|
+
### React Compiler
|
|
469
275
|
|
|
470
|
-
|
|
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
|
-
```
|
|
276
|
+
TanStack Table v8 returns one mutable table object, which React Compiler would memoize away. The registry files opt out with `'use no memo'`; add it to your own components that read `table` directly (as in [Your own layout](#your-own-layout)).
|
|
480
277
|
|
|
481
|
-
|
|
278
|
+
## Sources
|
|
482
279
|
|
|
483
|
-
|
|
280
|
+
A source is the only part that talks to your data. Every source receives the same validated conditions (`{ field, operator, value }`, Refine's operators: `eq ne lt lte gt gte in nin contains between null`), sort and page, and returns `{ rows, total }`.
|
|
484
281
|
|
|
485
|
-
|
|
486
|
-
- Client `filters` prop → validated against `filterCustom` keys
|
|
487
|
-
- Only defined keys are allowed (throws error otherwise)
|
|
282
|
+
### Mongoose
|
|
488
283
|
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
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
|
-
});
|
|
284
|
+
```ts
|
|
285
|
+
sourceMongoose({ model: ModelUser }); // ** .lean() plain objects
|
|
286
|
+
sourceMongoose({ model: ModelUser, hydrate: true }); // ** documents with methods (row: (props) => props.row.onClient())
|
|
287
|
+
sourceMongoose({ model: ModelUser, select: '-password' });
|
|
509
288
|
```
|
|
510
289
|
|
|
511
|
-
|
|
290
|
+
Imports mongoose for types only, so it always uses your app's mongoose. `contains` is an escaped, case-insensitive regex.
|
|
512
291
|
|
|
513
|
-
|
|
292
|
+
### Prisma
|
|
514
293
|
|
|
515
|
-
```
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
} = useDataKit({ action: fetchUsers });
|
|
519
|
-
if (error) return <div>Error: {error.message}</div>;
|
|
294
|
+
```ts
|
|
295
|
+
sourcePrisma({ model: prisma.user });
|
|
296
|
+
sourcePrisma({ model: prisma.user, select: { id: true, name: true }, insensitive: false }); // ** insensitive: false on MySQL / SQLite
|
|
520
297
|
```
|
|
521
298
|
|
|
522
|
-
|
|
299
|
+
Any model delegate; Prisma isn't imported. Nested fields (`author.name`) become relation filters.
|
|
523
300
|
|
|
524
|
-
|
|
525
|
-
import { createSearchFilter, escapeRegex } from 'next-data-kit/server';
|
|
301
|
+
### Drizzle
|
|
526
302
|
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
search: createSearchFilter(['name', 'email', 'phone']),
|
|
303
|
+
```ts
|
|
304
|
+
import { sourceDrizzle } from 'next-data-kit/server/drizzle';
|
|
530
305
|
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
price: { $gte: value.min, $lte: value.max },
|
|
534
|
-
}),
|
|
535
|
-
}
|
|
306
|
+
sourceDrizzle({ db, table: users }); // ** Postgres (ilike)
|
|
307
|
+
sourceDrizzle({ db, table: users, dialect: 'sqlite' }); // ** or 'mysql' (like)
|
|
536
308
|
```
|
|
537
309
|
|
|
538
|
-
|
|
310
|
+
Fields resolve to the table's own columns (an unknown field throws), values go as parameters, and LIKE wildcards are escaped. Tested on real SQL (PGlite).
|
|
539
311
|
|
|
540
|
-
|
|
312
|
+
### REST
|
|
541
313
|
|
|
542
|
-
```
|
|
543
|
-
|
|
544
|
-
<DataKitTable filters={[{ id: 'priceRange', label: 'Price', type: 'TEXT' }]} />
|
|
545
|
-
|
|
546
|
-
// Server
|
|
547
|
-
filterCustom: {
|
|
548
|
-
priceRange: value => ({ price: { $lte: Number(value) } }),
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
// Or use programmatically
|
|
552
|
-
const { actions: { setFilter } } = useDataKit({ ... });
|
|
553
|
-
setFilter('priceRange', 100);
|
|
314
|
+
```ts
|
|
315
|
+
sourceRest<TRepo>({ url: 'https://api.example.com/repos', request: { headers: { authorization: `Bearer ${token}` } } });
|
|
554
316
|
```
|
|
555
317
|
|
|
556
|
-
|
|
318
|
+
Speaks json-server / Refine simple-rest params (`_start`, `_end`, `_sort`, `_order`, `field_gte`, `field_like`, `q`) and reads `X-Total-Count`. Use `response: (props) => ({ rows, total })` for another body shape.
|
|
557
319
|
|
|
558
|
-
|
|
320
|
+
### Memory
|
|
559
321
|
|
|
560
|
-
|
|
322
|
+
`sourceMemory({ rows })`, for tests, fixtures and small static lists.
|
|
561
323
|
|
|
562
|
-
|
|
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) |
|
|
324
|
+
### Your own source
|
|
576
325
|
|
|
577
|
-
|
|
326
|
+
Map the 11 operators to your query language once; `list` runs the query:
|
|
578
327
|
|
|
579
|
-
|
|
328
|
+
```ts
|
|
329
|
+
import { sourceDefine } from 'next-data-kit/server';
|
|
580
330
|
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
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
|
-
}
|
|
331
|
+
export const sourceKysely = <TRow>(props: { db: Kysely<TDatabase>; table: keyof TDatabase }) =>
|
|
332
|
+
sourceDefine<TRow, Expression<SqlBool>>({
|
|
333
|
+
operator: {
|
|
334
|
+
eq: (props) => sql`${sql.ref(props.field)} = ${props.value}`,
|
|
335
|
+
contains: (props) => sql`${sql.ref(props.field)} ilike ${`%${String(props.value).replace(/[\\%_]/g, '\\$&')}%`}`,
|
|
336
|
+
between: (props) => sql`${sql.ref(props.field)} between ${props.value[0]} and ${props.value[1]}`,
|
|
337
|
+
// ** …ne, lt, lte, gt, gte, in, nin, null
|
|
338
|
+
},
|
|
339
|
+
and: (list) => sql.join(list, sql` and `),
|
|
340
|
+
or: (list) => sql`(${sql.join(list, sql` or `)})`,
|
|
341
|
+
list: async (props) => {
|
|
342
|
+
const query = props.db.selectFrom(table).$if(Boolean(props.where), (query) => query.where(props.where!));
|
|
343
|
+
const [rows, total] = await Promise.all([query.selectAll().orderBy(…).limit(props.page.limit).offset(props.page.offset).execute(), props.page.count ? query.select(sql`count(*)`.as('count')).executeTakeFirst() : null]);
|
|
344
|
+
return { rows, total: total ? Number(total.count) : null };
|
|
345
|
+
},
|
|
346
|
+
});
|
|
609
347
|
```
|
|
610
348
|
|
|
611
|
-
|
|
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
|
-
```
|
|
349
|
+
To keep a built-in translation but run your own query (an aggregate, a join), spread its operators: `sourceDefine({ ...sourceMongooseQuery, list: async (props) => … })`. `props.where` is the already-built Mongo filter, and `props.sort` lists the fields, so a computed sort (e.g. by a `$lookup` count) is yours to handle.
|
|
686
350
|
|
|
687
|
-
|
|
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>();
|
|
725
|
-
```
|
|
351
|
+
Rules for any source: combine with **and**, keep values as parameters (never in a query string), map fields through known columns, return the total of all matches (or `null` when `page.count` is false), and add a unique tie-break to the sort.
|
|
726
352
|
|
|
727
|
-
|
|
353
|
+
## Reference
|
|
728
354
|
|
|
729
|
-
|
|
355
|
+
### `dataKit(definition)` · `next-data-kit/server`
|
|
730
356
|
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
})
|
|
737
|
-
|
|
357
|
+
| Option | Default | |
|
|
358
|
+
|---|---|---|
|
|
359
|
+
| `source` | required | A built-in source, `sourceDefine(…)` or `{ list }`. |
|
|
360
|
+
| `column` | required | `{ [key]: { field?, filter?, option?, preset?, query?, sort?, hidden? } }` |
|
|
361
|
+
| `search` | none | Column keys the search box looks in. |
|
|
362
|
+
| `scope` | none | `(props: { context }) => pairs \| conditions`, always applied. |
|
|
363
|
+
| `sort` | none | `'field.direction'` or a list. |
|
|
364
|
+
| `page` | `{ size: 20 }` | `size`: number or `{ default, max }`; `count: 'exact' \| 'none'`. |
|
|
365
|
+
| `row` | required | `(props: { row }) => row` with a string `id`. |
|
|
738
366
|
|
|
739
|
-
|
|
367
|
+
`tableX.query({ searchParams, key?, context?, page? })` or `({ input, context?, page? })` returns `{ rows, total, page, sort, filter, search, meta }`. `tableX.schema` validates an action's input. Also exported: `filterCustom`, `sourceDefine`, `sourceMongoose`, `sourceMongooseQuery`, `sourcePrisma`, `sourceRest`, `sourceMemory`, `urlEncode`, `urlDecode`, and the `TDataKit*` types; `sourceDrizzle` from `next-data-kit/server/drizzle`.
|
|
740
368
|
|
|
741
|
-
###
|
|
369
|
+
### Components · `components/ui/ndk/data-kit/`
|
|
742
370
|
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
371
|
+
| | Props |
|
|
372
|
+
|---|---|
|
|
373
|
+
| `DataKit` | `data`, `columns`, `source?`, `dataKey?`, `refetch?: { intervalMs }`, `selectable?`, `hidden?`, `actions?`, `row?: { onClick }`, `toolbar?`, `controls?`, `pagination?`, `sizes?`, `labels?`, `className?` |
|
|
374
|
+
| `useDataKitTable` | `data`, `columns`, `source?`, `dataKey?`, `append?`, `refetch?`, `selectable?`, `hidden?` → TanStack `table` |
|
|
375
|
+
| `DataKitToolbar` · `DataKitTableView` · `DataKitPagination` · `DataKitInfinite` · `DataKitActionBar` | `table` (+ `children` / `row` / `sizes`) |
|
|
376
|
+
| `DataKitLabelsProvider` | `labels`, `children` |
|
|
746
377
|
|
|
747
|
-
|
|
748
|
-
{ id: "role", label: "Role", type: "SELECT", dataset: [{ id, name, label }] }
|
|
378
|
+
Column `meta`: `label` (the filter's name), `option` (value → label), `className`. `hidden` keeps filter-only columns (that just name a filter) out of the table.
|
|
749
379
|
|
|
750
|
-
|
|
751
|
-
{ id: "active", label: "Active", type: "BOOLEAN" }
|
|
752
|
-
```
|
|
380
|
+
### URL
|
|
753
381
|
|
|
754
|
-
|
|
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
|
-
```
|
|
382
|
+
`?page=2&size=20&sort=name.asc&search=ada&role=admin,user&age=18-30&createdAt=7d`. With a key, every param is prefixed (`?user.page=2`). Page 1 is left out.
|
|
775
383
|
|
|
776
|
-
|
|
384
|
+
## FAQ
|
|
777
385
|
|
|
778
|
-
|
|
779
|
-
interface TDataKitResult<R> {
|
|
780
|
-
type: 'ITEMS';
|
|
781
|
-
items: R[];
|
|
782
|
-
documentTotal: number;
|
|
783
|
-
}
|
|
784
|
-
```
|
|
386
|
+
### Is it safe to put sort and filters in the URL?
|
|
785
387
|
|
|
786
|
-
|
|
388
|
+
Yes. Only declared columns exist; every value is validated for its variant and checked against `option`; sizes, text and lists are capped; `scope` can't be touched from the request. Undeclared params are dropped before the source runs.
|
|
787
389
|
|
|
788
|
-
|
|
789
|
-
interface TFilterConfig {
|
|
790
|
-
[key: string]: {
|
|
791
|
-
type: 'REGEX' | 'EXACT';
|
|
792
|
-
field?: string;
|
|
793
|
-
};
|
|
794
|
-
}
|
|
795
|
-
```
|
|
390
|
+
### Does it work with SQL databases?
|
|
796
391
|
|
|
797
|
-
|
|
392
|
+
Yes: `sourcePrisma`, `sourceDrizzle` (Postgres, MySQL, SQLite), or your own with `sourceDefine`. The same `dataKit` definition works with any of them.
|
|
798
393
|
|
|
799
|
-
|
|
394
|
+
### Does it need Next.js?
|
|
800
395
|
|
|
801
|
-
|
|
802
|
-
import { adapterMemory } from 'next-data-kit/server';
|
|
803
|
-
import type { TDataKitAdapter } from 'next-data-kit/types';
|
|
396
|
+
The core and `useDataKit` don't import Next.js. The registry components use `next/navigation` for the default URL source; elsewhere pass `source={{ fetch }}` or edit the copied `hook.tsx`.
|
|
804
397
|
|
|
805
|
-
|
|
806
|
-
const adapter = adapterMemory(items);
|
|
398
|
+
### Why TanStack Table 8 and not 9?
|
|
807
399
|
|
|
808
|
-
|
|
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
|
-
};
|
|
400
|
+
v8's `ColumnDef` and `useReactTable` are what the shadcn data-table, tablecn and most examples use. v9 is a new API; the registry will move once the ecosystem does.
|
|
814
401
|
|
|
815
|
-
|
|
816
|
-
adapter: myAdapter,
|
|
817
|
-
input,
|
|
818
|
-
item: doc => ({ ... }),
|
|
819
|
-
});
|
|
820
|
-
```
|
|
402
|
+
### How do I update the copied components?
|
|
821
403
|
|
|
822
|
-
|
|
404
|
+
`npx shadcn add @ndk/data-kit` again and accept the overwrite only for `components/ui/ndk/data-kit/`; check your own edits with a git diff.
|
|
823
405
|
|
|
824
|
-
|
|
406
|
+
## Migrating
|
|
825
407
|
|
|
826
|
-
|
|
408
|
+
Only a major version (12.0.0, …) breaks your code, and every one gets a section here and in [MIGRATION.md](./MIGRATION.md). To upgrade: read the section for each major you cross, `npm install next-data-kit@<version>`, refresh the components (`npx shadcn add @ndk/data-kit`, overwriting only `components/ui/ndk/data-kit/`), and typecheck: the definition, the data shape and the component props are typed, so most breaks show up as type errors.
|
|
827
409
|
|
|
828
|
-
|
|
410
|
+
### 10.x → 11.0
|
|
829
411
|
|
|
830
|
-
|
|
412
|
+
11.0 replaces per-filter zod/query pairs with declared columns, and the `DataKitRoot` parts with one `DataKit` component on TanStack Table.
|
|
831
413
|
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
414
|
+
| 10.x | 11.0 |
|
|
415
|
+
|---|---|
|
|
416
|
+
| `dataKitDefine({ adapter, filter, sort, page, item })` | `dataKit({ source, column, search, scope, sort, page, row })` |
|
|
417
|
+
| `adapterMongoose` / `adapterMemory` / custom adapter fn | `sourceMongoose` / `sourceMemory` / `sourceDefine` (+ `sourcePrisma`, `sourceDrizzle`, `sourceRest`) |
|
|
418
|
+
| `filter: { role: { schema, query } }` | `column: { role: { filter: 'select', option: [...] } }` (`query` only to override) |
|
|
419
|
+
| `filterSearch({ field })` | `search: [...]` |
|
|
420
|
+
| `sort: { field: [...], default: [{ field, direction }] }` | `sort: true` per column + `sort: 'field.desc'` |
|
|
421
|
+
| `kit.parse` + `kit.query({ input })` | `table.query({ searchParams })` (or `{ input }`) |
|
|
422
|
+
| result `{ items, total, page, sort, filter }` | `{ rows, total, page, sort, filter, search, meta }` |
|
|
423
|
+
| `<DataKitRoot>{(kit) => <DataKitTable kit={kit} columns={[{ id, head, cell }]} />}</DataKitRoot>` | `<DataKit data={data} columns={ColumnDef[]} />` |
|
|
424
|
+
| `DataKitFilter` per filter | toolbar built from `data.meta` |
|
|
425
|
+
| `DataKitSelection` | `actions` prop |
|
|
426
|
+
| `labels` on every part | `DataKitLabelsProvider` once |
|
|
838
427
|
|
|
839
|
-
|
|
428
|
+
### 9.x → 10.0
|
|
840
429
|
|
|
841
|
-
|
|
430
|
+
See [MIGRATION.md](./MIGRATION.md#migrating-from-9x-to-100).
|
|
431
|
+
|
|
432
|
+
## License
|
|
842
433
|
|
|
843
|
-
|
|
434
|
+
MIT
|