@gridsay/tanstack-table 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +320 -2
- package/dist/index-yyGT4N9i.d.ts +180 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/react.d.ts +32 -0
- package/dist/react.js +56 -0
- package/dist/src-D4dDBjRk.js +890 -0
- package/package.json +66 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bluvio Software Studio LLP
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,321 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @gridsay/tanstack-table
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Your users ask a TanStack Table in plain words: "orders over 500 from Germany, newest first". The helper describes your table to Gridsay, sends the question, and applies the answer to the table: filters, sorting, grouping, or the top rows selected. All of the answer, or none of it, unless `reset()` comes while it is being applied. Where this stands: [gridsay.com/features#status](https://gridsay.com/features#status). More: [gridsay.com/product/tanstack-table](https://gridsay.com/product/tanstack-table) and [gridsay.com/docs/tanstack-table](https://gridsay.com/docs/tanstack-table).
|
|
4
|
+
|
|
5
|
+
TanStack Table is headless, and so is this package: it ships no interface. You bring the input box (step 4).
|
|
6
|
+
|
|
7
|
+
## Before you start
|
|
8
|
+
|
|
9
|
+
- **TanStack Table v9 only.** The peer range is `@tanstack/table-core` `^9.3.1`, and 9.3.1 is the version the tests run on. v8 is not supported, nor are Material React Table and Mantine React Table, which are built on v8.
|
|
10
|
+
- **React first.** The hook in `@gridsay/tanstack-table/react` needs React 18 or later. The core entry, `@gridsay/tanstack-table`, works with any v9 adapter, tested with React only.
|
|
11
|
+
- **A Gridsay secret key.** Create one in the Gridsay console, under Keys. It stays on your server.
|
|
12
|
+
|
|
13
|
+
## From nothing to a first answer
|
|
14
|
+
|
|
15
|
+
### 1. Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm install @gridsay/tanstack-table @tanstack/react-table@^9.3.1
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
### 2. Add your key
|
|
22
|
+
|
|
23
|
+
In `.env.local`, never in the browser:
|
|
24
|
+
|
|
25
|
+
```env
|
|
26
|
+
GRIDSAY_SECRET_KEY=your-secret-key
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### 3. Add a server route
|
|
30
|
+
|
|
31
|
+
The route adds your secret key and refuses callers who are not signed in. Anyone who can reach it spends your credits, so keep the check. This one is for Next.js, at `app/api/tanstack-table/route.ts`; any server can do the same.
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
// Replace with your app's own sign-in check, such as a session cookie. As written it refuses everyone.
|
|
35
|
+
const isSignedIn = async (_request: Request) => false;
|
|
36
|
+
|
|
37
|
+
export async function POST(request: Request) {
|
|
38
|
+
if (!(await isSignedIn(request))) {
|
|
39
|
+
return Response.json(
|
|
40
|
+
{ ok: false, code: 'unauthenticated_user', message: 'Sign in to use the assistant.' },
|
|
41
|
+
{ status: 401 },
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
const response = await fetch('https://api.gridsay.com/api/v1/datagrid/prompt', {
|
|
45
|
+
method: 'POST',
|
|
46
|
+
headers: { 'content-type': 'application/json', 'x-api-key': process.env.GRIDSAY_SECRET_KEY ?? '' },
|
|
47
|
+
body: await request.text(),
|
|
48
|
+
redirect: 'error', // never send the key on to a redirect target
|
|
49
|
+
});
|
|
50
|
+
return new Response(response.body, { status: response.status, headers: { 'content-type': 'application/json' } });
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
To try it on your own machine, let the route through only in development, as the example's `authorize.ts` does. Put your real check back before you deploy.
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
const isSignedIn = async (_request: Request) => process.env.NODE_ENV === 'development';
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### 4. Set up the table, the hook and an input
|
|
61
|
+
|
|
62
|
+
Register the features the assistant may change, put `assistantColumn` on the columns, and call the hook. The input is yours: this one is a form with a text box.
|
|
63
|
+
|
|
64
|
+
```tsx
|
|
65
|
+
'use client';
|
|
66
|
+
|
|
67
|
+
import {
|
|
68
|
+
assistantColumn,
|
|
69
|
+
assistantGroupedRowModel,
|
|
70
|
+
useTableAssistant,
|
|
71
|
+
} from '@gridsay/tanstack-table/react';
|
|
72
|
+
import {
|
|
73
|
+
columnFilteringFeature,
|
|
74
|
+
columnGroupingFeature,
|
|
75
|
+
createColumnHelper,
|
|
76
|
+
createExpandedRowModel,
|
|
77
|
+
createFilteredRowModel,
|
|
78
|
+
createSortedRowModel,
|
|
79
|
+
rowExpandingFeature,
|
|
80
|
+
rowSelectionFeature,
|
|
81
|
+
rowSortingFeature,
|
|
82
|
+
tableFeatures,
|
|
83
|
+
useTable,
|
|
84
|
+
} from '@tanstack/react-table';
|
|
85
|
+
import { useState } from 'react';
|
|
86
|
+
|
|
87
|
+
// The assistant changes only what you register here.
|
|
88
|
+
const features = tableFeatures({
|
|
89
|
+
columnFilteringFeature,
|
|
90
|
+
filteredRowModel: createFilteredRowModel(),
|
|
91
|
+
rowSortingFeature,
|
|
92
|
+
sortedRowModel: createSortedRowModel(),
|
|
93
|
+
columnGroupingFeature,
|
|
94
|
+
groupedRowModel: assistantGroupedRowModel(), // in place of createGroupedRowModel()
|
|
95
|
+
rowExpandingFeature,
|
|
96
|
+
expandedRowModel: createExpandedRowModel(),
|
|
97
|
+
rowSelectionFeature,
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
type Order = { customer: string; country: string; status: string; total: number; placedAt: Date };
|
|
101
|
+
|
|
102
|
+
const columnHelper = createColumnHelper<typeof features, Order>();
|
|
103
|
+
const columns = columnHelper.columns([
|
|
104
|
+
columnHelper.accessor('customer', { header: 'Customer' }),
|
|
105
|
+
columnHelper.accessor('country', { header: 'Country' }),
|
|
106
|
+
columnHelper.accessor('status', {
|
|
107
|
+
header: 'Status',
|
|
108
|
+
meta: { assistant: { type: 'singleSelect', options: ['open', 'paid', 'refunded'] } },
|
|
109
|
+
}),
|
|
110
|
+
columnHelper.accessor('total', {
|
|
111
|
+
header: 'Total',
|
|
112
|
+
meta: { assistant: { description: 'Order total in euros' } },
|
|
113
|
+
}),
|
|
114
|
+
columnHelper.accessor('placedAt', { header: 'Placed' }),
|
|
115
|
+
]);
|
|
116
|
+
|
|
117
|
+
export function Orders({ data }: { data: Order[] }) {
|
|
118
|
+
const table = useTable({
|
|
119
|
+
features,
|
|
120
|
+
columns,
|
|
121
|
+
data,
|
|
122
|
+
defaultColumn: assistantColumn, // the line that lets the assistant filter and sort
|
|
123
|
+
initialState: { expanded: true }, // groups the assistant makes show their rows...
|
|
124
|
+
autoResetExpanded: false, // ...and stay open after the next answer
|
|
125
|
+
});
|
|
126
|
+
const { ask, undo, canUndo, pending, error } = useTableAssistant(table, { url: '/api/tanstack-table' });
|
|
127
|
+
const [question, setQuestion] = useState('');
|
|
128
|
+
|
|
129
|
+
return (
|
|
130
|
+
<>
|
|
131
|
+
<form
|
|
132
|
+
onSubmit={async (event) => {
|
|
133
|
+
event.preventDefault();
|
|
134
|
+
if (await ask(question)) setQuestion('');
|
|
135
|
+
}}
|
|
136
|
+
>
|
|
137
|
+
<input
|
|
138
|
+
aria-label="Ask about the orders"
|
|
139
|
+
value={question}
|
|
140
|
+
onChange={(event) => setQuestion(event.target.value)}
|
|
141
|
+
readOnly={pending}
|
|
142
|
+
placeholder="Orders over 500 from Germany, newest first"
|
|
143
|
+
/>
|
|
144
|
+
<button type="submit" disabled={pending || !question.trim()}>
|
|
145
|
+
Ask
|
|
146
|
+
</button>
|
|
147
|
+
<button type="button" disabled={pending || !canUndo} onClick={() => undo()}>
|
|
148
|
+
Undo
|
|
149
|
+
</button>
|
|
150
|
+
</form>
|
|
151
|
+
{error ? <p role="alert">{error.message}</p> : null}
|
|
152
|
+
<table>
|
|
153
|
+
<thead>
|
|
154
|
+
{table.getHeaderGroups().map((headerGroup) => (
|
|
155
|
+
<tr key={headerGroup.id}>
|
|
156
|
+
{headerGroup.headers.map((header) => (
|
|
157
|
+
<th key={header.id}>
|
|
158
|
+
<table.FlexRender header={header} />
|
|
159
|
+
</th>
|
|
160
|
+
))}
|
|
161
|
+
</tr>
|
|
162
|
+
))}
|
|
163
|
+
</thead>
|
|
164
|
+
<tbody>
|
|
165
|
+
{table.getRowModel().rows.map((row) =>
|
|
166
|
+
row.getIsGrouped() ? (
|
|
167
|
+
<tr key={row.id}>
|
|
168
|
+
<th colSpan={columns.length}>
|
|
169
|
+
{String(row.groupingValue)} ({row.getLeafRows().length})
|
|
170
|
+
</th>
|
|
171
|
+
</tr>
|
|
172
|
+
) : (
|
|
173
|
+
<tr key={row.id} className={row.getIsSelected() ? 'selected' : undefined}>
|
|
174
|
+
{row.getAllCells().map((cell) => (
|
|
175
|
+
<td key={cell.id}>
|
|
176
|
+
<table.FlexRender cell={cell} />
|
|
177
|
+
</td>
|
|
178
|
+
))}
|
|
179
|
+
</tr>
|
|
180
|
+
),
|
|
181
|
+
)}
|
|
182
|
+
</tbody>
|
|
183
|
+
</table>
|
|
184
|
+
</>
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
Save it as `app/orders.tsx` and render `<Orders data={orders} />` from `app/page.tsx`, with your own `orders`.
|
|
190
|
+
|
|
191
|
+
### 5. Ask
|
|
192
|
+
|
|
193
|
+
Run your app and type "Orders over 500 from Germany, newest first". The table filters and sorts, and `ask` resolves `true`. Each answer's conversation goes with the next question, so a follow-up such as "only the ones over 1000" builds on the last answer. Undo puts back what the last answer changed.
|
|
194
|
+
|
|
195
|
+
### 6. See a refusal
|
|
196
|
+
|
|
197
|
+
Ask "make a chart of orders by country". The assistant cannot chart, so it declines: the table is unchanged, `ask` resolves `false`, and `error` holds a `GridsayError`: its `message` is the assistant's own sentence, which you can show your user, and the rest is for you: status 422, code `query_not_understood`.
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
import { CANNOT_APPLY_CODE, type GridsayError } from '@gridsay/tanstack-table/react';
|
|
201
|
+
|
|
202
|
+
// `error` is what `useTableAssistant` returns when a question failed.
|
|
203
|
+
export function report(error: GridsayError) {
|
|
204
|
+
console.warn(error.status, error.code, error.retryAfter, error.detail);
|
|
205
|
+
if (error.code === CANNOT_APPLY_CODE) console.warn('Not applied:', error.detail);
|
|
206
|
+
}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
A caller your route turns away gets status 401, code `unauthenticated_user` and "Sign in to use the assistant."
|
|
210
|
+
|
|
211
|
+
## The hook
|
|
212
|
+
|
|
213
|
+
`useTableAssistant(table, options)` returns:
|
|
214
|
+
|
|
215
|
+
- `ask(question)`: resolves `true` when the answer is on the table, `false` when it is not. Then `error` says why, except after `reset()`.
|
|
216
|
+
- `undo()`: puts back what the last answer changed and returns `true`. It does nothing and returns `false` when there is nothing to undo, or while a question is pending. It undoes one answer; it does not stack.
|
|
217
|
+
- `reset()`: starts a new conversation. The next question does not build on earlier ones, `undo` forgets, and the table stays as it is. It does not cancel a request already sent: Gridsay may still answer it, and charge for it. A question still waiting for its answer changes nothing on the table afterwards.
|
|
218
|
+
- `canUndo`: true after an applied answer; a refusal leaves it as it was. It is `false` while a question is pending.
|
|
219
|
+
- `pending`: true while a question is being answered.
|
|
220
|
+
- `error`: why the last question was not answered, as a `GridsayError`, or `null`. Show `error.message` to your user; read `code`, `status`, `retryAfter` and `detail` to tell failures apart.
|
|
221
|
+
|
|
222
|
+
`error` clears when the next `ask` starts, when an `undo` puts something back, and on `reset()`. The conversation lasts as long as the component stays mounted.
|
|
223
|
+
|
|
224
|
+
Without React, `createTableAssistant(table, options)` from `@gridsay/tanstack-table` returns `ask`, `undo`, `reset` and a read-only `canUndo`. Read `assistant.canUndo` when you need it rather than destructuring it once. `ask` rejects with a `GridsayError`; after `reset()` a question still waiting rejects with code `reset`.
|
|
225
|
+
|
|
226
|
+
```js
|
|
227
|
+
import { createTableAssistant, GridsayError } from '@gridsay/tanstack-table';
|
|
228
|
+
|
|
229
|
+
// `table` is the table your adapter made, with the features and columns of step 4.
|
|
230
|
+
const assistant = createTableAssistant(table, { url: '/api/tanstack-table' });
|
|
231
|
+
|
|
232
|
+
try {
|
|
233
|
+
await assistant.ask('orders over 500 from Germany, newest first');
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (!(error instanceof GridsayError)) throw error;
|
|
236
|
+
console.warn(error.code, error.message); // show error.message to your user
|
|
237
|
+
}
|
|
238
|
+
assistant.undo(); // false when there is nothing to undo, or while a question is pending
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
## Options
|
|
242
|
+
|
|
243
|
+
| Option | Meaning |
|
|
244
|
+
|---|---|
|
|
245
|
+
| `url` | Required. Where the question is posted: your route. To call Gridsay from the browser with a publishable key, use `https://api.gridsay.com/api/v1/datagrid/prompt`; the key needs your site's origin and a way to identify end users, both set in the console. |
|
|
246
|
+
| `headers` | Extra request headers, or a function that returns them. |
|
|
247
|
+
| `publishableKey`, `getToken` | For calling Gridsay from the browser. `publishableKey` is sent as `x-api-key`; `getToken` returns the signed-in user's token, sent as a bearer token. It may return `null` or `undefined`, and may be sync or async, so an auth library's `getToken` can be passed directly. |
|
|
248
|
+
| `additionalContext` | Extra text for the assistant about your table. |
|
|
249
|
+
| `privateMode` | Sent to Gridsay as `options.privateMode`. |
|
|
250
|
+
| `referenceId` | Your id for the end user. |
|
|
251
|
+
|
|
252
|
+
## Errors
|
|
253
|
+
|
|
254
|
+
Show `error.message` to your user. Everything else on a `GridsayError` is for you: `code`, `status` when a response arrived, `retryAfter`, `detail`, and `cause`. **Compare codes, never messages**: the messages may change. Each helper code is an exported constant, such as `CANNOT_APPLY_CODE` and `RESET_CODE`.
|
|
255
|
+
|
|
256
|
+
What Gridsay answers, with `status` and `code`:
|
|
257
|
+
|
|
258
|
+
| Error | Cause | Fix |
|
|
259
|
+
|---|---|---|
|
|
260
|
+
| 400 `invalid_request` | Gridsay could not read the request. `detail` names the field. | Forward the body unchanged from your route. |
|
|
261
|
+
| 401 `unauthenticated_user` | Not signed in, whoever noticed. Your route turned the caller away (a 401 with no code of its own), `getToken` gave nothing (`null`, `undefined` or an empty string) or threw (then there is no `status`, and nothing was sent), or Gridsay did not accept the end user's token. | Sign the user in, or return their token from `getToken`. |
|
|
262
|
+
| 413 `context_too_large` | The question, the columns and the table's state are more than the assistant accepts. `detail` says which limit. | Send fewer columns, shorter descriptions, fewer `examples` or fewer `singleSelect` options. Not charged. |
|
|
263
|
+
| 422 `query_not_understood` | The assistant declined the question, for example a total, a pivot, a chart or something the table does not allow. `message` is its own sentence, and the table is unchanged. | Show the message; the user rewords. Charged. |
|
|
264
|
+
| 429 `rate_limited` | A limit on your key or your user was reached, or the assistant is busy. | Wait `retryAfter` seconds when it is set, then ask again. Not charged. |
|
|
265
|
+
| 502 or 503 `upstream_unavailable` | The model service failed or its answer was unusable (502), or the service could not take the question (503). | Ask again; if it persists, `detail` says what to check. Not charged. |
|
|
266
|
+
|
|
267
|
+
Gridsay also answers 401 `invalid_api_key` for a key it does not accept, 402 for a plan that cannot cover the question, and 403 for a site the key does not allow or a publishable key with no sign-in method set up; `detail` says what to change.
|
|
268
|
+
|
|
269
|
+
What the helper itself reports, with no request to blame:
|
|
270
|
+
|
|
271
|
+
| `code` | When | Fix |
|
|
272
|
+
|---|---|---|
|
|
273
|
+
| `unexpected_error` | Something in your page threw: your `headers` function, or the table while it was being read (an accessor function with no `id` and no string header, say). `cause` holds it. A table that throws while taking the answer is `cannot_apply` instead, with the detail `state: the table threw on the answer`. | Fix what `cause` shows. |
|
|
274
|
+
| `connection_failed` | The request did not complete: no network, or the connection broke while the answer was read. | Ask again. |
|
|
275
|
+
| `not_json` | Your route answered with something that is not JSON, often because its path does not exist. `status` says which. | Check `url` and the route. |
|
|
276
|
+
| `invalid_answer` | The response was not an answer the helper can read. | Return Gridsay's body and status from your route as they came. |
|
|
277
|
+
| `cannot_apply` | The answer could not be applied to the table, so nothing changed. `detail` names what, such as `sorting: no column "total"`. | Check the column ids and the features you registered. Do not show `detail` to users. |
|
|
278
|
+
| `reset` | `reset()` was called while the question was waiting. The hook ignores it. | Nothing: no answer is wanted. |
|
|
279
|
+
|
|
280
|
+
A question the assistant declines (422) is charged. A question Gridsay fails to answer (413, 429, 502) is not. An answer the helper cannot apply (`cannot_apply`) was already answered by Gridsay, so it is charged like any answer.
|
|
281
|
+
|
|
282
|
+
## What an answer changes
|
|
283
|
+
|
|
284
|
+
An answer sets filters, sorting, grouping, and the selection of the first rows, each only when you registered what it needs:
|
|
285
|
+
|
|
286
|
+
| Answer | Needs on the table |
|
|
287
|
+
|---|---|
|
|
288
|
+
| Filters | `columnFilteringFeature` and `filteredRowModel`, and not `manualFiltering` |
|
|
289
|
+
| Sorting | `rowSortingFeature` and `sortedRowModel`, or `manualSorting` |
|
|
290
|
+
| Grouping | `columnGroupingFeature` and `assistantGroupedRowModel()`, or `manualGrouping` |
|
|
291
|
+
| Top rows selected | `rowSelectionFeature`, and `enableRowSelection` not `false` |
|
|
292
|
+
|
|
293
|
+
Whatever is missing is reported to Gridsay as switched off, and a question that needs it gets a sentence back.
|
|
294
|
+
|
|
295
|
+
It never changes totals, pivots or charts: a question that needs one gets a sentence back. It does not touch column visibility, order, pinning or sizing, or paging. An answer that changes filters, sorting or grouping sends the table to its first page, as TanStack does for any such change; undo puts the page and the open groups back as they were.
|
|
296
|
+
|
|
297
|
+
- **Filtering runs in the browser.** A table that filters on its server (`manualFiltering`) cannot be filtered by the assistant. With `manualSorting` or `manualGrouping` the assistant sets the sorting or grouping state, and fetching the rows in that order is your code.
|
|
298
|
+
- **An answer is the whole filter.** It replaces the column filters, including any you set by hand, and clears a global filter, such as a search box. Every question sends the table's current sorting and grouping and the filters an earlier answer set, so a header click that sorts is part of the next question.
|
|
299
|
+
- **State you own** (React state passed as `state` with `onSortingChange`, say) must show the answer within one second. Otherwise the table is put back and `ask` rejects with `cannot_apply`.
|
|
300
|
+
- **Top rows** are the first rows of the table in the order shown, inside groups too.
|
|
301
|
+
- **TanStack's own grouped row model** does not group for the assistant; use `assistantGroupedRowModel()`.
|
|
302
|
+
|
|
303
|
+
## Columns
|
|
304
|
+
|
|
305
|
+
The assistant sees the columns that have an accessor. Display columns are not sent, and an answer that names one is not applied.
|
|
306
|
+
|
|
307
|
+
- **An accessor function needs an `id`, or a string `header`** that becomes the id. TanStack itself refuses one with neither.
|
|
308
|
+
- **`assistantColumn`** is `filterFn: assistantFilter`, `sortFn: assistantSort` and `sortUndefined: false`. Set it as `defaultColumn` or spread it into a column. If no column has the filter function, the helper warns once in the browser console.
|
|
309
|
+
- **A column with its own `filterFn` or `sortFn` is left to you**, and so is one with `enableColumnFilter`, `enableSorting` or `enableGrouping` set to `false`. The assistant is told it cannot filter, sort or group by it.
|
|
310
|
+
- **`meta.assistant`** is `{ type, description, options, examples }`, all optional. `type` is `string`, `number`, `date`, `dateTime`, `boolean` or `singleSelect`; without one it is read from the first 100 rows, and anything unclear is `string`. A `singleSelect` needs its `options`: values, or `{ value, label }`. `examples` are sent only when you set them: a list, or `true` for up to five values from the rows.
|
|
311
|
+
- **What is sent**: your question, each column's id, header, type and description, which features are on, and the table's current sorting and grouping and the filters an answer set. Your rows are not sent, apart from the `examples` you ask for and the options you list.
|
|
312
|
+
|
|
313
|
+
## Versions
|
|
314
|
+
|
|
315
|
+
Before 1.0 a breaking change raises the minor version.
|
|
316
|
+
|
|
317
|
+
## Licence
|
|
318
|
+
|
|
319
|
+
This package is MIT licensed. TanStack Table is MIT-licensed open source by its own maintainers. Gridsay is an independent product, not affiliated with or endorsed by the TanStack Table project.
|
|
320
|
+
|
|
321
|
+
A runnable example: [examples/tanstack-table](https://github.com/gridsay/gridsay/tree/main/examples/tanstack-table).
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { CANNOT_APPLY_CODE, CONNECTION_FAILED, CONNECTION_FAILED_CODE, GridsayError, INVALID_ANSWER, INVALID_ANSWER_CODE, NOT_JSON, NOT_JSON_CODE, RequestOptions, UNAUTHENTICATED_USER, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE } from "@gridsay/core";
|
|
2
|
+
import { CellData, RowData, RowModel, Table, TableFeatures } from "@tanstack/table-core";
|
|
3
|
+
/** The column types the assistant knows, with the MUI X Data Grid's meaning. */
|
|
4
|
+
type ColumnType = 'string' | 'number' | 'date' | 'dateTime' | 'boolean' | 'singleSelect';
|
|
5
|
+
type Row = {
|
|
6
|
+
getValue: (columnId: string) => unknown;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* The plugin's filter function. Set it as `filterFn` on the columns the assistant may filter.
|
|
10
|
+
* It reads the plugin's own filter values and keeps every row for any other value.
|
|
11
|
+
*/
|
|
12
|
+
declare const assistantFilter: ((row: Row, _columnId: string, filterValue: unknown) => boolean) & {
|
|
13
|
+
resolveFilterValue: (value: unknown) => unknown;
|
|
14
|
+
};
|
|
15
|
+
/** What a column tells the assistant, under `meta.assistant`. Everything is optional. */
|
|
16
|
+
type AssistantColumnMeta = {
|
|
17
|
+
/** Wins over the type the plugin infers from the column's values. */
|
|
18
|
+
type?: ColumnType;
|
|
19
|
+
description?: string;
|
|
20
|
+
/** A singleSelect's choices: the stored value, or the stored value and the label people see. */
|
|
21
|
+
options?: readonly (string | number | {
|
|
22
|
+
value: string | number;
|
|
23
|
+
label: string;
|
|
24
|
+
})[];
|
|
25
|
+
/** Sample values sent to the server with each question. `true` takes them from the rows. */
|
|
26
|
+
examples?: readonly unknown[] | true;
|
|
27
|
+
};
|
|
28
|
+
declare module '@tanstack/table-core' {
|
|
29
|
+
interface ColumnMeta<in out TFeatures extends TableFeatures, in out TData extends RowData, TValue extends CellData = CellData> {
|
|
30
|
+
assistant?: AssistantColumnMeta;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** A table row, as far as the plugin reads it. */
|
|
34
|
+
type TableRow = {
|
|
35
|
+
id: string;
|
|
36
|
+
subRows: readonly TableRow[];
|
|
37
|
+
getValue: (columnId: string) => unknown;
|
|
38
|
+
};
|
|
39
|
+
/** A leaf column. The feature methods are there when their feature is registered. */
|
|
40
|
+
type TableColumn = {
|
|
41
|
+
id: string;
|
|
42
|
+
accessorFn?: unknown;
|
|
43
|
+
columnDef: {
|
|
44
|
+
header?: unknown;
|
|
45
|
+
meta?: unknown;
|
|
46
|
+
sortUndefined?: unknown;
|
|
47
|
+
invertSorting?: unknown;
|
|
48
|
+
};
|
|
49
|
+
getCanFilter?: () => boolean;
|
|
50
|
+
getFilterFn?: () => unknown;
|
|
51
|
+
getCanSort?: () => boolean;
|
|
52
|
+
getSortFn?: () => unknown;
|
|
53
|
+
getCanGroup?: () => boolean;
|
|
54
|
+
};
|
|
55
|
+
type Filter = {
|
|
56
|
+
id: string;
|
|
57
|
+
value: unknown;
|
|
58
|
+
};
|
|
59
|
+
type Sort = {
|
|
60
|
+
id: string;
|
|
61
|
+
desc: boolean;
|
|
62
|
+
};
|
|
63
|
+
type Pagination = {
|
|
64
|
+
pageIndex: number;
|
|
65
|
+
pageSize: number;
|
|
66
|
+
};
|
|
67
|
+
type Expanded = true | Readonly<Record<string, boolean>>;
|
|
68
|
+
/** The slices of table state the plugin reads and writes. */
|
|
69
|
+
type TableSlices = {
|
|
70
|
+
columnFilters?: readonly Filter[];
|
|
71
|
+
globalFilter?: unknown;
|
|
72
|
+
sorting?: readonly Sort[];
|
|
73
|
+
grouping?: readonly string[];
|
|
74
|
+
rowSelection?: Readonly<Record<string, true>>;
|
|
75
|
+
pagination?: Readonly<Pagination>;
|
|
76
|
+
expanded?: Expanded;
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* The part of a TanStack Table v9 `Table` the plugin uses, described by shape so that a table
|
|
80
|
+
* built with any set of features fits it.
|
|
81
|
+
*/
|
|
82
|
+
type AssistantTable = {
|
|
83
|
+
options: {
|
|
84
|
+
features: object;
|
|
85
|
+
manualFiltering?: boolean;
|
|
86
|
+
manualSorting?: boolean;
|
|
87
|
+
manualGrouping?: boolean;
|
|
88
|
+
enableRowSelection?: unknown;
|
|
89
|
+
};
|
|
90
|
+
store: {
|
|
91
|
+
get: () => TableSlices;
|
|
92
|
+
};
|
|
93
|
+
getAllLeafColumns: () => readonly TableColumn[];
|
|
94
|
+
getCoreRowModel: () => {
|
|
95
|
+
flatRows: readonly TableRow[];
|
|
96
|
+
};
|
|
97
|
+
getSortedRowModel: () => {
|
|
98
|
+
rows: readonly TableRow[];
|
|
99
|
+
};
|
|
100
|
+
getRowModel: () => unknown;
|
|
101
|
+
setColumnFilters?: (filters: Filter[]) => void;
|
|
102
|
+
setGlobalFilter?: (value: unknown) => void;
|
|
103
|
+
setSorting?: (sorting: Sort[]) => void;
|
|
104
|
+
setGrouping?: (grouping: string[]) => void;
|
|
105
|
+
setRowSelection?: (selection: Record<string, true>) => void;
|
|
106
|
+
setPagination?: (pagination: Pagination) => void;
|
|
107
|
+
setExpanded?: (expanded: true | Record<string, boolean>) => void;
|
|
108
|
+
};
|
|
109
|
+
/** A row as `assistantSort` reads it. */
|
|
110
|
+
type SortRow = {
|
|
111
|
+
getValue: (columnId: string) => unknown;
|
|
112
|
+
getIsGrouped?: () => boolean;
|
|
113
|
+
table: {
|
|
114
|
+
getColumn: (columnId: string) => TableColumn | undefined;
|
|
115
|
+
getCoreRowModel: () => {
|
|
116
|
+
flatRows: readonly TableRow[];
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
/**
|
|
121
|
+
* The plugin's sort function, set by `assistantColumn`. Rows that tie keep the order of the data,
|
|
122
|
+
* as on the grid.
|
|
123
|
+
*/
|
|
124
|
+
declare const assistantSort: (rowA: SortRow, rowB: SortRow, columnId: string) => number;
|
|
125
|
+
/**
|
|
126
|
+
* Register in place of `createGroupedRowModel()` so that grouped rows match the MUI X Data Grid.
|
|
127
|
+
* The assistant groups only a table that has it.
|
|
128
|
+
*/
|
|
129
|
+
declare function assistantGroupedRowModel<TFeatures extends TableFeatures, TData extends RowData = RowData>(): (table: Table<TFeatures, TData>) => () => RowModel<TFeatures, TData>;
|
|
130
|
+
/** `ask` rejects with this, code `RESET_CODE`, when `reset()` was called before its answer arrived. */
|
|
131
|
+
declare const RESET = "The conversation was reset before this answer arrived.";
|
|
132
|
+
declare const RESET_CODE = "reset";
|
|
133
|
+
/** `ask` rejects with this, code `CANNOT_APPLY_CODE`, when the table cannot take the answer. */
|
|
134
|
+
declare const CANNOT_APPLY = "This answer could not be applied to the table.";
|
|
135
|
+
type TableAssistantOptions = RequestOptions & {
|
|
136
|
+
/** Where the prompt is posted: your own proxy route, or the Gridsay gateway. */
|
|
137
|
+
url: string;
|
|
138
|
+
};
|
|
139
|
+
type TableAssistant = {
|
|
140
|
+
/**
|
|
141
|
+
* Answers the question on the table. Rejects with a `GridsayError`; an answer the table cannot
|
|
142
|
+
* take is not applied, or is taken back. After `reset()`, a part already applied stays.
|
|
143
|
+
*/
|
|
144
|
+
ask: (question: string) => Promise<void>;
|
|
145
|
+
/**
|
|
146
|
+
* Puts back what the last answer changed, leaving the rest of the table as it is now.
|
|
147
|
+
* Returns false, doing nothing, when there is nothing to undo or a question is pending.
|
|
148
|
+
*/
|
|
149
|
+
undo: () => boolean;
|
|
150
|
+
/**
|
|
151
|
+
* True when there is an applied answer to undo and no question is pending. A refusal leaves the
|
|
152
|
+
* answer to undo as it was.
|
|
153
|
+
*/
|
|
154
|
+
readonly canUndo: boolean;
|
|
155
|
+
/**
|
|
156
|
+
* Starts a new conversation and forgets what `undo` would put back; the table stays as it is.
|
|
157
|
+
* A question still waiting for its answer rejects with `RESET` and changes the table no further.
|
|
158
|
+
* A request already sent is not cancelled: the server may still answer it, and charge for it.
|
|
159
|
+
*/
|
|
160
|
+
reset: () => void;
|
|
161
|
+
};
|
|
162
|
+
/**
|
|
163
|
+
* The one line a table needs: `defaultColumn: assistantColumn`, or spread it into the columns the
|
|
164
|
+
* assistant may filter and sort. Filters and sorts as the MUI X Data Grid does.
|
|
165
|
+
*/
|
|
166
|
+
declare const assistantColumn: {
|
|
167
|
+
readonly filterFn: ((row: {
|
|
168
|
+
getValue: (columnId: string) => unknown;
|
|
169
|
+
}, _columnId: string, filterValue: unknown) => boolean) & {
|
|
170
|
+
resolveFilterValue: (value: unknown) => unknown;
|
|
171
|
+
};
|
|
172
|
+
readonly sortFn: typeof assistantSort;
|
|
173
|
+
readonly sortUndefined: false;
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
176
|
+
* The TanStack Table counterpart of `createPromptResolver`: give it the table, ask in words.
|
|
177
|
+
* Columns the assistant may filter and sort need `assistantColumn`.
|
|
178
|
+
*/
|
|
179
|
+
declare function createTableAssistant(table: AssistantTable, options: TableAssistantOptions): TableAssistant;
|
|
180
|
+
export { ColumnType as C, AssistantTable as S, assistantColumn as _, GridsayError as a, assistantSort as b, NOT_JSON as c, RESET_CODE as d, TableAssistant as f, UNEXPECTED_ERROR_CODE as g, UNAUTHENTICATED_USER_CODE as h, CONNECTION_FAILED_CODE as i, NOT_JSON_CODE as l, UNAUTHENTICATED_USER as m, CANNOT_APPLY_CODE as n, INVALID_ANSWER as o, TableAssistantOptions as p, CONNECTION_FAILED as r, INVALID_ANSWER_CODE as s, CANNOT_APPLY as t, RESET as u, createTableAssistant as v, assistantFilter as w, AssistantColumnMeta as x, assistantGroupedRowModel as y };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { C as ColumnType, S as AssistantTable, _ as assistantColumn, a as GridsayError, b as assistantSort, c as NOT_JSON, d as RESET_CODE, f as TableAssistant, g as UNEXPECTED_ERROR_CODE, h as UNAUTHENTICATED_USER_CODE, i as CONNECTION_FAILED_CODE, l as NOT_JSON_CODE, m as UNAUTHENTICATED_USER, n as CANNOT_APPLY_CODE, o as INVALID_ANSWER, p as TableAssistantOptions, r as CONNECTION_FAILED, s as INVALID_ANSWER_CODE, t as CANNOT_APPLY, u as RESET, v as createTableAssistant, w as assistantFilter, x as AssistantColumnMeta, y as assistantGroupedRowModel } from "./index-yyGT4N9i.js";
|
|
2
|
+
export { type AssistantColumnMeta, type AssistantTable, CANNOT_APPLY, CANNOT_APPLY_CODE, CONNECTION_FAILED, CONNECTION_FAILED_CODE, type ColumnType, GridsayError, INVALID_ANSWER, INVALID_ANSWER_CODE, NOT_JSON, NOT_JSON_CODE, RESET, RESET_CODE, TableAssistant, TableAssistantOptions, UNAUTHENTICATED_USER, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE, assistantColumn, assistantFilter, assistantGroupedRowModel, assistantSort, createTableAssistant };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as CANNOT_APPLY, n as CANNOT_APPLY_CODE, r as CONNECTION_FAILED, i as CONNECTION_FAILED_CODE, a as GridsayError, o as INVALID_ANSWER, s as INVALID_ANSWER_CODE, c as NOT_JSON, l as NOT_JSON_CODE, u as RESET, d as RESET_CODE, f as UNAUTHENTICATED_USER, p as UNAUTHENTICATED_USER_CODE, m as UNEXPECTED_ERROR_CODE, h as assistantColumn, y as assistantFilter, v as assistantGroupedRowModel, _ as assistantSort, g as createTableAssistant } from "./src-D4dDBjRk.js";
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { GridsayError as GridsayError$1 } from "@gridsay/core";
|
|
2
|
+
import { C as ColumnType, S as AssistantTable, _ as assistantColumn, a as GridsayError, b as assistantSort, c as NOT_JSON, d as RESET_CODE, f as TableAssistant, g as UNEXPECTED_ERROR_CODE, h as UNAUTHENTICATED_USER_CODE, i as CONNECTION_FAILED_CODE, l as NOT_JSON_CODE, m as UNAUTHENTICATED_USER, n as CANNOT_APPLY_CODE, o as INVALID_ANSWER, p as TableAssistantOptions, r as CONNECTION_FAILED, s as INVALID_ANSWER_CODE, t as CANNOT_APPLY, u as RESET, v as createTableAssistant, w as assistantFilter, x as AssistantColumnMeta, y as assistantGroupedRowModel } from "./index-yyGT4N9i.js";
|
|
3
|
+
export type TableAssistantState = {
|
|
4
|
+
/**
|
|
5
|
+
* Answers the question on the table. Resolves false when it could not; `error` then says why,
|
|
6
|
+
* unless `reset()` was called before the answer arrived.
|
|
7
|
+
*/
|
|
8
|
+
ask: (question: string) => Promise<boolean>;
|
|
9
|
+
/**
|
|
10
|
+
* Puts back what the last answer changed. Returns false, doing nothing, when there is nothing to
|
|
11
|
+
* undo or a question is pending.
|
|
12
|
+
*/
|
|
13
|
+
undo: () => boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Starts a new conversation, forgets what `undo` would put back and clears `error`;
|
|
16
|
+
* the table stays as it is. A question still waiting for its answer changes the table no further;
|
|
17
|
+
* its request is not cancelled, so the server may still answer it, and charge for it.
|
|
18
|
+
*/
|
|
19
|
+
reset: () => void;
|
|
20
|
+
/** True when there is an applied answer to undo and `pending` is false. */
|
|
21
|
+
canUndo: boolean;
|
|
22
|
+
/** True while a question is being answered. */
|
|
23
|
+
pending: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Why the last question was not answered; null otherwise. Show `error.message` to the user, and
|
|
26
|
+
* read `code`, `status`, `retryAfter` and `detail` to tell failures apart.
|
|
27
|
+
*/
|
|
28
|
+
error: GridsayError$1 | null;
|
|
29
|
+
};
|
|
30
|
+
/** The table assistant for a React component: `ask`, `undo`, `reset`, the pending state and the last error. */
|
|
31
|
+
export declare function useTableAssistant(table: AssistantTable, options: TableAssistantOptions): TableAssistantState;
|
|
32
|
+
export { type AssistantColumnMeta, type AssistantTable, CANNOT_APPLY, CANNOT_APPLY_CODE, CONNECTION_FAILED, CONNECTION_FAILED_CODE, type ColumnType, GridsayError, INVALID_ANSWER, INVALID_ANSWER_CODE, NOT_JSON, NOT_JSON_CODE, RESET, RESET_CODE, TableAssistant, TableAssistantOptions, UNAUTHENTICATED_USER, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE, assistantColumn, assistantFilter, assistantGroupedRowModel, assistantSort, createTableAssistant };
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { GridsayError as GridsayError$1, INVALID_ANSWER as INVALID_ANSWER$1 } from "@gridsay/core";
|
|
2
|
+
import { useCallback, useReducer, useRef, useState } from "react";
|
|
3
|
+
import { _ as assistantSort, a as GridsayError, c as NOT_JSON, d as RESET_CODE, f as UNAUTHENTICATED_USER, g as createTableAssistant, h as assistantColumn, i as CONNECTION_FAILED_CODE, l as NOT_JSON_CODE, m as UNEXPECTED_ERROR_CODE, n as CANNOT_APPLY_CODE, o as INVALID_ANSWER, p as UNAUTHENTICATED_USER_CODE, r as CONNECTION_FAILED, s as INVALID_ANSWER_CODE, t as CANNOT_APPLY, u as RESET, v as assistantGroupedRowModel, y as assistantFilter } from "./src-D4dDBjRk.js";
|
|
4
|
+
// src/react.ts
|
|
5
|
+
/** Reads through to the latest value, so the assistant made on the first render follows the props. */
|
|
6
|
+
function latest(ref) {
|
|
7
|
+
return new Proxy(ref.current, { get: (_, key) => Reflect.get(ref.current, key) });
|
|
8
|
+
}
|
|
9
|
+
/** The table assistant for a React component: `ask`, `undo`, `reset`, the pending state and the last error. */
|
|
10
|
+
function useTableAssistant(table, options) {
|
|
11
|
+
const tableRef = useRef(table);
|
|
12
|
+
const optionsRef = useRef(options);
|
|
13
|
+
tableRef.current = table;
|
|
14
|
+
optionsRef.current = options;
|
|
15
|
+
const [assistant] = useState(() => createTableAssistant(latest(tableRef), latest(optionsRef)));
|
|
16
|
+
const [count, setCount] = useState(0);
|
|
17
|
+
const [error, setError] = useState(null);
|
|
18
|
+
const [, refresh] = useReducer((n) => n + 1, 0);
|
|
19
|
+
return {
|
|
20
|
+
ask: useCallback(async (question) => {
|
|
21
|
+
setError(null);
|
|
22
|
+
setCount((n) => n + 1);
|
|
23
|
+
try {
|
|
24
|
+
await assistant.ask(question);
|
|
25
|
+
setError(null);
|
|
26
|
+
return true;
|
|
27
|
+
} catch (cause) {
|
|
28
|
+
if (cause instanceof GridsayError$1 && cause.code === "reset") return false;
|
|
29
|
+
setError(cause instanceof GridsayError$1 ? cause : new GridsayError$1(INVALID_ANSWER$1, {
|
|
30
|
+
code: UNEXPECTED_ERROR_CODE,
|
|
31
|
+
cause
|
|
32
|
+
}));
|
|
33
|
+
return false;
|
|
34
|
+
} finally {
|
|
35
|
+
setCount((n) => n - 1);
|
|
36
|
+
}
|
|
37
|
+
}, [assistant]),
|
|
38
|
+
undo: useCallback(() => {
|
|
39
|
+
const restored = assistant.undo();
|
|
40
|
+
if (restored) {
|
|
41
|
+
setError(null);
|
|
42
|
+
refresh();
|
|
43
|
+
}
|
|
44
|
+
return restored;
|
|
45
|
+
}, [assistant]),
|
|
46
|
+
reset: useCallback(() => {
|
|
47
|
+
assistant.reset();
|
|
48
|
+
setError(null);
|
|
49
|
+
refresh();
|
|
50
|
+
}, [assistant]),
|
|
51
|
+
canUndo: assistant.canUndo,
|
|
52
|
+
pending: count > 0,
|
|
53
|
+
error
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
export { CANNOT_APPLY, CANNOT_APPLY_CODE, CONNECTION_FAILED, CONNECTION_FAILED_CODE, GridsayError, INVALID_ANSWER, INVALID_ANSWER_CODE, NOT_JSON, NOT_JSON_CODE, RESET, RESET_CODE, UNAUTHENTICATED_USER, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE, assistantColumn, assistantFilter, assistantGroupedRowModel, assistantSort, createTableAssistant, useTableAssistant };
|