next-data-kit 10.0.0 → 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 +35 -3
- package/README.md +360 -94
- package/dist/chunk-5D747NEB.js +12 -0
- package/dist/chunk-5D747NEB.js.map +1 -0
- package/dist/index.d.ts +53 -22
- package/dist/index.js +44 -33
- 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 +227 -74
- package/dist/server.js +247 -71
- package/dist/server.js.map +1 -1
- package/dist/source--l-z9HHB.d.ts +60 -0
- package/package.json +31 -9
- package/registry/r/data-kit.json +35 -19
- package/registry/r/registry.json +58 -9
package/MIGRATION.md
CHANGED
|
@@ -1,8 +1,40 @@
|
|
|
1
|
-
# Migrating
|
|
1
|
+
# Migrating
|
|
2
|
+
|
|
3
|
+
## Migrating from 10.x to 11.0
|
|
4
|
+
|
|
5
|
+
11.0 declares a table as columns instead of per-filter zod/query pairs, plugs in any data source, and renders it with one `DataKit` component on TanStack Table 8.
|
|
6
|
+
|
|
7
|
+
### Steps
|
|
8
|
+
|
|
9
|
+
1. `npm install next-data-kit@11` (needs zod 4, React 19).
|
|
10
|
+
2. Refresh the components: `npx shadcn add @ndk/data-kit`, overwriting only `components/ui/ndk/data-kit/`. Delete the old `root.tsx`, `table.tsx`, `filter.tsx` and `selection.tsx` there.
|
|
11
|
+
3. Rewrite each `dataKitDefine` as a `dataKit`:
|
|
12
|
+
- `adapter: adapterMongoose({ model })` → `source: sourceMongoose({ model })`; a custom adapter function → `sourceDefine({ ...sourceMongooseQuery, list })` or `{ list }`, which gets `{ filter, sort, page: { offset, limit, count } }` and returns `{ rows, total }`.
|
|
13
|
+
- Each `filter: { key: { schema, query } }` → `column: { key: { filter: variant, option? } }`. Keep `query` on the column only when the variant's own condition isn't the one you need; use `filterCustom({ schema, query })` for a filter with no toolbar control.
|
|
14
|
+
- `filterSearch({ field })` → `search: [...]` (add columns for those fields, with `field` when the database path differs).
|
|
15
|
+
- `sort: { field, default }` → `sort: true` on each sortable column, and `sort: 'field.desc'` at the top.
|
|
16
|
+
- `page.size` and `scope` stay; `item: (props) => …props.document…` → `row: (props) => …props.row…`.
|
|
17
|
+
4. In pages, `kit.query({ input: kit.parse({ searchParams }) })` → `table.query({ searchParams })`. Server actions keep `{ input }`; validate with `table.schema`.
|
|
18
|
+
5. In views, replace `DataKitRoot` + parts with `<DataKit data={data} columns={…} />`. Columns become TanStack `ColumnDef`s (`head` → `header`, `cell: ({ item })` → `cell: ({ row }) => row.original…`, `className` → `meta: { className }`), and the column `id` / `accessorKey` must match the server column key for sorting and filter labels. `DataKitSelection` → `actions`; per-part labels → one `DataKitLabelsProvider`.
|
|
19
|
+
6. URLs change: filter values are variant-encoded (`role=a,b`, `age=18-30`, `createdAt=7d`) and sort is `column.direction`. Old links fall back to the defaults.
|
|
20
|
+
|
|
21
|
+
### Renames
|
|
22
|
+
|
|
23
|
+
| 10.x | 11.0 |
|
|
24
|
+
|---|---|
|
|
25
|
+
| `dataKitDefine` | `dataKit` |
|
|
26
|
+
| `adapterMongoose`, `adapterMemory` | `sourceMongoose`, `sourceMemory` |
|
|
27
|
+
| `filterSearch` | `search` option |
|
|
28
|
+
| `kit.parse` | removed (`query({ searchParams })`) |
|
|
29
|
+
| `items`, `item()` | `rows`, `row()` |
|
|
30
|
+
| `TDataKitResult` | `TDataKitData` (+ `TDataKitRow`, `TDataKitDataOf`) |
|
|
31
|
+
| `DataKitRoot`, `DataKitTable`, `DataKitFilter`, `DataKitSelection`, `useDataKitRoot` | `DataKit`, `useDataKitTable`, `DataKitToolbar`, `DataKitTableView`, `DataKitPagination`, `DataKitInfinite`, `DataKitLabelsProvider` |
|
|
32
|
+
|
|
33
|
+
## Migrating from 9.x to 10.0
|
|
2
34
|
|
|
3
35
|
10.0 is a rewrite. Tables are declared once on the server with only the filters and sorts you allow; the UI moves into your project as a shadcn registry item; the package ships no CSS and no Radix.
|
|
4
36
|
|
|
5
|
-
|
|
37
|
+
### What changes
|
|
6
38
|
|
|
7
39
|
| 9.x | 10.0 |
|
|
8
40
|
|---|---|
|
|
@@ -33,7 +65,7 @@
|
|
|
33
65
|
| peers: Radix, `cva`, `lucide-react`, zod 3 | peers: `react` 19, `react-dom` 19, `zod` 4, optional `mongoose` |
|
|
34
66
|
| CommonJS build | ESM only |
|
|
35
67
|
|
|
36
|
-
|
|
68
|
+
### Steps
|
|
37
69
|
|
|
38
70
|
1. `npm install next-data-kit@10` and remove `@radix-ui/*`, `class-variance-authority` and `react-intersection-observer` if only next-data-kit used them.
|
|
39
71
|
2. Add `"@ndk": "https://unpkg.com/next-data-kit@10/registry/r/{name}.json"` to `registries` in `components.json`, then `npx shadcn add @ndk/data-kit`.
|
package/README.md
CHANGED
|
@@ -1,19 +1,42 @@
|
|
|
1
1
|
# next-data-kit
|
|
2
2
|
|
|
3
|
-
Server-
|
|
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
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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
|
+
```
|
|
9
18
|
|
|
10
|
-
|
|
19
|
+
```tsx
|
|
20
|
+
// ** client
|
|
21
|
+
<DataKit data={data} columns={[{ accessorKey: 'name', header: 'Name' }, { accessorKey: 'role', header: 'Role' }]} />
|
|
22
|
+
```
|
|
11
23
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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).
|
|
30
|
+
|
|
31
|
+
## Contents
|
|
32
|
+
|
|
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)
|
|
17
40
|
|
|
18
41
|
## Install
|
|
19
42
|
|
|
@@ -21,147 +44,390 @@ Server-first pagination, filtering and sorting for React tables. You declare a t
|
|
|
21
44
|
npm install next-data-kit
|
|
22
45
|
```
|
|
23
46
|
|
|
24
|
-
Peers: `react` 19, `react-dom` 19, `zod` 4
|
|
47
|
+
Peers: `react` 19, `react-dom` 19, `zod` 4; `mongoose` 8–9 or `drizzle-orm` only if you use those sources.
|
|
25
48
|
|
|
26
|
-
Add the registry to `components.json`, then
|
|
49
|
+
Add the registry to `components.json`, then the components:
|
|
27
50
|
|
|
28
51
|
```json
|
|
29
|
-
{ "registries": { "@ndk": "https://unpkg.com/next-data-kit@
|
|
52
|
+
{ "registries": { "@ndk": "https://unpkg.com/next-data-kit@11/registry/r/{name}.json" } }
|
|
30
53
|
```
|
|
31
54
|
|
|
32
55
|
```bash
|
|
33
56
|
npx shadcn add @ndk/data-kit
|
|
34
57
|
```
|
|
35
58
|
|
|
36
|
-
|
|
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.
|
|
60
|
+
|
|
61
|
+
## Quick start
|
|
37
62
|
|
|
38
|
-
|
|
63
|
+
**1. Declare the table** once, on the server (`controllers/user.ts`):
|
|
39
64
|
|
|
40
65
|
```ts
|
|
41
|
-
import {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
66
|
+
import { dataKit, sourceMongoose } from 'next-data-kit/server';
|
|
67
|
+
|
|
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 },
|
|
52
77
|
},
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
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 }),
|
|
56
82
|
});
|
|
57
83
|
```
|
|
58
84
|
|
|
59
|
-
|
|
60
|
-
- A filter's `query` may be async, for example to look up ids in another collection first.
|
|
61
|
-
- `item` must return plain JSON with a string `id`. In development a warning is logged when it doesn't.
|
|
62
|
-
- An `_id` tie-break is added to every Mongoose sort, so ties stay in a stable order.
|
|
85
|
+
**2. Query it in the page** (server component):
|
|
63
86
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
| `filter` | `{}` | Undeclared keys are dropped. |
|
|
69
|
-
| `sort.field` | `[]` | Allowed sort fields; anything else falls back to `sort.default`. |
|
|
70
|
-
| `page.size` | `20` / max `100` | Larger requests are capped at `max`. |
|
|
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;
|
|
90
|
+
```
|
|
71
91
|
|
|
72
|
-
|
|
92
|
+
**3. Render it** (client component):
|
|
73
93
|
|
|
74
94
|
```tsx
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
};
|
|
95
|
+
'use client';
|
|
96
|
+
|
|
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]} />;
|
|
79
109
|
```
|
|
80
110
|
|
|
81
|
-
|
|
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.
|
|
112
|
+
|
|
113
|
+
## Guides
|
|
114
|
+
|
|
115
|
+
### Filters
|
|
116
|
+
|
|
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:
|
|
118
|
+
|
|
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 |
|
|
129
|
+
|
|
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.
|
|
136
|
+
|
|
137
|
+
### Search
|
|
138
|
+
|
|
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.
|
|
82
140
|
|
|
83
|
-
|
|
141
|
+
### Sorting
|
|
142
|
+
|
|
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.
|
|
144
|
+
|
|
145
|
+
### Page size and counting
|
|
146
|
+
|
|
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.
|
|
148
|
+
|
|
149
|
+
Counting every match costs a query. `page: { count: 'none' }` skips it: `total` is `null` and pagination shows previous / next only.
|
|
150
|
+
|
|
151
|
+
### Scope and auth
|
|
152
|
+
|
|
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 } });
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
It returns field → value pairs (each an equality) or a list of conditions.
|
|
162
|
+
|
|
163
|
+
### Custom filters
|
|
164
|
+
|
|
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:
|
|
166
|
+
|
|
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
|
+
```
|
|
171
|
+
|
|
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 }) }) },
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### The row shape
|
|
179
|
+
|
|
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>`.
|
|
181
|
+
|
|
182
|
+
### Selection and bulk actions
|
|
84
183
|
|
|
85
184
|
```tsx
|
|
86
|
-
|
|
185
|
+
<DataKit
|
|
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
|
+
/>
|
|
191
|
+
```
|
|
192
|
+
|
|
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>`.
|
|
194
|
+
|
|
195
|
+
### Row actions
|
|
87
196
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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.
|
|
198
|
+
|
|
199
|
+
### Your own controls
|
|
200
|
+
|
|
201
|
+
`controls` adds anything to the end of the toolbar; a falsy value renders nothing:
|
|
202
|
+
|
|
203
|
+
```tsx
|
|
204
|
+
<DataKit data={data} columns={columns} controls={data.filter.user && <Link href="?">One user only ✕</Link>} />
|
|
205
|
+
```
|
|
206
|
+
|
|
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:
|
|
212
|
+
|
|
213
|
+
```tsx
|
|
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>
|
|
106
221
|
);
|
|
107
222
|
```
|
|
108
223
|
|
|
109
|
-
|
|
224
|
+
The kit is on `table.options.meta.dataKit` (`set.filter`, `set.sort`, `reset`, `row.update`, `selection`, …).
|
|
110
225
|
|
|
111
|
-
|
|
226
|
+
### Infinite scroll
|
|
112
227
|
|
|
113
|
-
|
|
228
|
+
Infinite scroll fetches from the browser, so it needs a server action. **Check auth in it**: a server action is a public endpoint.
|
|
114
229
|
|
|
115
230
|
```ts
|
|
116
231
|
'use server';
|
|
232
|
+
export const aUserList = async (input: unknown) => tableUser.query({ input, context: await authContext() });
|
|
233
|
+
```
|
|
117
234
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
}
|
|
235
|
+
```tsx
|
|
236
|
+
const table = useDataKitTable({ data, columns: [], source: { fetch: aUserList }, append: true });
|
|
237
|
+
// ** …render table.getRowModel().rows, then:
|
|
238
|
+
<DataKitInfinite table={table} />
|
|
122
239
|
```
|
|
123
240
|
|
|
241
|
+
Answers that arrive out of order are dropped. `source: { fetch, url: true }` keeps the state in the URL too.
|
|
242
|
+
|
|
243
|
+
### Several tables on one page
|
|
244
|
+
|
|
124
245
|
```tsx
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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
|
+
```
|
|
252
|
+
|
|
253
|
+
### Exports
|
|
254
|
+
|
|
255
|
+
Reuse the definition with a server-only page size (it ignores `max`):
|
|
256
|
+
|
|
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
|
|
261
|
+
});
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
### Translations
|
|
265
|
+
|
|
266
|
+
Set every label once, near the root (for example inside your i18n provider):
|
|
267
|
+
|
|
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>
|
|
270
|
+
```
|
|
271
|
+
|
|
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`).
|
|
273
|
+
|
|
274
|
+
### React Compiler
|
|
275
|
+
|
|
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)).
|
|
277
|
+
|
|
278
|
+
## Sources
|
|
279
|
+
|
|
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 }`.
|
|
281
|
+
|
|
282
|
+
### Mongoose
|
|
283
|
+
|
|
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' });
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
Imports mongoose for types only, so it always uses your app's mongoose. `contains` is an escaped, case-insensitive regex.
|
|
291
|
+
|
|
292
|
+
### Prisma
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
sourcePrisma({ model: prisma.user });
|
|
296
|
+
sourcePrisma({ model: prisma.user, select: { id: true, name: true }, insensitive: false }); // ** insensitive: false on MySQL / SQLite
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
Any model delegate; Prisma isn't imported. Nested fields (`author.name`) become relation filters.
|
|
300
|
+
|
|
301
|
+
### Drizzle
|
|
302
|
+
|
|
303
|
+
```ts
|
|
304
|
+
import { sourceDrizzle } from 'next-data-kit/server/drizzle';
|
|
305
|
+
|
|
306
|
+
sourceDrizzle({ db, table: users }); // ** Postgres (ilike)
|
|
307
|
+
sourceDrizzle({ db, table: users, dialect: 'sqlite' }); // ** or 'mysql' (like)
|
|
129
308
|
```
|
|
130
309
|
|
|
131
|
-
|
|
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).
|
|
132
311
|
|
|
133
|
-
|
|
312
|
+
### REST
|
|
134
313
|
|
|
135
314
|
```ts
|
|
136
|
-
|
|
137
|
-
// kit.items · kit.total · kit.page.{number,size,count} · kit.sort · kit.filter · kit.state.{isPending,error}
|
|
138
|
-
// kit.set.{page,size,sort,filter} · kit.refresh() · kit.reset()
|
|
139
|
-
// kit.item.{push,update,remove} · kit.selection.{ids,has,toggle,all,clear}
|
|
315
|
+
sourceRest<TRepo>({ url: 'https://api.example.com/repos', request: { headers: { authorization: `Bearer ${token}` } } });
|
|
140
316
|
```
|
|
141
317
|
|
|
142
|
-
|
|
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.
|
|
319
|
+
|
|
320
|
+
### Memory
|
|
321
|
+
|
|
322
|
+
`sourceMemory({ rows })`, for tests, fixtures and small static lists.
|
|
323
|
+
|
|
324
|
+
### Your own source
|
|
325
|
+
|
|
326
|
+
Map the 11 operators to your query language once; `list` runs the query:
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
import { sourceDefine } from 'next-data-kit/server';
|
|
330
|
+
|
|
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
|
+
});
|
|
347
|
+
```
|
|
348
|
+
|
|
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.
|
|
350
|
+
|
|
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.
|
|
352
|
+
|
|
353
|
+
## Reference
|
|
354
|
+
|
|
355
|
+
### `dataKit(definition)` · `next-data-kit/server`
|
|
143
356
|
|
|
144
|
-
|
|
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`. |
|
|
366
|
+
|
|
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`.
|
|
368
|
+
|
|
369
|
+
### Components · `components/ui/ndk/data-kit/`
|
|
370
|
+
|
|
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` |
|
|
145
377
|
|
|
146
|
-
|
|
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.
|
|
379
|
+
|
|
380
|
+
### URL
|
|
381
|
+
|
|
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.
|
|
147
383
|
|
|
148
384
|
## FAQ
|
|
149
385
|
|
|
150
|
-
### Is it safe to
|
|
386
|
+
### Is it safe to put sort and filters in the URL?
|
|
387
|
+
|
|
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.
|
|
389
|
+
|
|
390
|
+
### Does it work with SQL databases?
|
|
151
391
|
|
|
152
|
-
Yes
|
|
392
|
+
Yes: `sourcePrisma`, `sourceDrizzle` (Postgres, MySQL, SQLite), or your own with `sourceDefine`. The same `dataKit` definition works with any of them.
|
|
153
393
|
|
|
154
394
|
### Does it need Next.js?
|
|
155
395
|
|
|
156
|
-
The core and
|
|
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`.
|
|
397
|
+
|
|
398
|
+
### Why TanStack Table 8 and not 9?
|
|
399
|
+
|
|
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.
|
|
401
|
+
|
|
402
|
+
### How do I update the copied components?
|
|
403
|
+
|
|
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.
|
|
405
|
+
|
|
406
|
+
## Migrating
|
|
407
|
+
|
|
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.
|
|
409
|
+
|
|
410
|
+
### 10.x → 11.0
|
|
157
411
|
|
|
158
|
-
|
|
412
|
+
11.0 replaces per-filter zod/query pairs with declared columns, and the `DataKitRoot` parts with one `DataKit` component on TanStack Table.
|
|
159
413
|
|
|
160
|
-
|
|
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 |
|
|
161
427
|
|
|
162
|
-
###
|
|
428
|
+
### 9.x → 10.0
|
|
163
429
|
|
|
164
|
-
See [MIGRATION.md](./MIGRATION.md).
|
|
430
|
+
See [MIGRATION.md](./MIGRATION.md#migrating-from-9x-to-100).
|
|
165
431
|
|
|
166
432
|
## License
|
|
167
433
|
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// src/server/source/define.ts
|
|
2
|
+
var sourceDefine = (props) => {
|
|
3
|
+
const { operator, and, or, list } = props;
|
|
4
|
+
const translate = (condition) => "or" in condition ? or(condition.or.map(translate)) : "native" in condition ? condition.native : operator[condition.operator]({ field: condition.field, value: condition.value });
|
|
5
|
+
return {
|
|
6
|
+
list: (props2) => list({ where: props2.filter.length ? and(props2.filter.map(translate)) : void 0, sort: props2.sort, page: props2.page })
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export { sourceDefine };
|
|
11
|
+
//# sourceMappingURL=chunk-5D747NEB.js.map
|
|
12
|
+
//# sourceMappingURL=chunk-5D747NEB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/source/define.ts"],"names":["props"],"mappings":";AAKO,IAAM,YAAA,GAAe,CAC3B,KAAA,KAM0B;AAE1B,EAAA,MAAM,EAAE,QAAA,EAAU,GAAA,EAAK,EAAA,EAAI,MAAK,GAAI,KAAA;AAGpC,EAAA,MAAM,SAAA,GAAY,CAAC,SAAA,KAClB,IAAA,IAAQ,SAAA,GAAY,EAAA,CAAG,SAAA,CAAU,EAAA,CAAG,GAAA,CAAI,SAAS,CAAC,CAAA,GAAI,QAAA,IAAY,SAAA,GAAa,SAAA,CAAU,MAAA,GAAqB,QAAA,CAAS,SAAA,CAAU,QAAQ,CAAA,CAAE,EAAE,KAAA,EAAO,SAAA,CAAU,KAAA,EAAO,KAAA,EAAO,SAAA,CAAU,KAAA,EAAgB,CAAA;AAEvM,EAAA,OAAO;AAAA,IACN,IAAA,EAAM,CAACA,MAAAA,KAAU,IAAA,CAAK,EAAE,KAAA,EAAOA,MAAAA,CAAM,MAAA,CAAO,MAAA,GAAS,GAAA,CAAIA,MAAAA,CAAM,OAAO,GAAA,CAAI,SAAS,CAAC,CAAA,GAAI,MAAA,EAAW,IAAA,EAAMA,OAAM,IAAA,EAAM,IAAA,EAAMA,MAAAA,CAAM,IAAA,EAAM;AAAA,GACxI;AACD","file":"chunk-5D747NEB.js","sourcesContent":["import type { TDataKitCondition, TDataKitOperator, TDataKitSort } from '../../types';\nimport type { TDataKitSource } from '../../types/server/source';\n\n// ** Build a source for any database: map the 11 operators to your query language once, then run the query in `list`\n// ** `between` always gets both ends; `in` / `nin` get an array; `contains` gets raw text (escape it); `null` gets true (is null) or false\nexport const sourceDefine = <TRow, TNative>(\n\tprops: Readonly<{\n\t\toperator: { [TKey in TDataKitOperator]: (props: Readonly<{ field: string; value: TKey extends 'in' | 'nin' ? unknown[] : TKey extends 'between' ? [unknown, unknown] : TKey extends 'null' ? boolean : unknown }>) => TNative };\n\t\tand: (list: TNative[]) => TNative;\n\t\tor: (list: TNative[]) => TNative;\n\t\tlist: (props: Readonly<{ where: TNative | undefined; sort: TDataKitSort[]; page: { offset: number; limit: number; count: boolean } }>) => Promise<{ rows: TRow[]; total: number | null }>;\n\t}>,\n): TDataKitSource<TRow> => {\n\t// ** Deconstruct Props\n\tconst { operator, and, or, list } = props;\n\n\t// ** A custom filter's `native` query passes through untouched\n\tconst translate = (condition: TDataKitCondition): TNative =>\n\t\t'or' in condition ? or(condition.or.map(translate)) : 'native' in condition ? (condition.native as TNative) : operator[condition.operator]({ field: condition.field, value: condition.value as never });\n\n\treturn {\n\t\tlist: (props) => list({ where: props.filter.length ? and(props.filter.map(translate)) : undefined, sort: props.sort, page: props.page }),\n\t};\n};\n"]}
|