next-data-kit 10.0.0 → 12.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 +93 -3
- package/README.md +463 -96
- package/dist/chunk-A4ILIJJR.js +12 -0
- package/dist/chunk-A4ILIJJR.js.map +1 -0
- package/dist/chunk-BERW2A2B.js +123 -0
- package/dist/chunk-BERW2A2B.js.map +1 -0
- package/dist/index-j8_iNoy6.d.ts +120 -0
- package/dist/index.d.ts +13 -80
- package/dist/index.js +5 -105
- 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 +250 -78
- package/dist/server.js +308 -79
- package/dist/server.js.map +1 -1
- package/dist/source-BPO-9lNK.d.ts +70 -0
- package/dist/style.css +1 -0
- package/dist/ui.d.ts +401 -0
- package/dist/ui.js +696 -0
- package/dist/ui.js.map +1 -0
- package/package.json +62 -13
- package/registry/r/data-kit.json +71 -19
- package/registry/r/registry.json +88 -9
package/README.md
CHANGED
|
@@ -1,19 +1,41 @@
|
|
|
1
1
|
# next-data-kit
|
|
2
2
|
|
|
3
|
-
Server-
|
|
3
|
+
Server-driven data tables for 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
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
```ts
|
|
6
|
+
// ** server
|
|
7
|
+
export const tableUser = dataKit({
|
|
8
|
+
source: dataKitSourceMongoose({ model: ModelUser }),
|
|
9
|
+
column: {
|
|
10
|
+
name: { sort: true, filter: { variant: 'text' } },
|
|
11
|
+
role: { filter: { variant: 'multiSelect', option: ['admin', 'user'] } },
|
|
12
|
+
createdAt: { sort: true, filter: { variant: 'dateRange', preset: ['7d', '30d'] } },
|
|
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={[{ id: 'name', header: 'Name' }, { id: 'role', header: 'Role' }]} />
|
|
22
|
+
```
|
|
9
23
|
|
|
10
|
-
|
|
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
|
+
- **Any data source**: Mongoose, Prisma, Drizzle (any SQL dialect), REST and in-memory built in; a new database is one `dataKitSourceDefine` call. Sources work like Refine data providers.
|
|
26
|
+
- **Two ready UIs**: a styled `<DataKit>` from `next-data-kit/ui` (plain HTML and one small stylesheet, no shadcn needed), or a shadcn registry item built from your own components. Both run on the same logic hook.
|
|
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
|
+
- **No runtime dependencies**: about 1.4 kB client core, 3.3 kB server, 5.9 kB UI and 1.5 kB CSS (brotli).
|
|
11
29
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
30
|
+
## Contents
|
|
31
|
+
|
|
32
|
+
- [Install](#install)
|
|
33
|
+
- [Quick start](#quick-start): [without shadcn](#without-shadcn) · [with shadcn](#with-shadcn)
|
|
34
|
+
- [Guides](#guides): [columns](#columns) · [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) · [theming the default UI](#theming-the-default-ui)
|
|
35
|
+
- [Sources](#sources): [Mongoose](#mongoose) · [Prisma](#prisma) · [Drizzle](#drizzle) · [REST](#rest) · [memory](#memory) · [your own](#your-own-source)
|
|
36
|
+
- [Reference](#reference)
|
|
37
|
+
- [FAQ](#faq)
|
|
38
|
+
- [Migrating](#migrating)
|
|
17
39
|
|
|
18
40
|
## Install
|
|
19
41
|
|
|
@@ -21,147 +43,492 @@ Server-first pagination, filtering and sorting for React tables. You declare a t
|
|
|
21
43
|
npm install next-data-kit
|
|
22
44
|
```
|
|
23
45
|
|
|
24
|
-
Peers: `react` 19, `react-dom` 19, `zod` 4
|
|
46
|
+
Peers: `react` 19, `react-dom` 19, `zod` 4; `next` 15+ for the `next-data-kit/ui` entry; `mongoose` 8–9 or `drizzle-orm` only if you use those sources.
|
|
47
|
+
|
|
48
|
+
| Entry | What's in it |
|
|
49
|
+
|---|---|
|
|
50
|
+
| `next-data-kit/server` | `dataKit`, `dataKitFilterCustom`, the `dataKitSource*` sources, `dataKitUrlDecode` |
|
|
51
|
+
| `next-data-kit/server/drizzle` | `dataKitSourceDrizzle` (needs `drizzle-orm`) |
|
|
52
|
+
| `next-data-kit` | `useDataKit` (the state hook, framework-free), `dataKitUrlEncode`, types |
|
|
53
|
+
| `next-data-kit/ui` | `useDataKitTable` (all the view logic) and the ready UI: `DataKit`, `DataKitTable`, `DataKitToolbar`, `DataKitPagination`, `DataKitInfinite`, `DataKitActionBar`, labels |
|
|
54
|
+
| `next-data-kit/style.css` | the default UI's stylesheet |
|
|
25
55
|
|
|
26
|
-
|
|
56
|
+
## Quick start
|
|
57
|
+
|
|
58
|
+
**1. Declare the table** once, on the server (`controllers/user.ts`):
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { dataKit, dataKitSourceMongoose } from 'next-data-kit/server';
|
|
62
|
+
|
|
63
|
+
export const tableUser = dataKit({
|
|
64
|
+
source: dataKitSourceMongoose({ model: ModelUser }),
|
|
65
|
+
column: {
|
|
66
|
+
name: { sort: true, filter: { variant: 'text' } },
|
|
67
|
+
email: { sort: true },
|
|
68
|
+
role: { filter: { variant: 'multiSelect', option: ['admin', 'user', 'guest'] } },
|
|
69
|
+
age: { sort: true, filter: { variant: 'range' } },
|
|
70
|
+
active: { filter: { variant: 'boolean' } },
|
|
71
|
+
createdAt: { sort: true, filter: { variant: 'dateRange', preset: ['7d', '30d'] } },
|
|
72
|
+
},
|
|
73
|
+
search: ['name', 'email'],
|
|
74
|
+
sort: 'createdAt.desc',
|
|
75
|
+
page: { size: 20 },
|
|
76
|
+
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 }),
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
**2. Query it in the page** (server component):
|
|
81
|
+
|
|
82
|
+
```tsx
|
|
83
|
+
const Page = async (props: { searchParams: Promise<Record<string, string | string[] | undefined>> }) => <ViewUser data={await tableUser.query({ searchParams: await props.searchParams })} />;
|
|
84
|
+
export default Page;
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
**3. Render it** (client component), with either UI.
|
|
88
|
+
|
|
89
|
+
### Without shadcn
|
|
90
|
+
|
|
91
|
+
Import the stylesheet once. With Tailwind, put it in your global CSS inside the `components` layer, so your utility classes still win over it:
|
|
92
|
+
|
|
93
|
+
```css
|
|
94
|
+
@import 'tailwindcss';
|
|
95
|
+
@import 'next-data-kit/style.css' layer(components);
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Without Tailwind, import it in your root layout: `import 'next-data-kit/style.css';`.
|
|
99
|
+
|
|
100
|
+
```tsx
|
|
101
|
+
'use client';
|
|
102
|
+
|
|
103
|
+
import type { TDataKitTableData } from 'next-data-kit';
|
|
104
|
+
import { DataKit } from 'next-data-kit/ui';
|
|
105
|
+
import type { tableUser } from '@/controllers/user';
|
|
106
|
+
|
|
107
|
+
export const ViewUser = (props: { data: TDataKitTableData<typeof tableUser> }) => (
|
|
108
|
+
<DataKit
|
|
109
|
+
data={props.data}
|
|
110
|
+
columns={[
|
|
111
|
+
{ id: 'name', header: 'Name' },
|
|
112
|
+
{ id: 'email', header: 'Email' },
|
|
113
|
+
{ id: 'role', header: 'Role', filter: { option: { admin: 'Admin', user: 'User', guest: 'Guest' } } },
|
|
114
|
+
]}
|
|
115
|
+
pagination={{ size: [10, 20, 50] }}
|
|
116
|
+
/>
|
|
117
|
+
);
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### With shadcn
|
|
121
|
+
|
|
122
|
+
Add the registry to `components.json`, then the components:
|
|
27
123
|
|
|
28
124
|
```json
|
|
29
|
-
{ "registries": { "@ndk": "https://unpkg.com/next-data-kit@
|
|
125
|
+
{ "registries": { "@ndk": "https://unpkg.com/next-data-kit@12/registry/r/{name}.json" } }
|
|
30
126
|
```
|
|
31
127
|
|
|
32
128
|
```bash
|
|
33
129
|
npx shadcn add @ndk/data-kit
|
|
34
130
|
```
|
|
35
131
|
|
|
36
|
-
|
|
132
|
+
That adds `components/ui/ndk/data-kit/` (markup only, from your `table`, `popover`, `command`, `calendar`, … components, installing any you don't have yet). If shadcn asks to overwrite one of your own components, answer **No**. It works with shadcn's Radix and Base UI styles. The view is the same as above, importing `DataKit` from `@/components/ui/ndk/data-kit` instead of `next-data-kit/ui`.
|
|
133
|
+
|
|
134
|
+
Either way that's the whole table: a search box and one filter per declared column, sortable headers (`aria-sort`), pagination with real links and page sizes.
|
|
135
|
+
|
|
136
|
+
## Guides
|
|
137
|
+
|
|
138
|
+
### Columns
|
|
37
139
|
|
|
38
|
-
|
|
140
|
+
Columns are plain objects, typed from `data` (no generics to write):
|
|
141
|
+
|
|
142
|
+
```tsx
|
|
143
|
+
columns={[
|
|
144
|
+
{ id: 'name', header: 'Name' }, // ** shows row.name
|
|
145
|
+
{ id: 'role', header: 'Role', cell: ({ row }) => <Badge>{row.role}</Badge> },
|
|
146
|
+
{ id: 'age', header: 'Age', className: 'text-right tabular-nums' }, // ** on the header and the cells
|
|
147
|
+
{ id: 'status', table: false, filter: { label: 'Status', option: { online: 'Online' } } }, // ** names a filter, no table column
|
|
148
|
+
]}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
- `id` is the server column key: that's how a header knows it can sort and a filter finds its label. A column without `cell` shows the row's field with the same id as text.
|
|
152
|
+
- `filter.label` names the column's filter in the toolbar (it falls back to `header` when that's a string); `filter.option` names its option values.
|
|
153
|
+
- Columns hold functions, so write them in a client component.
|
|
154
|
+
|
|
155
|
+
### Filters
|
|
156
|
+
|
|
157
|
+
Each column's `filter.variant` fixes the operator, the URL encoding and the toolbar control, so the client never chooses how to query:
|
|
158
|
+
|
|
159
|
+
| Variant | URL | Condition | Toolbar |
|
|
160
|
+
|---|---|---|---|
|
|
161
|
+
| `text` | `?name=ada` | contains (case-insensitive) | input |
|
|
162
|
+
| `number` | `?age=30` | equals | number input |
|
|
163
|
+
| `numberCompare` | `?stock=gt.5` | the picked operator (`eq ne gt gte lt lte`) | operator + number |
|
|
164
|
+
| `range` | `?age=18-30`, `?age=18-`, `?age=-30`, `?temp=-5--2` | between / ≥ / ≤ | min–max inputs |
|
|
165
|
+
| `slider` | `?price=20-450` | between / ≥ / ≤, inside `bound` | two-thumb slider + min–max |
|
|
166
|
+
| `select` | `?role=admin` | equals one of `option` | single-choice list |
|
|
167
|
+
| `multiSelect` | `?role=admin,user` | in `option` | multi-choice list |
|
|
168
|
+
| `tags` | `?sku=A-1,B-2` | in the values (or contains any) | chip input |
|
|
169
|
+
| `boolean` | `?active=true` | equals | yes / no |
|
|
170
|
+
| `exists` | `?note=true` | has a value / is empty | has value / is empty |
|
|
171
|
+
| `date` | `?createdAt=<ms>-<ms>` | between (that day) | date picker |
|
|
172
|
+
| `dateRange` | `?createdAt=<ms>-<ms>` or `?createdAt=7d` | between, or since a `preset` | presets + from / to |
|
|
173
|
+
| `dateTimeRange` | `?at=<ms>-<ms>` or `?at=24h` | between, or since a `preset` | presets + from / to with times |
|
|
39
174
|
|
|
40
175
|
```ts
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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
|
-
});
|
|
176
|
+
column: {
|
|
177
|
+
price: { sort: true, filter: { variant: 'slider', bound: { min: 0, max: 500, step: 5 } } }, // ** bound can be async, per request
|
|
178
|
+
stock: { filter: { variant: 'numberCompare', compare: ['gt', 'lte'] } }, // ** compare: the operators offered (default all six)
|
|
179
|
+
sku: { filter: { variant: 'tags', match: 'contains', schema: z.string().max(20) } }, // ** match: 'exact' (default) or 'contains'; schema checks each value
|
|
180
|
+
note: { filter: { variant: 'exists' } },
|
|
181
|
+
updatedAt: { filter: { variant: 'dateTimeRange', preset: ['1h', '24h', '7d'] } },
|
|
182
|
+
}
|
|
57
183
|
```
|
|
58
184
|
|
|
59
|
-
-
|
|
60
|
-
-
|
|
61
|
-
- `
|
|
62
|
-
-
|
|
185
|
+
- Dates are sent as the browser's own day (or minute) boundaries, so the server never guesses a time zone; the datetime inputs show which zone they're in. `preset: ['7d', '24h']` stays relative in a shared link. A reversed range is dropped.
|
|
186
|
+
- `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 the column's `filter.option`.
|
|
187
|
+
- A slider snaps to its `step` and stays inside its `bound`; dragging back to an end leaves that side open, and the full range means no filter. It applies once you let go.
|
|
188
|
+
- Tags: Enter or a comma adds one, a pasted list adds them all, Backspace in the empty field removes the last. A value `schema` rejects is dropped.
|
|
189
|
+
- A different database field than the key: `username: { field: 'username.data', filter: { variant: 'text' } }`. Two filters can share one field (`cost: { field: 'price', filter: { variant: 'numberCompare' } }`).
|
|
190
|
+
- Filterable from the URL but not shown in the toolbar (a link from another page): `filter: { variant: 'text', hidden: true }`.
|
|
191
|
+
- Invalid values are dropped as if unset; text is capped at 200 characters and lists at 100 values. A misconfigured variant (a slider without `bound`, `compare` on a text filter, …) throws when the table is defined.
|
|
192
|
+
- 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. While you're using a filter the order holds, so its popover stays open and focus stays put.
|
|
193
|
+
- Typed values apply after a short pause (or Enter / blur), lists on click, sliders on release, dates on change. No Apply button is needed.
|
|
194
|
+
- Not built in yet: a select that searches the server as you type (for thousands of options), and counts next to options. Use `dataKitFilterCustom` with your own control in `toolbar.control` meanwhile.
|
|
63
195
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
196
|
+
### Search
|
|
197
|
+
|
|
198
|
+
`search: ['name', 'email']` adds a search box (`?search=`) that matches any of those columns. They can be columns without a filter of their own.
|
|
199
|
+
|
|
200
|
+
### Sorting
|
|
201
|
+
|
|
202
|
+
Columns with `sort: true` get a sortable header (ascending → descending → off; the default column toggles between its two directions). `sort: 'createdAt.desc'` (or a list) is the default, and anything else in `?sort=` falls back to it. Sources add a unique tie-break, so equal values keep a stable order across pages.
|
|
203
|
+
|
|
204
|
+
### Page size and counting
|
|
205
|
+
|
|
206
|
+
`page: { size: 20 }` (the max defaults to 100) or `page: { size: { default: 25, max: 25 } }`. `<DataKit pagination={{ size: [10, 25, 50] }} />` adds a rows-per-page select. A page past the end shows the last one.
|
|
207
|
+
|
|
208
|
+
Counting every match costs a query. `page: { count: 'none' }` skips it: `total` is `null` and pagination shows previous / next only.
|
|
209
|
+
|
|
210
|
+
### Scope and auth
|
|
211
|
+
|
|
212
|
+
`scope` is always applied and never read from the request: tenants, owners, soft deletes. It gets the `context` you pass to `query`:
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
scope: (props: { context: { teamId: string } }) => ({ teamId: props.context.teamId, deletedAt: null }),
|
|
216
|
+
// ** page.tsx — check auth as usual, then:
|
|
217
|
+
await tableInvoice.query({ searchParams, context: { teamId: session.teamId } });
|
|
218
|
+
```
|
|
71
219
|
|
|
72
|
-
|
|
220
|
+
It returns field → value pairs (each an equality) or a list of conditions.
|
|
221
|
+
|
|
222
|
+
### Custom filters
|
|
223
|
+
|
|
224
|
+
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:
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
type: { filter: { variant: 'select', option: ['user', 'admin'], query: (props) => (props.value === 'admin' ? { type: 'admin' } : { type: { $ne: 'admin' } }) } },
|
|
228
|
+
status: { filter: { variant: 'select', option: ['online'], query: async () => ({ _id: { $in: await ModelSession.distinct('userId', { expiresAt: { $gt: new Date() } }) } }) } },
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
For a filter with no toolbar control at all, `dataKitFilterCustom` takes a zod schema and types `value` from it:
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
user: { filter: dataKitFilterCustom({ schema: z.string().regex(/^[a-f\d]{24}$/i), query: (props) => ({ userId: props.value }) }) },
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
### The row shape
|
|
238
|
+
|
|
239
|
+
`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 (`dataKitSourceMongoose({ model, select: '-password' })`). In development a warning shows when a row has no string `id` or carries an `ObjectId`. Reuse the types with `TDataKitTableRow<typeof tableUser>` and `TDataKitTableData<typeof tableUser>`.
|
|
240
|
+
|
|
241
|
+
### Selection and bulk actions
|
|
73
242
|
|
|
74
243
|
```tsx
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
244
|
+
<DataKit
|
|
245
|
+
data={data}
|
|
246
|
+
columns={columns}
|
|
247
|
+
selection={{
|
|
248
|
+
enabled: ({ row }) => row.id !== currentUserId, // ** optional: which rows can be picked
|
|
249
|
+
action: (selection) => <Button onClick={() => aUsersDelete({ ids: selection.rows.map((row) => row.id) }).then(selection.clear)}>Delete</Button>,
|
|
250
|
+
}}
|
|
251
|
+
/>
|
|
79
252
|
```
|
|
80
253
|
|
|
81
|
-
|
|
254
|
+
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"` in a portal, the count is announced to screen readers, and **Escape** clears the selection. The header checkbox only picks rows `enabled` allows. Rows that disappear (deleted, filtered out) leave the selection on their own. Two tables' bars stack instead of overlapping.
|
|
255
|
+
|
|
256
|
+
### Row actions
|
|
257
|
+
|
|
258
|
+
Put a dropdown in a cell. 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.
|
|
82
259
|
|
|
83
|
-
|
|
260
|
+
### Your own controls
|
|
261
|
+
|
|
262
|
+
`toolbar={{ control }}` adds anything to the end of the toolbar; a falsy value renders nothing:
|
|
84
263
|
|
|
85
264
|
```tsx
|
|
86
|
-
|
|
265
|
+
<DataKit data={data} columns={columns} toolbar={{ control: data.filter.user && <Link href="?">One user only ✕</Link> }} />
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
`toolbar={false}` and `pagination={false}` hide those parts (e.g. a "latest 5" card).
|
|
87
269
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
<
|
|
97
|
-
<
|
|
98
|
-
|
|
99
|
-
|
|
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>
|
|
270
|
+
### Your own layout
|
|
271
|
+
|
|
272
|
+
`useDataKitTable` (from `next-data-kit/ui`) returns the table ready to render; every part takes it:
|
|
273
|
+
|
|
274
|
+
```tsx
|
|
275
|
+
const table = useDataKitTable({ data, columns });
|
|
276
|
+
return (
|
|
277
|
+
<Fragment>
|
|
278
|
+
<DataKitToolbar table={table} />
|
|
279
|
+
<div className="grid grid-cols-3 gap-4">{table.row.map((item) => <Card key={item.id} user={item.row} />)}</div>
|
|
280
|
+
<DataKitPagination table={table} />
|
|
281
|
+
</Fragment>
|
|
106
282
|
);
|
|
107
283
|
```
|
|
108
284
|
|
|
109
|
-
|
|
285
|
+
| `table.` | |
|
|
286
|
+
|---|---|
|
|
287
|
+
| `header` | `{ id, content, className, sort: { can, direction, aria, toggle } }[]` |
|
|
288
|
+
| `row` | `{ id, row, selected, disabled, toggle, cell: { id, content, className }[] }[]` |
|
|
289
|
+
| `filter` | `list` (`{ id, variant, label, option, preset, state, set, clear }[]`, active first), `active`, `reset` |
|
|
290
|
+
| `selection` | `active` (rows can be picked at all), `rows`, `count`, `clear`, `page: { checked, indeterminate, toggle }` |
|
|
291
|
+
| `page` | `number`, `count`, `next`, `total`, `size: { value, set }`, `list` (`[1, 'gap', 4, 5, 6, 'gap', 20]`), `link(page, enabled?)` (real link props) |
|
|
292
|
+
| `kit` | `useDataKit`'s state: `set.filter`, `set.sort`, `reset`, `refresh`, `row.update`, … |
|
|
110
293
|
|
|
111
|
-
|
|
294
|
+
### Infinite scroll
|
|
112
295
|
|
|
113
|
-
|
|
296
|
+
Infinite scroll fetches from the browser, so it needs a server action. **Check auth in it**: a server action is a public endpoint.
|
|
114
297
|
|
|
115
298
|
```ts
|
|
116
299
|
'use server';
|
|
300
|
+
export const aUserList = async (input: unknown) => tableUser.query({ input, context: await authContext() });
|
|
301
|
+
```
|
|
117
302
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
}
|
|
303
|
+
```tsx
|
|
304
|
+
const table = useDataKitTable({ data, source: { fetch: aUserList }, append: true });
|
|
305
|
+
// ** …render table.row, then:
|
|
306
|
+
<DataKitInfinite table={table} />
|
|
122
307
|
```
|
|
123
308
|
|
|
309
|
+
Answers that arrive out of order are dropped. `source: { fetch, url: true }` keeps the state in the URL too.
|
|
310
|
+
|
|
311
|
+
### Several tables on one page
|
|
312
|
+
|
|
313
|
+
Give each `query` its own `prefix`. It comes back in the data, so the views don't repeat it:
|
|
314
|
+
|
|
124
315
|
```tsx
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
316
|
+
const users = await tableUser.query({ searchParams, prefix: 'user' });
|
|
317
|
+
const logs = await tableLog.query({ searchParams, prefix: 'log' });
|
|
318
|
+
// ** ?user.page=2&user.role=admin&log.sort=createdAt.desc
|
|
319
|
+
<DataKit data={users} columns={…} />
|
|
320
|
+
<DataKit data={logs} columns={…} />
|
|
129
321
|
```
|
|
130
322
|
|
|
131
|
-
|
|
323
|
+
Each table only reads and writes its own params and keeps everything else in the URL. A prefix uses `a-z`, `0-9` and `-`; a column key can't contain `.`. In development, two tables on one page with the same prefix (or none) log a warning.
|
|
132
324
|
|
|
133
|
-
|
|
325
|
+
### Exports
|
|
326
|
+
|
|
327
|
+
Reuse the definition with a server-only page size (it ignores `max`):
|
|
134
328
|
|
|
135
329
|
```ts
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
//
|
|
139
|
-
|
|
330
|
+
export const aUsersExport = action.schema(tableUser.schema).action(async ({ parsedInput }) => {
|
|
331
|
+
const { rows } = await tableUser.query({ input: { ...parsedInput, page: { number: 1, size: parsedInput.page.size } }, page: { size: 10_000 } });
|
|
332
|
+
// ** …build the CSV
|
|
333
|
+
});
|
|
140
334
|
```
|
|
141
335
|
|
|
142
|
-
|
|
336
|
+
### Translations
|
|
337
|
+
|
|
338
|
+
Set every label once, near the root (for example inside your i18n provider):
|
|
339
|
+
|
|
340
|
+
```tsx
|
|
341
|
+
<DataKitLabelsProvider
|
|
342
|
+
labels={{
|
|
343
|
+
pagination: { previous: t('previous'), next: t('next') },
|
|
344
|
+
filter: { reset: t('reset') },
|
|
345
|
+
date: { preset: (value) => t('lastDays', { days: value.slice(0, -1) }), format: (date) => format.dateTime(date, { dateStyle: 'medium' }) },
|
|
346
|
+
}}
|
|
347
|
+
>
|
|
348
|
+
{children}
|
|
349
|
+
</DataKitLabelsProvider>
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
`<DataKit labels={…}>` overrides them for one table, e.g. `pagination.summary` or `table.empty`. Column and option names come from your columns (`header`, `filter.label`, `filter.option`). Pass your i18n formatter as `date.format` (and `date.formatTime` / `date.formatClock` for date-and-time filters), so the server and the browser print a picked date the same way. The other new strings are `compare` (each operator's symbol and spoken name), `exists`, `tags` and `date.zone`. The provider and `dataKitLabels` (the English defaults) come from `next-data-kit/ui` and serve both UIs.
|
|
353
|
+
|
|
354
|
+
### Theming the default UI
|
|
355
|
+
|
|
356
|
+
Every part has a `data-slot` (`data-kit`, `data-kit-toolbar`, `data-kit-filter`, `data-kit-table`, `data-kit-row`, `data-kit-pagination`, `data-kit-action-bar`, …) and a `data-state` where it has one. The stylesheet only uses `:where()` selectors in its own `ndk` layer, so any style of yours wins. Colors come from variables:
|
|
357
|
+
|
|
358
|
+
```css
|
|
359
|
+
[data-slot='data-kit'],
|
|
360
|
+
[data-slot='data-kit-action-bar'] {
|
|
361
|
+
--ndk-background: #fff;
|
|
362
|
+
--ndk-foreground: #111;
|
|
363
|
+
--ndk-border: #e5e5e5;
|
|
364
|
+
--ndk-radius: 0.375rem;
|
|
365
|
+
}
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
The defaults are system colors that follow the page's `color-scheme`, so dark mode works with no extra CSS. `.dark` or `[data-theme="dark"]` on any ancestor (next-themes) also switches it.
|
|
369
|
+
|
|
370
|
+
## Sources
|
|
371
|
+
|
|
372
|
+
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 }`.
|
|
373
|
+
|
|
374
|
+
### Mongoose
|
|
375
|
+
|
|
376
|
+
```ts
|
|
377
|
+
dataKitSourceMongoose({ model: ModelUser }); // ** .lean() plain objects
|
|
378
|
+
dataKitSourceMongoose({ model: ModelUser, hydrate: true }); // ** documents with methods (row: (props) => props.row.onClient())
|
|
379
|
+
dataKitSourceMongoose({ model: ModelUser, select: '-password' });
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
Imports mongoose for types only, so it always uses your app's mongoose. `contains` is an escaped, case-insensitive regex.
|
|
383
|
+
|
|
384
|
+
### Prisma
|
|
385
|
+
|
|
386
|
+
```ts
|
|
387
|
+
dataKitSourcePrisma({ model: prisma.user });
|
|
388
|
+
dataKitSourcePrisma({ model: prisma.user, select: { id: true, name: true }, insensitive: false }); // ** insensitive: false on MySQL / SQLite
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
Any model delegate; Prisma isn't imported. Nested fields (`author.name`) become relation filters.
|
|
392
|
+
|
|
393
|
+
### Drizzle
|
|
394
|
+
|
|
395
|
+
```ts
|
|
396
|
+
import { dataKitSourceDrizzle } from 'next-data-kit/server/drizzle';
|
|
397
|
+
|
|
398
|
+
dataKitSourceDrizzle({ db, table: users }); // ** Postgres (ilike)
|
|
399
|
+
dataKitSourceDrizzle({ db, table: users, dialect: 'sqlite' }); // ** or 'mysql' (like)
|
|
400
|
+
```
|
|
143
401
|
|
|
144
|
-
|
|
402
|
+
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).
|
|
145
403
|
|
|
146
|
-
|
|
404
|
+
### REST
|
|
405
|
+
|
|
406
|
+
```ts
|
|
407
|
+
dataKitSourceRest<TRepo>({ url: 'https://api.example.com/repos', request: { headers: { authorization: `Bearer ${token}` } } });
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
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.
|
|
411
|
+
|
|
412
|
+
### Memory
|
|
413
|
+
|
|
414
|
+
`dataKitSourceMemory({ rows })`, for tests, fixtures and small static lists.
|
|
415
|
+
|
|
416
|
+
### Your own source
|
|
417
|
+
|
|
418
|
+
Map the 11 operators to your query language once; `list` runs the query:
|
|
419
|
+
|
|
420
|
+
```ts
|
|
421
|
+
import { dataKitSourceDefine } from 'next-data-kit/server';
|
|
422
|
+
|
|
423
|
+
export const dataKitSourceKysely = <TRow>(props: { db: Kysely<TDatabase>; table: keyof TDatabase }) =>
|
|
424
|
+
dataKitSourceDefine<TRow, Expression<SqlBool>>({
|
|
425
|
+
operator: {
|
|
426
|
+
eq: (props) => sql`${sql.ref(props.field)} = ${props.value}`,
|
|
427
|
+
contains: (props) => sql`${sql.ref(props.field)} ilike ${`%${String(props.value).replace(/[\\%_]/g, '\\$&')}%`}`,
|
|
428
|
+
between: (props) => sql`${sql.ref(props.field)} between ${props.value[0]} and ${props.value[1]}`,
|
|
429
|
+
// ** …ne, lt, lte, gt, gte, in, nin, null
|
|
430
|
+
},
|
|
431
|
+
and: (list) => sql.join(list, sql` and `),
|
|
432
|
+
or: (list) => sql`(${sql.join(list, sql` or `)})`,
|
|
433
|
+
list: async (props) => {
|
|
434
|
+
const query = props.db.selectFrom(table).$if(Boolean(props.where), (query) => query.where(props.where!));
|
|
435
|
+
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]);
|
|
436
|
+
return { rows, total: total ? Number(total.count) : null };
|
|
437
|
+
},
|
|
438
|
+
});
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
To keep a built-in translation but run your own query (an aggregate, a join), spread its operators: `dataKitSourceDefine({ ...dataKitSourceMongooseQuery, 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.
|
|
442
|
+
|
|
443
|
+
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.
|
|
444
|
+
|
|
445
|
+
## Reference
|
|
446
|
+
|
|
447
|
+
### `dataKit(definition)` · `next-data-kit/server`
|
|
448
|
+
|
|
449
|
+
| Option | Default | |
|
|
450
|
+
|---|---|---|
|
|
451
|
+
| `source` | required | A built-in source, `dataKitSourceDefine(…)` or `{ list }`. |
|
|
452
|
+
| `column` | required | `{ [key]: { field?, sort?, filter?: { variant, option?, preset?, query?, hidden? } \| dataKitFilterCustom(…) } }` |
|
|
453
|
+
| `search` | none | Column keys the search box looks in. |
|
|
454
|
+
| `scope` | none | `(props: { context }) => pairs \| conditions`, always applied. |
|
|
455
|
+
| `sort` | none | `'field.direction'` or a list. |
|
|
456
|
+
| `page` | `{ size: 20 }` | `size`: number or `{ default, max }`; `count: 'exact' \| 'none'`. |
|
|
457
|
+
| `row` | required | `(props: { row }) => row` with a string `id`. |
|
|
458
|
+
|
|
459
|
+
`tableX.query({ searchParams, prefix?, context?, page? })` or `({ input, prefix?, context?, page? })` returns `{ rows, total, page, sort, filter, search, prefix, meta }`. `tableX.schema` validates an action's input. Also exported: `dataKitFilterCustom`, `dataKitSourceDefine`, `dataKitSourceMongoose`, `dataKitSourceMongooseQuery`, `dataKitSourcePrisma`, `dataKitSourceRest`, `dataKitSourceMemory`, `dataKitUrlEncode`, `dataKitUrlDecode`, and the `TDataKit*` types; `dataKitSourceDrizzle` from `next-data-kit/server/drizzle`.
|
|
460
|
+
|
|
461
|
+
### UI · `next-data-kit/ui` and `components/ui/ndk/data-kit/`
|
|
462
|
+
|
|
463
|
+
Both UIs export the same components with the same props.
|
|
464
|
+
|
|
465
|
+
| | Props |
|
|
466
|
+
|---|---|
|
|
467
|
+
| `DataKit` | `data`, `columns`, `source?`, `refetch?: { intervalMs }`, `selection?: { enabled?, action? }`, `row?: { onClick }`, `toolbar?: boolean \| { control }`, `pagination?: boolean \| { size }`, `labels?`, `className?` |
|
|
468
|
+
| `useDataKitTable` | `data`, `columns?`, `source?`, `append?`, `refetch?`, `selection?: { enabled? }` → `table` (see [your own layout](#your-own-layout)) |
|
|
469
|
+
| `DataKitToolbar` · `DataKitTable` · `DataKitPagination` · `DataKitInfinite` · `DataKitActionBar` | `table` (+ `children` / `row` / `size`) |
|
|
470
|
+
| `DataKitLabelsProvider` | `labels`, `children` (from `next-data-kit/ui`) |
|
|
471
|
+
|
|
472
|
+
Column: `{ id, header?, cell?, className?, filter?: { label?, option? }, table?: false }`.
|
|
473
|
+
|
|
474
|
+
### URL
|
|
475
|
+
|
|
476
|
+
`?page=2&size=20&sort=name.asc&search=ada&role=admin,user&age=18-30&createdAt=7d`. With a prefix, every param is prefixed (`?user.page=2`). Page 1 is left out.
|
|
147
477
|
|
|
148
478
|
## FAQ
|
|
149
479
|
|
|
150
|
-
### Is it safe to
|
|
480
|
+
### Is it safe to put sort and filters in the URL?
|
|
481
|
+
|
|
482
|
+
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.
|
|
483
|
+
|
|
484
|
+
### Does it work with SQL databases?
|
|
485
|
+
|
|
486
|
+
Yes: `dataKitSourcePrisma`, `dataKitSourceDrizzle` (Postgres, MySQL, SQLite), or your own with `dataKitSourceDefine`. The same `dataKit` definition works with any of them.
|
|
151
487
|
|
|
152
|
-
|
|
488
|
+
### Do I need shadcn?
|
|
489
|
+
|
|
490
|
+
No. `next-data-kit/ui` with `next-data-kit/style.css` is a complete UI in plain HTML. The shadcn registry is the same table built from your shadcn components, if you'd rather match them.
|
|
153
491
|
|
|
154
492
|
### Does it need Next.js?
|
|
155
493
|
|
|
156
|
-
The
|
|
494
|
+
The server entries and `useDataKit` don't import Next.js. `next-data-kit/ui` (and the registry) use `next/navigation` for the default URL source. Elsewhere, use `useDataKit` with `source={{ fetch }}` and your own markup.
|
|
495
|
+
|
|
496
|
+
### Why don't my Tailwind classes apply to the default UI?
|
|
497
|
+
|
|
498
|
+
A stylesheet imported after Tailwind declares its layer later, and a later layer wins. Import it with `@import 'next-data-kit/style.css' layer(components);` in your global CSS (see [without shadcn](#without-shadcn)).
|
|
499
|
+
|
|
500
|
+
### How do I update the copied components?
|
|
501
|
+
|
|
502
|
+
`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.
|
|
503
|
+
|
|
504
|
+
## Migrating
|
|
505
|
+
|
|
506
|
+
Only a major version (13.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 if you use the registry, and typecheck: the definition, the data shape and the component props are typed, so most breaks show up as type errors.
|
|
507
|
+
|
|
508
|
+
### 11.x → 12.0
|
|
509
|
+
|
|
510
|
+
12.0 drops TanStack Table, adds a ready UI that needs no shadcn (`next-data-kit/ui` + `style.css`), puts every export under the `dataKit` name, and nests each column's filter options.
|
|
157
511
|
|
|
158
|
-
|
|
512
|
+
| 11.x | 12.0 |
|
|
513
|
+
|---|---|
|
|
514
|
+
| `sourceMongoose`, `sourceDefine`, `sourcePrisma`, … | `dataKitSourceMongoose`, `dataKitSourceDefine`, `dataKitSourcePrisma`, … |
|
|
515
|
+
| `filterCustom`, `urlEncode`, `urlDecode` | `dataKitFilterCustom`, `dataKitUrlEncode`, `dataKitUrlDecode` |
|
|
516
|
+
| `name: { filter: 'text', option, preset, query, hidden }` | `name: { filter: { variant: 'text', option, preset, query, hidden } }` |
|
|
517
|
+
| `query({ searchParams, key })` + `<DataKit dataKey>` | `query({ searchParams, prefix })` only |
|
|
518
|
+
| `TDataKitRow` / `TDataKitDataOf` | `TDataKitTableRow` / `TDataKitTableData` |
|
|
519
|
+
| TanStack `ColumnDef`: `accessorKey`, `cell: ({ row }) => row.original.x`, `meta: { className, label, option }` | `{ id, cell: ({ row }) => row.x, className, filter: { label, option } }` |
|
|
520
|
+
| `hidden={['status']}` | `{ id: 'status', table: false }` |
|
|
521
|
+
| `selectable`, `actions` | `selection={{ enabled, action }}` |
|
|
522
|
+
| `controls`, `sizes` | `toolbar={{ control }}`, `pagination={{ size }}` |
|
|
523
|
+
| `useDataKitTable` from the registry → TanStack `table` | from `next-data-kit/ui` → `table.header`, `table.row`, `table.filter`, `table.page` |
|
|
524
|
+
| `DataKitTableView` | `DataKitTable` |
|
|
525
|
+
| `kit.set.page(n)`, `kit.set.size(n)` | `kit.set.page.number(n)`, `kit.set.page.size(n)` |
|
|
159
526
|
|
|
160
|
-
|
|
527
|
+
Step by step, with before/after snippets: [MIGRATION.md](./MIGRATION.md#migrating-from-11x-to-120).
|
|
161
528
|
|
|
162
|
-
###
|
|
529
|
+
### 10.x → 11.0 and 9.x → 10.0
|
|
163
530
|
|
|
164
|
-
See [MIGRATION.md](./MIGRATION.md).
|
|
531
|
+
See [MIGRATION.md](./MIGRATION.md#migrating-from-10x-to-110).
|
|
165
532
|
|
|
166
533
|
## License
|
|
167
534
|
|