@gridsay/mui-x-data-grid 0.0.0-stage → 1.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/LICENSE +21 -0
- package/README.md +288 -2
- package/dist/index.d.ts +126 -0
- package/dist/index.js +833 -0
- package/package.json +60 -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,289 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @gridsay/mui-x-data-grid
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Gridsay prompt resolver for the MUI X Data Grid Premium AI Assistant. It replaces MUI's
|
|
4
|
+
`unstable_gridDefaultPromptResolver` in one line, sends your grid's switches, column limits and
|
|
5
|
+
current view with each question, and checks every answer before the grid applies it.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @gridsay/mui-x-data-grid
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
MUI X Data Grid Premium is MUI's commercial product, not part of Gridsay's service. This helper is
|
|
12
|
+
compatible with it: peer dependency `@mui/x-data-grid-premium` 9.18 or a later 9.x release
|
|
13
|
+
(`^9.18.0`), tested with 9.18.0; other major versions are not tested. In a project on another
|
|
14
|
+
version, such as 9.17 or a future 10.x, npm 7 and later stop the install with an `ERESOLVE` error, and so does pnpm with strict peer dependencies on; otherwise pnpm and yarn warn. Earlier versions, 9.17 included, are not supported. You need your own MUI X Premium licence; without one, MUI shows its
|
|
15
|
+
watermark.
|
|
16
|
+
|
|
17
|
+
## What leaves the browser
|
|
18
|
+
|
|
19
|
+
With every question, the resolver posts to your `url`:
|
|
20
|
+
|
|
21
|
+
- the question and the conversation id;
|
|
22
|
+
- the column context the grid builds: each column's field, description, type and filter
|
|
23
|
+
operators, and the columns the grid derives for pivoting. Pivoting on a column turns that column's values into column names (pivot on an id column, and the ids become column names), and the grid puts these names in its context even with data sampling off; the helper's own description leaves them out. Of any option list in this context, the helper sends only the first 500 options, and of each only its value and label, when its value is text, a number or a boolean; an option with any other value is left out and still counts toward the 500. Example values go only if you turn on
|
|
24
|
+
the grid's `allowAiAssistantDataSampling` (the grid then picks values from random rows) or write
|
|
25
|
+
`examples` on a column;
|
|
26
|
+
- with `apiRef`, the grid as it is now: the features you switched off (filtering, sorting,
|
|
27
|
+
grouping, aggregation, pivoting, selection, and charts when no chart is active); per column,
|
|
28
|
+
the limits you set (`filterable`, `sortable`, `groupable`, `pivotable` or `aggregable` set to `false`, and the names in `availableAggregationFunctions` as you wrote them); for `singleSelect` and `multiSelect` columns
|
|
29
|
+
only, the value and label of each of the first 500 options, the same whether data sampling is
|
|
30
|
+
on or off; and the filters (with the values typed or picked in them, when they are text, numbers, booleans or dates), sorting, grouping,
|
|
31
|
+
aggregation and pivot;
|
|
32
|
+
- `additionalContext`, `privateMode` and `referenceId`, when you set them;
|
|
33
|
+
- in the headers: always `content-type: application/json` (your own `headers` can replace it),
|
|
34
|
+
then your own `headers`, `x-api-key` when you set `publishableKey`, and
|
|
35
|
+
`Authorization: Bearer …` with the end user's token when you set `getToken`.
|
|
36
|
+
The helper calls `fetch` with its default credentials mode, so the browser adds your cookies
|
|
37
|
+
only when `url` is on the page's own origin.
|
|
38
|
+
|
|
39
|
+
The helper sends no rows, row ids or selection of its own.
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
```tsx
|
|
44
|
+
import { createPromptResolver } from '@gridsay/mui-x-data-grid';
|
|
45
|
+
import { DataGridPremium, GridAiAssistantPanel, useGridApiRef } from '@mui/x-data-grid-premium';
|
|
46
|
+
import { useMemo } from 'react';
|
|
47
|
+
|
|
48
|
+
const apiRef = useGridApiRef();
|
|
49
|
+
const onPrompt = useMemo(
|
|
50
|
+
() => createPromptResolver({ url: '/api/ai-assistant', apiRef }),
|
|
51
|
+
[apiRef],
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
<DataGridPremium
|
|
55
|
+
apiRef={apiRef}
|
|
56
|
+
rows={rows}
|
|
57
|
+
columns={columns}
|
|
58
|
+
aiAssistant
|
|
59
|
+
onPrompt={onPrompt}
|
|
60
|
+
slots={{ aiAssistantPanel: GridAiAssistantPanel }}
|
|
61
|
+
showToolbar
|
|
62
|
+
/>;
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`/api/ai-assistant` is your server route that adds your secret key and forwards to
|
|
66
|
+
`https://api.gridsay.com/api/v1/datagrid/prompt`; see
|
|
67
|
+
[the server-route quickstart](https://gridsay.com/docs/quickstart). To call the gateway straight
|
|
68
|
+
from the browser, pass that URL with a `publishableKey` and `getToken`; see
|
|
69
|
+
[browser keys](https://gridsay.com/docs/browser-keys).
|
|
70
|
+
|
|
71
|
+
| Option | Meaning |
|
|
72
|
+
|---|---|
|
|
73
|
+
| `url` | Required. Where the prompt is posted: your own route, or the Gridsay gateway. |
|
|
74
|
+
| `apiRef` | The grid's `apiRef`. With it, the helper describes the grid to the server and adapts answers to it. Without it, you still get answer checking and readable errors, but the helper cannot see the grid: an answer that leaves pivot mode can be overwritten (see [Versioning](#versioning)). With controlled state, such as `filterModel`, update it from the grid's change callbacks, or the panel reports answers the grid does not show. |
|
|
75
|
+
| `headers` | An object, or a function returning one (it may be async), added to each request. |
|
|
76
|
+
| `publishableKey` | A publishable key, sent as `x-api-key`. For calling the gateway from the browser. |
|
|
77
|
+
| `getToken` | Returns your end user's token, called for every request and sent as `Authorization: Bearer …`. If it throws or returns nothing (`null`, `undefined` or `''`, at once or from a promise), the prompt fails with "Sign in to use the assistant." (`unauthenticated_user`) and nothing is sent. |
|
|
78
|
+
| `additionalContext`, `privateMode`, `referenceId` | Sent in the request's `options`, as the stock resolver sends them. |
|
|
79
|
+
|
|
80
|
+
## Errors
|
|
81
|
+
|
|
82
|
+
The resolver rejects with a `GridsayError`; the grid shows its `message` to your user as it is.
|
|
83
|
+
To log why, wrap the resolver and read the error's `code`, `status`, `retryAfter` and `detail`.
|
|
84
|
+
`code` is the gateway's (such as `quota_exceeded` or `rate_limited`) or one of the helper's own,
|
|
85
|
+
below. Compare codes, never messages: the messages may be reworded in a minor release. A code
|
|
86
|
+
the helper does not know, such as one the gateway adds later, arrives as it is, with the
|
|
87
|
+
gateway's `status` and sentence.
|
|
88
|
+
|
|
89
|
+
The helper's own failures, each code exported as `<NAME>_CODE` beside its sentence:
|
|
90
|
+
|
|
91
|
+
| `code` | Sentence | When |
|
|
92
|
+
|---|---|---|
|
|
93
|
+
| `unauthenticated_user` | `UNAUTHENTICATED_USER`: "Sign in to use the assistant." (or your route's own sentence) | `getToken` threw or returned nothing (nothing was sent), or the response was a 401 whose body names no other code. The same code the gateway sends. |
|
|
94
|
+
| `unexpected_error` | `INVALID_ANSWER`: "The assistant couldn't complete your request. Try again." | Your `headers` function threw, or something failed unexpectedly while the helper prepared the request or the answer; the original is in `cause`. The user sees this sentence, never the text of what was thrown. |
|
|
95
|
+
| `connection_failed` | `CONNECTION_FAILED`: "The connection was interrupted. Try again." | The request got no answer, or the answer was cut off. |
|
|
96
|
+
| `not_json` | `NOT_JSON`: "The assistant couldn't respond. Try again." | The response was not JSON (a 401 is `unauthenticated_user` instead). `status` 404 usually means `url` is wrong. |
|
|
97
|
+
| `invalid_answer` | `INVALID_ANSWER` | The response was not an answer the helper can read, or an error without a sentence of its own. |
|
|
98
|
+
|
|
99
|
+
An error from the gateway keeps the gateway's own code, `status`, `retryAfter` and `detail`; a 401 that names no code keeps its sentence, `status` and `detail` but not `retryAfter`.
|
|
100
|
+
|
|
101
|
+
## What changes compared with the stock resolver
|
|
102
|
+
|
|
103
|
+
- **The server sees your grid.** Each request carries a snapshot: features you switched off
|
|
104
|
+
(`disableColumnSorting`, `rowSelection={false}`, no active chart…), per-column limits
|
|
105
|
+
(`filterable`, `sortable`, `groupable`, `pivotable`, `aggregable: false`,
|
|
106
|
+
`availableAggregationFunctions`), singleSelect values and labels, and the filters, sorting,
|
|
107
|
+
grouping, aggregation and pivot the user has now, including changes made by hand.
|
|
108
|
+
- **Answers are checked before the grid touches them.** A malformed answer leaves the grid as it
|
|
109
|
+
was. End users see short messages instead of browser errors
|
|
110
|
+
(see Errors). Messages from the server are shown as they are.
|
|
111
|
+
- **Top N selects rows that exist.** Asking for more rows than exist, or for rows spread over
|
|
112
|
+
several pages, selects the rows that exist. With a data source, selection waits for the grid to
|
|
113
|
+
announce the new rows, and selects nothing if it does not within 15 seconds.
|
|
114
|
+
- **Sorting a grouped column reorders the groups.** The sort is moved to the grouping column the
|
|
115
|
+
grid generates (single or multiple grouping-column mode); other sorts are kept.
|
|
116
|
+
- **Leaving pivot mode** no longer brings back the grouping and aggregation from before the pivot.
|
|
117
|
+
- **A chart follow-up** keeps the aggregation it asked for.
|
|
118
|
+
- **One prompt at a time.** A prompt sent while another is running on the same grid waits for it,
|
|
119
|
+
for a bounded time, then is sent anyway; with `apiRef`, every resolver created for the same grid shares that line. If that time passes, both prompts are in flight and each answer is applied when it is ready,
|
|
120
|
+
so the two can interleave. A failed prompt does not block the next one. The request itself has no
|
|
121
|
+
time limit, as with MUI's own resolver; the helper's wait for a data source's rows ends after 15
|
|
122
|
+
seconds. Each request carries exactly the conversation id the grid gave the prompt, as with MUI's
|
|
123
|
+
own resolver: a prompt typed before the first answer of a new conversation starts its own
|
|
124
|
+
conversation. When an app keeps `aiAssistantConversations` in its own state and a second resolver
|
|
125
|
+
asks while an answer is being read, the grid writes that state from stale props: with MUI's own
|
|
126
|
+
resolver and with this helper alike, the overlapping prompt is lost from the conversation; the
|
|
127
|
+
difference is that with this helper the first prompt ends as successful instead of staying at
|
|
128
|
+
"Processing…".
|
|
129
|
+
|
|
130
|
+
## When something goes wrong after the answer arrives
|
|
131
|
+
|
|
132
|
+
- **The grid refuses part of an answer.** The grid applies an answer itself, after the resolver
|
|
133
|
+
returns it, one part after another (in 9.18: filters, pivot, grouping, aggregation, sorting,
|
|
134
|
+
chart, selection). It has no rollback: if it throws partway, the parts before stay, and the
|
|
135
|
+
panel shows the grid's own error text, not one of this helper's sentences. The helper's own
|
|
136
|
+
steps come around that: it leaves pivot mode before returning an answer without a pivot, and
|
|
137
|
+
selects the top rows a moment after, so pivot mode can already be off, and the top rows can
|
|
138
|
+
still be selected, when the grid refuses the rest. Nothing undoes an answer; ask again or change
|
|
139
|
+
the grid by hand.
|
|
140
|
+
- **The delayed top-rows selection fails.** It runs after the panel has shown the answer as
|
|
141
|
+
applied, so its error cannot be shown there; the rows are simply not selected.
|
|
142
|
+
- **The grid is unmounted while a question is out.** If the grid unmounts or is replaced while a
|
|
143
|
+
question is in flight, the answer is handled by MUI exactly as with MUI's own resolver; the
|
|
144
|
+
helper's own steps are applied only to a grid that is still in the document. With React 19.3.1, a
|
|
145
|
+
reply that arrives while the grid is hidden under `<Activity>` gets the same handling as from
|
|
146
|
+
MUI's own resolver, and the helper's own steps (leaving pivot mode, rewriting a sort on a grouped
|
|
147
|
+
column, the safe top-rows selection, waiting for a data source's rows, repairing a chart's
|
|
148
|
+
aggregation) are skipped. The helper describes the grid after your `headers` and `getToken` have
|
|
149
|
+
resolved, checking that it is in the document before each read and once more after the last, with
|
|
150
|
+
nothing awaited between that check and the request; a grid that leaves the document after that
|
|
151
|
+
moment, while the request is out, is described as it was then.
|
|
152
|
+
- **Part of the grid fails: an untested grid version, or a callback of yours.** Every call into the
|
|
153
|
+
grid goes through one guarded path: reading its private API, its root props
|
|
154
|
+
(`disableColumnFilter`, `disableColumnSorting`, `disableRowGrouping`, `disableAggregation`,
|
|
155
|
+
`disablePivoting`, `rowSelection`, `rowGroupingColumnMode`, `dataSource`) and its state (filters,
|
|
156
|
+
sorting, row grouping, aggregation, pivot mode and model, the active chart, whether rows are
|
|
157
|
+
loading), your column definitions and functions (`valueOptions`, `getOptionValue`,
|
|
158
|
+
`getOptionLabel`, and what they return), and each of the helper's own steps on it (subscribing to
|
|
159
|
+
its events, leaving pivot mode, keeping a chart's aggregation, selecting the top rows). The one
|
|
160
|
+
thing the helper does on a grid that has left the document is remove its own listeners. A part
|
|
161
|
+
that is missing, in another shape, or throws is a failure. An error thrown by the grid or by your
|
|
162
|
+
own callbacks (such as `onPivotActiveChange`) during these steps is reported in the console and
|
|
163
|
+
the step is skipped: the question goes ahead with what could be read, and the steps that depend on
|
|
164
|
+
a failed one are skipped too. Without the root props, or when pivot mode cannot be read or left,
|
|
165
|
+
the helper skips moving a grouped column's sort to the grouping column, selecting the top rows
|
|
166
|
+
(the grid is not asked to either: its own selection throws when asked for more rows than its
|
|
167
|
+
filters leave) and keeping a chart's aggregation; it never selects rows of a page whose loading it
|
|
168
|
+
could not see end. Every wait on the grid has a bound and always ends. The grid's current view is
|
|
169
|
+
sent whole or not at all, so the server keeps the conversation's last answer rather than being
|
|
170
|
+
told a part is empty.
|
|
171
|
+
- **The console warning.** Each part of the grid that fails is reported once per resolver, when
|
|
172
|
+
the question that met it has settled, however it ended. The first question to meet a failure
|
|
173
|
+
prints the full warning, naming every part it could not read or change, followed by each error
|
|
174
|
+
it caught, so you see your own stack. A part that first fails on a later question prints one
|
|
175
|
+
short line (the package, the part, "skipped", and the error). A part already reported is never
|
|
176
|
+
reported again, so the output is bounded by the number of parts the helper touches, however many questions are asked. One exception: an `apiRef` whose `current` throws when read is reported at once, before the question settles, in a full warning of its own.
|
|
177
|
+
- **Reading your column definitions.** The helper reads your column definitions once, before the
|
|
178
|
+
request, as MUI reads them: `valueOptions` called with `{ field }`, then `getOptionValue` and
|
|
179
|
+
`getOptionLabel` once per option, each as a method of its column. If reading them throws, or the
|
|
180
|
+
grid has left the page by the end of that read, the question is sent without a description and
|
|
181
|
+
settles as MUI's resolver would; what was thrown is reported in the console. Nothing read from the
|
|
182
|
+
grid refuses a question. Column definitions whose getters or functions throw only sometimes,
|
|
183
|
+
return different values on each call, or change the grid while being read are outside what the
|
|
184
|
+
helper supports. A change that makes nothing fail, such as a prop that keeps its name but changes
|
|
185
|
+
its meaning, is not noticed.
|
|
186
|
+
|
|
187
|
+
## Known limits
|
|
188
|
+
|
|
189
|
+
- Grid-wide switches (`disable…`, `rowSelection`, `rowGroupingColumnMode`, `dataSource`) are not
|
|
190
|
+
in the grid's public API. The helper reads them from the grid's internal props, tested with
|
|
191
|
+
`@mui/x-data-grid-premium` 9.18.0. If a later version moves them, the helper warns once and
|
|
192
|
+
skips its own steps that depend on them rather than guess (see above). An optional prop such as
|
|
193
|
+
`dataSource` cannot be told apart from one that moved.
|
|
194
|
+
- With a data source, top N selects at most the rows of the loaded page.
|
|
195
|
+
- In single grouping-column mode, all group levels share one sort direction: the first grouped
|
|
196
|
+
column in the sort decides it.
|
|
197
|
+
- While leaving pivot mode, the grid shows its pre-pivot state for a moment before the answer
|
|
198
|
+
lands.
|
|
199
|
+
- The snapshot leaves out quick-filter text, filter values that are not text, numbers, booleans or
|
|
200
|
+
dates, aggregation functions other than `avg`, `sum`, `min`, `max` and `size`, options past the
|
|
201
|
+
500th, and options that `valueOptions` gives only for a row (it is called with `{ field }` only,
|
|
202
|
+
as by MUI's own assistant).
|
|
203
|
+
- The assistant cannot create, remove or change the type of a chart; it only fills the active one.
|
|
204
|
+
- **Selecting the top rows** differs from MUI's own resolver: the helper selects the first rows that
|
|
205
|
+
pass the filters and are not group rows, even inside a collapsed group, where MUI's selects the
|
|
206
|
+
first visible rows, a group row included. The answer it returns, and the grid stores in the
|
|
207
|
+
conversation, has `select: -1` in place of the number asked for.
|
|
208
|
+
- A chart's aggregation that you change by hand within half a second of an answer that set it is
|
|
209
|
+
put back to the answer's.
|
|
210
|
+
- The description can be incomplete in three cases: an active filter whose operator needs no value
|
|
211
|
+
and is past the column's 64th operator is left out; an option whose label is over 255 characters
|
|
212
|
+
is left out and still counts toward the 500; an aggregation function name over 64 characters is
|
|
213
|
+
left out and still counts toward the 32.
|
|
214
|
+
- The per-grid ordering holds when each grid has its own resolver and passes `apiRef`. Without
|
|
215
|
+
`apiRef`, one resolver shared by two grids makes each wait for the other, and two resolvers on
|
|
216
|
+
one grid do not wait for each other.
|
|
217
|
+
- A column whose field contains `>->` is treated as a pivot column and left out of the helper's
|
|
218
|
+
description: its limits, and its filters, sorting, grouping, aggregation and pivot entries.
|
|
219
|
+
- With no `additionalContext`, the request's `options` is `{}`, where MUI's own resolver sends
|
|
220
|
+
`additionalContext: ''`.
|
|
221
|
+
- Requests use the browser's default credentials mode (cookies only for the same origin). Put a
|
|
222
|
+
cross-origin route's credentials in `headers` or `getToken`.
|
|
223
|
+
|
|
224
|
+
## Exports
|
|
225
|
+
|
|
226
|
+
Everything the package exports, and nothing else, is covered by the versioning rule below.
|
|
227
|
+
|
|
228
|
+
| Export | What it is |
|
|
229
|
+
|---|---|
|
|
230
|
+
| `createPromptResolver(options)` | Returns the grid's `onPrompt`. |
|
|
231
|
+
| `PromptResolver` (type) | The type of what `createPromptResolver` returns: `(prompt, context, conversationId?) => Promise<PromptData>`. |
|
|
232
|
+
| `PromptResolverOptions` (type) | The options in the table above. |
|
|
233
|
+
| `GridsayError` | The class every rejection is an instance of (see Errors). |
|
|
234
|
+
| `CONNECTION_FAILED`, `INVALID_ANSWER`, `NOT_JSON`, `UNAUTHENTICATED_USER` | The sentences (typed as `string`). |
|
|
235
|
+
| `CONNECTION_FAILED_CODE`, `INVALID_ANSWER_CODE`, `NOT_JSON_CODE`, `UNAUTHENTICATED_USER_CODE`, `UNEXPECTED_ERROR_CODE` | The codes. |
|
|
236
|
+
|
|
237
|
+
Entry points: `@gridsay/mui-x-data-grid` (ESM, with its type declarations) and
|
|
238
|
+
`@gridsay/mui-x-data-grid/package.json` (the package's manifest, for tools that read it).
|
|
239
|
+
|
|
240
|
+
## Versioning
|
|
241
|
+
|
|
242
|
+
`@gridsay/mui-x-data-grid` follows semver from its first major release. It pins `@gridsay/core`
|
|
243
|
+
exactly.
|
|
244
|
+
|
|
245
|
+
- **Codes are the contract; sentences are not.** Match on `error.code`. The sentences
|
|
246
|
+
(`error.message`, and the exported `INVALID_ANSWER`, `CONNECTION_FAILED` and the others) are for
|
|
247
|
+
people and may be reworded in a minor.
|
|
248
|
+
- **A major** for anything that breaks what this package exports, whether the change is here or in
|
|
249
|
+
`@gridsay/core`: a removed or changed export, type, option or error code, or a new required
|
|
250
|
+
method or prop on what it accepts from the grid (`apiRef`).
|
|
251
|
+
- **A minor** for what only adds: a new optional field on `GridsayError` or on an answer, a new
|
|
252
|
+
option, a new error code.
|
|
253
|
+
|
|
254
|
+
**What this package promises.** It is tested with `@mui/x-data-grid-premium` 9.18.0. With that
|
|
255
|
+
version, `apiRef` passed, callbacks of yours that do not throw, and any controlled state (such as
|
|
256
|
+
`filterModel`) updated from the grid's change callbacks, an answer the panel shows as applied is what the grid shows, except a chart when no chart is active: the panel lists "Charts" among the applied changes, as with MUI's own resolver, while the grid has no chart to fill. Without `apiRef` the helper cannot see the grid: an answer that leaves pivot
|
|
257
|
+
mode can be overwritten when the grid restores what it showed before the pivot. With controlled
|
|
258
|
+
state your callbacks do not update, the grid keeps your state while the panel reports the answer
|
|
259
|
+
applied. An error thrown by the grid or by your own callbacks during the helper's own steps (reading
|
|
260
|
+
the grid, leaving pivot mode, selecting the top rows, keeping a chart's aggregation) is reported in the console and that step is skipped; when it is thrown while reading your column definitions, the question goes out without a description of the grid. While the grid
|
|
261
|
+
applies the answer itself, an error from your callbacks (such as `onSortModelChange`) is the grid's:
|
|
262
|
+
it stops the answer there, the panel shows its text, and the helper does not see it. On other grid
|
|
263
|
+
versions the behaviour is best effort and failures are reported the same way; a change that makes
|
|
264
|
+
nothing fail is not noticed.
|
|
265
|
+
|
|
266
|
+
Its own types (`PromptResolver`, what `apiRef` accepts) are declared in this package and do not
|
|
267
|
+
change with the grid; they accept what 9.18.0's types do, with `strict` and with
|
|
268
|
+
`exactOptionalPropertyTypes`.
|
|
269
|
+
|
|
270
|
+
To check this package's types against a release of the grid by hand, build it and run
|
|
271
|
+
`node packages/mui-x-data-grid/compat/check.mjs 9.18.0` (or `9` for the newest 9.x). It is not in
|
|
272
|
+
CI, because it installs MUI X Data Grid Premium, a commercial package.
|
|
273
|
+
|
|
274
|
+
`pnpm --filter @gridsay/mui-x-data-grid compare` runs each life-cycle scenario (unmount, a
|
|
275
|
+
replacement, a re-key, a ref swap, two resolvers, strict mode, `<Activity>`, a portal move) on a
|
|
276
|
+
real grid twice, with MUI's own resolver and with this helper, and checks that the grid, the
|
|
277
|
+
panel and your callbacks see the same; it is run by hand for the same reason.
|
|
278
|
+
|
|
279
|
+
Where this stands: [gridsay.com/features#status](https://gridsay.com/features#status). ESM only,
|
|
280
|
+
no runtime dependencies besides `@gridsay/core`.
|
|
281
|
+
|
|
282
|
+
Example: [`examples/mui-x-data-grid`](https://github.com/gridsay/gridsay/tree/main/examples/mui-x-data-grid).
|
|
283
|
+
|
|
284
|
+
Gridsay is an independent product, not affiliated with, sponsored or endorsed by MUI. MUI is a
|
|
285
|
+
trademark of its owner.
|
|
286
|
+
|
|
287
|
+
## Licence
|
|
288
|
+
|
|
289
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { CONNECTION_FAILED_CODE, GridsayError, INVALID_ANSWER_CODE, NOT_JSON_CODE, PromptData, RequestHeaders, RequestOptions, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE } from "@gridsay/core";
|
|
2
|
+
type RowId = string | number;
|
|
3
|
+
type ValueOption = string | number | object;
|
|
4
|
+
/** MUI's `GridFilterItem['operator']`: its operators, or any other string. */
|
|
5
|
+
type FilterOperator = 'contains' | 'doesNotContain' | 'equals' | 'doesNotEqual' | 'startsWith' | 'endsWith' | '=' | '!=' | '>' | '>=' | '<' | '<=' | 'is' | 'not' | 'after' | 'onOrAfter' | 'before' | 'onOrBefore' | 'isEmpty' | 'isNotEmpty' | 'isAnyOf' | (string & {});
|
|
6
|
+
/** The column properties the helper reads. */
|
|
7
|
+
type Column = {
|
|
8
|
+
field: string;
|
|
9
|
+
type?: string;
|
|
10
|
+
filterable?: boolean;
|
|
11
|
+
sortable?: boolean;
|
|
12
|
+
groupable?: boolean;
|
|
13
|
+
pivotable?: boolean;
|
|
14
|
+
aggregable?: boolean;
|
|
15
|
+
availableAggregationFunctions?: string[];
|
|
16
|
+
filterOperators?: readonly {
|
|
17
|
+
value: string;
|
|
18
|
+
requiresFilterValue?: boolean;
|
|
19
|
+
}[];
|
|
20
|
+
valueOptions?: ValueOption[] | ((params: {
|
|
21
|
+
field: string;
|
|
22
|
+
}) => ValueOption[]);
|
|
23
|
+
getOptionValue?: (option: ValueOption) => unknown;
|
|
24
|
+
getOptionLabel?: (option: ValueOption) => string;
|
|
25
|
+
};
|
|
26
|
+
/** The part of the grid API the helper reads and drives: what `apiRef` must point to. */
|
|
27
|
+
type GridApi = {
|
|
28
|
+
getAllColumns: () => Column[];
|
|
29
|
+
getSortedRowIds: () => RowId[];
|
|
30
|
+
getRowNode: (id: RowId) => {
|
|
31
|
+
type: string;
|
|
32
|
+
} | null;
|
|
33
|
+
setRowSelectionModel: (model: {
|
|
34
|
+
type: 'include' | 'exclude';
|
|
35
|
+
ids: Set<RowId>;
|
|
36
|
+
}, reason?: 'singleRowSelection' | 'multipleRowsSelection') => void;
|
|
37
|
+
setAggregationModel: (model: Record<string, string>) => void;
|
|
38
|
+
setPivotActive: (active: boolean | ((prev: boolean) => boolean)) => void;
|
|
39
|
+
subscribeEvent: (event: 'rowsSet' | 'aggregationModelChange', handler: () => void) => () => void;
|
|
40
|
+
rootElementRef: {
|
|
41
|
+
readonly current: {
|
|
42
|
+
readonly isConnected: boolean;
|
|
43
|
+
} | null;
|
|
44
|
+
};
|
|
45
|
+
state: {
|
|
46
|
+
filter: {
|
|
47
|
+
filteredRowsLookup: Record<RowId, false>;
|
|
48
|
+
filterModel: {
|
|
49
|
+
items: {
|
|
50
|
+
id?: number | string;
|
|
51
|
+
field: string;
|
|
52
|
+
operator: FilterOperator;
|
|
53
|
+
value?: unknown;
|
|
54
|
+
}[];
|
|
55
|
+
logicOperator?: 'and' | 'or';
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
sorting: {
|
|
59
|
+
sortModel: readonly {
|
|
60
|
+
field: string;
|
|
61
|
+
sort: 'asc' | 'desc' | null | undefined;
|
|
62
|
+
}[];
|
|
63
|
+
};
|
|
64
|
+
rowGrouping: {
|
|
65
|
+
model: string[];
|
|
66
|
+
};
|
|
67
|
+
aggregation: {
|
|
68
|
+
model: Record<string, string>;
|
|
69
|
+
};
|
|
70
|
+
pivoting: {
|
|
71
|
+
active: boolean;
|
|
72
|
+
model: {
|
|
73
|
+
columns: {
|
|
74
|
+
field: string;
|
|
75
|
+
sort?: 'asc' | 'desc';
|
|
76
|
+
hidden?: boolean;
|
|
77
|
+
}[];
|
|
78
|
+
rows: {
|
|
79
|
+
field: string;
|
|
80
|
+
hidden?: boolean;
|
|
81
|
+
}[];
|
|
82
|
+
values: {
|
|
83
|
+
field: string;
|
|
84
|
+
aggFunc: string;
|
|
85
|
+
hidden?: boolean;
|
|
86
|
+
}[];
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
chartsIntegration: {
|
|
90
|
+
activeChartId: string;
|
|
91
|
+
};
|
|
92
|
+
rows: {
|
|
93
|
+
loading?: boolean;
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* The grid's `onPrompt`, declared here so a grid release cannot change it. A test checks it still
|
|
99
|
+
* fits the grid's own prop at the tested version.
|
|
100
|
+
*/
|
|
101
|
+
type PromptResolver = (prompt: string, context: string, conversationId?: string) => Promise<PromptData>;
|
|
102
|
+
export declare const CONNECTION_FAILED: string;
|
|
103
|
+
export declare const INVALID_ANSWER: string;
|
|
104
|
+
export declare const NOT_JSON: string;
|
|
105
|
+
export declare const UNAUTHENTICATED_USER: string;
|
|
106
|
+
export type PromptResolverOptions = {
|
|
107
|
+
/** Where the prompt is posted: your own proxy route, or the Gridsay gateway. */
|
|
108
|
+
url: string;
|
|
109
|
+
/** With it, the helper describes the grid to the server and adapts answers to the grid. */
|
|
110
|
+
apiRef?: {
|
|
111
|
+
readonly current: GridApi | null;
|
|
112
|
+
} | undefined;
|
|
113
|
+
/** Added to each request. */
|
|
114
|
+
headers?: RequestHeaders | (() => RequestHeaders | Promise<RequestHeaders>) | undefined;
|
|
115
|
+
/** A publishable key, sent as `x-api-key`. */
|
|
116
|
+
publishableKey?: string | undefined;
|
|
117
|
+
/** The end user's token, fetched for every request and sent as a bearer token. */
|
|
118
|
+
getToken?: RequestOptions['getToken'] | undefined;
|
|
119
|
+
additionalContext?: string | undefined;
|
|
120
|
+
privateMode?: boolean | undefined;
|
|
121
|
+
/** Your id for the end user. */
|
|
122
|
+
referenceId?: string | undefined;
|
|
123
|
+
};
|
|
124
|
+
/** Replaces `unstable_gridDefaultPromptResolver` as the grid's `onPrompt`. */
|
|
125
|
+
export declare function createPromptResolver(options: PromptResolverOptions): PromptResolver;
|
|
126
|
+
export { CONNECTION_FAILED_CODE, GridsayError, INVALID_ANSWER_CODE, NOT_JSON_CODE, type PromptResolver, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,833 @@
|
|
|
1
|
+
import * as core from "@gridsay/core";
|
|
2
|
+
import { CONNECTION_FAILED_CODE, CONNECTION_FAILED_CODE as CONNECTION_FAILED_CODE$1, GridsayError, GridsayError as GridsayError$1, INVALID_ANSWER_CODE, NOT_JSON_CODE, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE, UNEXPECTED_ERROR_CODE as UNEXPECTED_ERROR_CODE$1 } from "@gridsay/core";
|
|
3
|
+
import { isRecord, promptOptionsOf, readResponse, requestHeaders } from "@gridsay/core/internal";
|
|
4
|
+
// src/boundary.ts
|
|
5
|
+
/** Root props the grid always fills in, with its defaults, in the tested release. */
|
|
6
|
+
const SWITCHES = [
|
|
7
|
+
"disableColumnFilter",
|
|
8
|
+
"disableColumnSorting",
|
|
9
|
+
"disableRowGrouping",
|
|
10
|
+
"disableAggregation",
|
|
11
|
+
"disablePivoting",
|
|
12
|
+
"rowSelection",
|
|
13
|
+
"rowGroupingColumnMode"
|
|
14
|
+
];
|
|
15
|
+
/** How often a wait checks that its grid's root is still in the document. */
|
|
16
|
+
const DETACH_CHECK_MS = 50;
|
|
17
|
+
const fail = (what) => {
|
|
18
|
+
throw new TypeError(`${what} is missing or not in the shape the tested grid release has`);
|
|
19
|
+
};
|
|
20
|
+
const isString = (value) => typeof value === "string";
|
|
21
|
+
const list = (value, what) => Array.isArray(value) ? value : fail(what);
|
|
22
|
+
const record = (value, what) => isRecord(value) ? value : fail(what);
|
|
23
|
+
const string = (value, what) => isString(value) ? value : fail(what);
|
|
24
|
+
const optional = (value, check, what) => value === void 0 || check(value) ? value : fail(what);
|
|
25
|
+
const isDirection = (value) => value === "asc" || value === "desc";
|
|
26
|
+
const isBoolean = (value) => typeof value === "boolean";
|
|
27
|
+
/**
|
|
28
|
+
* The one boundary between the helper and the grid, for one question on one grid. Every call
|
|
29
|
+
* goes through `use`, which never throws: a call that throws, or a part that is missing or in
|
|
30
|
+
* another shape, is handed to `failed` with what was thrown, and gives nothing. Nothing is called
|
|
31
|
+
* once the grid is no longer the one on `apiRef`.
|
|
32
|
+
*/
|
|
33
|
+
/**
|
|
34
|
+
* Thrown inside the helper when the grid cannot be described: it was found detached, or the app's
|
|
35
|
+
* column functions threw. The question then goes out without a description, as from MUI's resolver.
|
|
36
|
+
*/
|
|
37
|
+
var Undescribed = class extends Error {};
|
|
38
|
+
/** For the generated test: how deep inside the one gate to the grid the helper is now. */
|
|
39
|
+
const gate = { depth: 0 };
|
|
40
|
+
var Grid = class {
|
|
41
|
+
failed;
|
|
42
|
+
/** Set once any access found the grid detached: a description read so far is then dropped. */
|
|
43
|
+
detached = false;
|
|
44
|
+
ref;
|
|
45
|
+
constructor(api, failed) {
|
|
46
|
+
this.failed = failed;
|
|
47
|
+
this.ref = api instanceof WeakRef ? api : new WeakRef(api);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The grid, when it can take the helper's reads and writes: its root element exists and is in
|
|
51
|
+
* the document. Checked immediately before every access, which all go through `use` and
|
|
52
|
+
* `column`. With React 19.3.1, hiding the grid under `<Activity>` clears its root ref, so a
|
|
53
|
+
* hidden grid counts as not connected and gets the stock handling. The helper never decides
|
|
54
|
+
* that a grid is gone.
|
|
55
|
+
*/
|
|
56
|
+
live() {
|
|
57
|
+
const api = this.ref.deref();
|
|
58
|
+
if (!api) return void 0;
|
|
59
|
+
try {
|
|
60
|
+
const ref = record(api.rootElementRef, "rootElementRef");
|
|
61
|
+
if (!("current" in ref)) fail("rootElementRef.current");
|
|
62
|
+
const root = ref.current;
|
|
63
|
+
if (isRecord(root) && root.isConnected === true) return api;
|
|
64
|
+
} catch (error) {
|
|
65
|
+
this.failed({
|
|
66
|
+
member: "rootElementRef",
|
|
67
|
+
error
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
this.detached = true;
|
|
71
|
+
}
|
|
72
|
+
connected() {
|
|
73
|
+
return this.live() !== void 0;
|
|
74
|
+
}
|
|
75
|
+
/** The one gate to the grid: checks that it is connected, then calls; never throws. */
|
|
76
|
+
use(member, call) {
|
|
77
|
+
const api = this.live();
|
|
78
|
+
if (!api) return void 0;
|
|
79
|
+
gate.depth += 1;
|
|
80
|
+
try {
|
|
81
|
+
return { value: call(api) };
|
|
82
|
+
} catch (error) {
|
|
83
|
+
this.failed({
|
|
84
|
+
member,
|
|
85
|
+
error
|
|
86
|
+
});
|
|
87
|
+
return;
|
|
88
|
+
} finally {
|
|
89
|
+
gate.depth -= 1;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Reads from the app's own column definitions and functions (`valueOptions`, `getOptionValue`,
|
|
94
|
+
* `getOptionLabel`), and everything read from what they return, through the same gate. A
|
|
95
|
+
* detached grid, or anything thrown there, makes the grid undescribed: the throw is reported,
|
|
96
|
+
* and the question goes out without a description.
|
|
97
|
+
*/
|
|
98
|
+
column(read) {
|
|
99
|
+
if (!this.live()) throw new Undescribed();
|
|
100
|
+
gate.depth += 1;
|
|
101
|
+
try {
|
|
102
|
+
return read();
|
|
103
|
+
} catch (error) {
|
|
104
|
+
if (error instanceof Undescribed) throw error;
|
|
105
|
+
if (this.live()) this.failed({
|
|
106
|
+
member: "column functions",
|
|
107
|
+
error
|
|
108
|
+
});
|
|
109
|
+
throw new Undescribed();
|
|
110
|
+
} finally {
|
|
111
|
+
gate.depth -= 1;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** Inside `column`: before each further call into the app's functions, the grid is still there. */
|
|
115
|
+
still() {
|
|
116
|
+
if (!this.live()) throw new Undescribed();
|
|
117
|
+
}
|
|
118
|
+
/** The columns. When they cannot be read, whatever was thrown, the grid is not described. */
|
|
119
|
+
columns() {
|
|
120
|
+
const api = this.live();
|
|
121
|
+
if (!api) throw new Undescribed();
|
|
122
|
+
gate.depth += 1;
|
|
123
|
+
try {
|
|
124
|
+
const columns = api.getAllColumns();
|
|
125
|
+
return Array.isArray(columns) ? columns : fail("getAllColumns()");
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (this.live()) this.failed({
|
|
128
|
+
member: "getAllColumns",
|
|
129
|
+
error
|
|
130
|
+
});
|
|
131
|
+
throw new Undescribed();
|
|
132
|
+
} finally {
|
|
133
|
+
gate.depth -= 1;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/** Anything else thrown while describing the grid: reported, and the grid is not described. */
|
|
137
|
+
undescribed(error) {
|
|
138
|
+
if (!(error instanceof Undescribed)) this.failed({
|
|
139
|
+
member: "the description",
|
|
140
|
+
error
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Grid-wide props. The public API does not expose them, so they are read from the private API
|
|
145
|
+
* the grid keeps on `apiRef.current`. When any cannot be read, nothing is guessed.
|
|
146
|
+
*/
|
|
147
|
+
switches() {
|
|
148
|
+
const props = this.use("privateApi", (api) => {
|
|
149
|
+
const symbol = Object.getOwnPropertySymbols(api).find((s) => s.description === "mui.api_private");
|
|
150
|
+
const privateApi = symbol ? Reflect.get(api, symbol) : void 0;
|
|
151
|
+
return record(record(privateApi, "the private API").rootProps, "the private API");
|
|
152
|
+
})?.value;
|
|
153
|
+
if (!props) return void 0;
|
|
154
|
+
const values = {};
|
|
155
|
+
let complete = true;
|
|
156
|
+
for (const key of SWITCHES) {
|
|
157
|
+
const read = this.use(`rootProps.${key}`, () => {
|
|
158
|
+
const value = key in props ? props[key] : fail(key);
|
|
159
|
+
return (key === "rowGroupingColumnMode" ? value === void 0 || value === "single" || value === "multiple" : value === void 0 || isBoolean(value)) ? value : fail(key);
|
|
160
|
+
});
|
|
161
|
+
if (read) values[key] = read.value;
|
|
162
|
+
else complete = false;
|
|
163
|
+
}
|
|
164
|
+
const dataSource = this.use("rootProps.dataSource", () => props.dataSource != null);
|
|
165
|
+
if (!complete || !dataSource) return void 0;
|
|
166
|
+
return {
|
|
167
|
+
filtering: values.disableColumnFilter !== true,
|
|
168
|
+
sorting: values.disableColumnSorting !== true,
|
|
169
|
+
grouping: values.disableRowGrouping !== true,
|
|
170
|
+
aggregation: values.disableAggregation !== true,
|
|
171
|
+
pivoting: values.disablePivoting !== true,
|
|
172
|
+
selection: values.rowSelection === true,
|
|
173
|
+
multipleGroupingColumns: values.rowGroupingColumnMode === "multiple",
|
|
174
|
+
dataSource: dataSource.value
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
filterModel() {
|
|
178
|
+
return this.use("state.filter.filterModel", (api) => {
|
|
179
|
+
const model = record(api.state.filter.filterModel, "filterModel");
|
|
180
|
+
return {
|
|
181
|
+
items: list(model.items, "filterModel.items").map((item) => {
|
|
182
|
+
const { field, operator, value } = record(item, "a filter item");
|
|
183
|
+
return {
|
|
184
|
+
field: string(field, "a filter item"),
|
|
185
|
+
operator: string(operator, "a filter item"),
|
|
186
|
+
value
|
|
187
|
+
};
|
|
188
|
+
}),
|
|
189
|
+
or: model.logicOperator === "or"
|
|
190
|
+
};
|
|
191
|
+
})?.value;
|
|
192
|
+
}
|
|
193
|
+
sortModel() {
|
|
194
|
+
return this.use("state.sorting.sortModel", (api) => list(api.state.sorting.sortModel, "sortModel").map((item) => {
|
|
195
|
+
const { field, sort } = record(item, "a sort item");
|
|
196
|
+
return {
|
|
197
|
+
field: string(field, "a sort item"),
|
|
198
|
+
sort: isDirection(sort) ? sort : null
|
|
199
|
+
};
|
|
200
|
+
}))?.value;
|
|
201
|
+
}
|
|
202
|
+
rowGroupingModel() {
|
|
203
|
+
return this.use("state.rowGrouping.model", (api) => list(api.state.rowGrouping.model, "rowGrouping.model").map((f) => string(f, "a grouping")))?.value;
|
|
204
|
+
}
|
|
205
|
+
aggregationModel() {
|
|
206
|
+
return this.use("state.aggregation.model", (api) => {
|
|
207
|
+
const model = record(api.state.aggregation.model, "aggregation.model");
|
|
208
|
+
return Object.fromEntries(Object.entries(model).map(([field, fn]) => [field, string(fn, "an aggregation")]));
|
|
209
|
+
})?.value;
|
|
210
|
+
}
|
|
211
|
+
pivotActive() {
|
|
212
|
+
return this.use("state.pivoting.active", (api) => {
|
|
213
|
+
const active = api.state.pivoting.active;
|
|
214
|
+
return isBoolean(active) ? active : fail("pivoting.active");
|
|
215
|
+
})?.value;
|
|
216
|
+
}
|
|
217
|
+
pivotModel() {
|
|
218
|
+
return this.use("state.pivoting.model", (api) => {
|
|
219
|
+
const model = record(api.state.pivoting.model, "pivoting.model");
|
|
220
|
+
const entry = (item) => {
|
|
221
|
+
const { field, hidden } = record(item, "a pivot entry");
|
|
222
|
+
return {
|
|
223
|
+
field: string(field, "a pivot entry"),
|
|
224
|
+
hidden: optional(hidden, isBoolean, "a pivot entry")
|
|
225
|
+
};
|
|
226
|
+
};
|
|
227
|
+
return {
|
|
228
|
+
columns: list(model.columns, "pivoting.model.columns").map((item) => ({
|
|
229
|
+
...entry(item),
|
|
230
|
+
sort: optional(record(item, "a pivot column").sort, isDirection, "a pivot column")
|
|
231
|
+
})),
|
|
232
|
+
rows: list(model.rows, "pivoting.model.rows").map(entry),
|
|
233
|
+
values: list(model.values, "pivoting.model.values").map((item) => ({
|
|
234
|
+
...entry(item),
|
|
235
|
+
aggFunc: string(record(item, "a pivot value").aggFunc, "a pivot value")
|
|
236
|
+
}))
|
|
237
|
+
};
|
|
238
|
+
})?.value;
|
|
239
|
+
}
|
|
240
|
+
/** The active chart's id, `''` for none. */
|
|
241
|
+
activeChart() {
|
|
242
|
+
return this.use("state.chartsIntegration.activeChartId", (api) => string(api.state.chartsIntegration.activeChartId, "activeChartId"))?.value;
|
|
243
|
+
}
|
|
244
|
+
rowsLoading() {
|
|
245
|
+
return this.use("state.rows.loading", (api) => {
|
|
246
|
+
const rows = record(api.state.rows, "state.rows");
|
|
247
|
+
if (!("loading" in rows)) fail("rows.loading");
|
|
248
|
+
return optional(rows.loading, isBoolean, "rows.loading") ?? false;
|
|
249
|
+
})?.value;
|
|
250
|
+
}
|
|
251
|
+
/** True once the grid took the call. */
|
|
252
|
+
leavePivot() {
|
|
253
|
+
return this.use("setPivotActive", (api) => api.setPivotActive(false)) !== void 0;
|
|
254
|
+
}
|
|
255
|
+
setAggregation(model) {
|
|
256
|
+
return this.use("setAggregationModel", (api) => api.setAggregationModel(model)) !== void 0;
|
|
257
|
+
}
|
|
258
|
+
/** Selects the first `count` visible leaf rows; true once the grid took the selection. */
|
|
259
|
+
selectTop(count) {
|
|
260
|
+
const ids = this.use("getSortedRowIds", (api) => list(api.getSortedRowIds(), "getSortedRowIds()").map((id) => isString(id) || typeof id === "number" ? id : fail("a row id")))?.value;
|
|
261
|
+
const lookup = this.use("state.filter.filteredRowsLookup", (api) => ({ ...record(api.state.filter.filteredRowsLookup, "filteredRowsLookup") }))?.value;
|
|
262
|
+
if (!ids || !lookup) return false;
|
|
263
|
+
const picked = [];
|
|
264
|
+
for (const id of ids) {
|
|
265
|
+
if (picked.length >= count) break;
|
|
266
|
+
if (lookup[id] === false) continue;
|
|
267
|
+
const node = this.use("getRowNode", (api) => api.getRowNode(id));
|
|
268
|
+
if (!node) return false;
|
|
269
|
+
const type = this.use("getRowNode().type", () => node.value === null ? null : string(record(node.value, "a row node").type, "a row node type"));
|
|
270
|
+
if (!type) return false;
|
|
271
|
+
if (type.value === "leaf") picked.push(id);
|
|
272
|
+
}
|
|
273
|
+
return this.use("setRowSelectionModel", (api) => api.setRowSelectionModel({
|
|
274
|
+
type: "include",
|
|
275
|
+
ids: new Set(picked)
|
|
276
|
+
})) !== void 0;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Waits for `event`, at most `timeout` ms, and always settles: on the event (when `onEvent`
|
|
280
|
+
* gives true or is left out), at the timeout, at once when the grid is detached, or when a call
|
|
281
|
+
* throws (`onEvent` gives undefined). It settles before cleaning up, so nothing thrown while
|
|
282
|
+
* unsubscribing can hold a question. `cancel` settles it as `failed`.
|
|
283
|
+
*/
|
|
284
|
+
wait(event, timeout, onEvent = () => true) {
|
|
285
|
+
let finish = () => {};
|
|
286
|
+
let subscribed = false;
|
|
287
|
+
const settled = new Promise((resolve) => {
|
|
288
|
+
let done = false;
|
|
289
|
+
let unsubscribe;
|
|
290
|
+
let timer;
|
|
291
|
+
let watch;
|
|
292
|
+
finish = (result) => {
|
|
293
|
+
if (done) return;
|
|
294
|
+
done = true;
|
|
295
|
+
resolve(result);
|
|
296
|
+
clearTimeout(timer);
|
|
297
|
+
clearInterval(watch);
|
|
298
|
+
const off = unsubscribe?.value;
|
|
299
|
+
if (unsubscribe) try {
|
|
300
|
+
if (typeof off !== "function") return fail("the unsubscribe function");
|
|
301
|
+
off();
|
|
302
|
+
} catch (error) {
|
|
303
|
+
this.failed({
|
|
304
|
+
member: "unsubscribe",
|
|
305
|
+
error
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
if (!this.connected()) return finish("detached");
|
|
310
|
+
timer = setTimeout(() => finish("timeout"), timeout);
|
|
311
|
+
watch = setInterval(() => {
|
|
312
|
+
if (!this.connected()) finish("detached");
|
|
313
|
+
}, DETACH_CHECK_MS);
|
|
314
|
+
unsubscribe = this.use("subscribeEvent", (api) => api.subscribeEvent(event, () => {
|
|
315
|
+
if (done) return;
|
|
316
|
+
if (!this.connected()) return finish("detached");
|
|
317
|
+
const stop = onEvent();
|
|
318
|
+
if (stop === void 0) finish("failed");
|
|
319
|
+
else if (stop) finish("event");
|
|
320
|
+
}));
|
|
321
|
+
subscribed = unsubscribe !== void 0;
|
|
322
|
+
if (!unsubscribe) finish(this.connected() ? "failed" : "detached");
|
|
323
|
+
});
|
|
324
|
+
return Object.assign(settled, {
|
|
325
|
+
cancel: () => finish("failed"),
|
|
326
|
+
subscribed
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
// src/grid.ts
|
|
331
|
+
/** Generated grouping columns, as exported by the grid (`GRID_ROW_GROUPING_SINGLE_GROUPING_FIELD`). */
|
|
332
|
+
const SINGLE_GROUPING_FIELD = "__row_group_by_columns_group__";
|
|
333
|
+
const groupingField = (column) => `__row_group_by_columns_group_${column}__`;
|
|
334
|
+
/** The grid release this helper release is tested with. */
|
|
335
|
+
const TESTED_GRID = "@mui/x-data-grid-premium 9.18.0";
|
|
336
|
+
/** Printed once per resolver, followed by what was thrown, when part of the grid failed. */
|
|
337
|
+
const gridWarning = (members) => `@gridsay/mui-x-data-grid: part of the grid could not be read or changed (${[...new Set(members)].join(", ")}). This helper is tested with ${TESTED_GRID}: the grid may be a version it was not tested with, or a callback of yours threw (what was thrown follows). The helper does not guess: until a helper release names your grid version as tested, it leaves that part out of what it sends and skips its own steps that depend on it (for the grid's settings or pivot mode: moving a grouped column's sort to the grouping column, selecting the top rows, keeping a chart's aggregation). Questions still go ahead, and the grid applies each answer as it does by default.`;
|
|
338
|
+
const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
339
|
+
/** Sorting a grouped column must target the grouping column, or group headers keep their order. */
|
|
340
|
+
function sortGroups(data, multiple) {
|
|
341
|
+
const grouped = new Set(data.grouping.map((g) => g.column));
|
|
342
|
+
const seen = /* @__PURE__ */ new Set();
|
|
343
|
+
return data.sorting.flatMap((sort) => {
|
|
344
|
+
if (!grouped.has(sort.column)) return [sort];
|
|
345
|
+
const column = multiple ? groupingField(sort.column) : SINGLE_GROUPING_FIELD;
|
|
346
|
+
if (seen.has(column)) return [];
|
|
347
|
+
seen.add(column);
|
|
348
|
+
return [{
|
|
349
|
+
...sort,
|
|
350
|
+
column
|
|
351
|
+
}];
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Leaves pivot mode and waits for the grid to restore its rows. True only once the grid is seen
|
|
356
|
+
* out of pivot mode: the steps after it assume that.
|
|
357
|
+
*/
|
|
358
|
+
async function leavePivot(grid) {
|
|
359
|
+
const restored = grid.wait("rowsSet", 1e3);
|
|
360
|
+
if (!restored.subscribed) return false;
|
|
361
|
+
if (!grid.leavePivot() && grid.pivotActive() !== false) {
|
|
362
|
+
restored.cancel();
|
|
363
|
+
return false;
|
|
364
|
+
}
|
|
365
|
+
const result = await restored;
|
|
366
|
+
if (result === "failed" || result === "detached") return false;
|
|
367
|
+
await tick();
|
|
368
|
+
return grid.connected() && grid.pivotActive() === false;
|
|
369
|
+
}
|
|
370
|
+
/** Selects the top rows once they are this answer's: never rows of a page still loading. */
|
|
371
|
+
async function selectWhenLoaded(grid, top, dataSource) {
|
|
372
|
+
if (dataSource) {
|
|
373
|
+
await tick();
|
|
374
|
+
if (!grid.connected()) return;
|
|
375
|
+
const loading = grid.rowsLoading();
|
|
376
|
+
if (loading === void 0) return;
|
|
377
|
+
if (loading) {
|
|
378
|
+
if (await grid.wait("rowsSet", 15e3) !== "event") return;
|
|
379
|
+
await tick();
|
|
380
|
+
if (!grid.connected() || grid.rowsLoading() !== false) return;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (grid.connected()) grid.selectTop(top);
|
|
384
|
+
}
|
|
385
|
+
const sameAggregation = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((k) => a[k] === b[k]);
|
|
386
|
+
/** The charts integration writes back a stale aggregation model a render after a chart update. */
|
|
387
|
+
const keepAggregation = (grid, aggregation) => grid.wait("aggregationModelChange", 500, () => {
|
|
388
|
+
const model = grid.aggregationModel();
|
|
389
|
+
if (!model) return void 0;
|
|
390
|
+
if (!sameAggregation(model, aggregation) && !grid.setAggregation(aggregation)) return void 0;
|
|
391
|
+
return false;
|
|
392
|
+
});
|
|
393
|
+
/**
|
|
394
|
+
* Prepares a checked answer for the grid. `response` goes back to the grid, which applies it
|
|
395
|
+
* synchronously; `applied` settles once the helper has finished its own changes after that.
|
|
396
|
+
* Each step runs only on what the steps before it confirmed; the rest is left to the grid.
|
|
397
|
+
*/
|
|
398
|
+
async function adapt(grid, data) {
|
|
399
|
+
const asItIs = {
|
|
400
|
+
response: data,
|
|
401
|
+
applied: Promise.resolve()
|
|
402
|
+
};
|
|
403
|
+
if (!grid.connected()) return asItIs;
|
|
404
|
+
const on = grid.switches();
|
|
405
|
+
const pivots = (on ? on.pivoting : true) && "columns" in data.pivoting;
|
|
406
|
+
let layoutKnown = true;
|
|
407
|
+
if (!pivots) {
|
|
408
|
+
const active = grid.pivotActive();
|
|
409
|
+
layoutKnown = active === false || active === true && await leavePivot(grid);
|
|
410
|
+
if (!grid.connected()) return asItIs;
|
|
411
|
+
}
|
|
412
|
+
const response = {
|
|
413
|
+
...data,
|
|
414
|
+
select: -1
|
|
415
|
+
};
|
|
416
|
+
if (!on || !layoutKnown) return {
|
|
417
|
+
response,
|
|
418
|
+
applied: Promise.resolve()
|
|
419
|
+
};
|
|
420
|
+
if (on.grouping && !pivots && !on.dataSource && data.grouping.length > 0) response.sorting = sortGroups(data, on.multipleGroupingColumns);
|
|
421
|
+
const top = on.selection && data.select > 0 ? data.select : 0;
|
|
422
|
+
const charted = data.chart && !pivots && on.aggregation && grid.activeChart();
|
|
423
|
+
return {
|
|
424
|
+
response,
|
|
425
|
+
applied: (async () => {
|
|
426
|
+
const kept = charted ? keepAggregation(grid, data.aggregation) : void 0;
|
|
427
|
+
await tick();
|
|
428
|
+
if (top > 0 && grid.connected()) await selectWhenLoaded(grid, top, on.dataSource);
|
|
429
|
+
await kept;
|
|
430
|
+
})()
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
// src/queue.ts
|
|
434
|
+
/** The answer for the grid, adapted when there is a grid to adapt it to. */
|
|
435
|
+
async function finish(grid, data) {
|
|
436
|
+
return grid ? adapt(grid, data) : {
|
|
437
|
+
response: data,
|
|
438
|
+
applied: Promise.resolve()
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* The one bound on the line: a question waits at most this long for the one before it on the same
|
|
443
|
+
* grid, then is sent anyway. The request itself, like MUI's own resolver's, has no time limit.
|
|
444
|
+
*/
|
|
445
|
+
const QUEUE_WAIT_MS = 6e4;
|
|
446
|
+
/** `promise`, or nothing once `ms` have passed; the timer never outlives it. */
|
|
447
|
+
function atMost(promise, ms) {
|
|
448
|
+
let timer;
|
|
449
|
+
const elapsed = new Promise((resolve) => {
|
|
450
|
+
timer = setTimeout(resolve, ms);
|
|
451
|
+
});
|
|
452
|
+
return Promise.race([promise, elapsed]).finally(() => clearTimeout(timer));
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* One line per grid API instance, shared by every resolver created for that grid (the README's
|
|
456
|
+
* `useMemo` makes a new one when `apiRef` changes), kept weakly: a grid that is gone takes its line.
|
|
457
|
+
*/
|
|
458
|
+
const lines = /* @__PURE__ */ new WeakMap();
|
|
459
|
+
const lineOf = (api) => {
|
|
460
|
+
let line = lines.get(api);
|
|
461
|
+
if (!line) {
|
|
462
|
+
line = { queue: Promise.resolve() };
|
|
463
|
+
lines.set(api, line);
|
|
464
|
+
}
|
|
465
|
+
return line;
|
|
466
|
+
};
|
|
467
|
+
/**
|
|
468
|
+
* One prompt at a time per grid, so a follow-up is sent after the previous answer is on it. Each
|
|
469
|
+
* question carries exactly the conversation id the grid gave it, as with MUI's own resolver.
|
|
470
|
+
*/
|
|
471
|
+
function oneAtATime(send, grid) {
|
|
472
|
+
const unbound = { queue: Promise.resolve() };
|
|
473
|
+
return (query, context, conversationId) => {
|
|
474
|
+
const api = grid();
|
|
475
|
+
const own = api ? lineOf(api) : unbound;
|
|
476
|
+
const weak = api ? new WeakRef(api) : null;
|
|
477
|
+
const result = atMost(own.queue, QUEUE_WAIT_MS).then(() => send(query, context, conversationId, weak));
|
|
478
|
+
own.queue = result.then((sent) => sent.applied).catch(() => void 0);
|
|
479
|
+
return result.then((sent) => sent.response);
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
// src/snapshot.ts
|
|
483
|
+
const FUNCTIONS = [
|
|
484
|
+
"avg",
|
|
485
|
+
"sum",
|
|
486
|
+
"min",
|
|
487
|
+
"max",
|
|
488
|
+
"size"
|
|
489
|
+
];
|
|
490
|
+
const isFunction = (fn) => FUNCTIONS.includes(fn);
|
|
491
|
+
const PIVOT_SEPARATOR = ">->";
|
|
492
|
+
/** A column the grid generated, or one named after cell values: never written into the description. */
|
|
493
|
+
const isGenerated = (field) => field.startsWith("__") && field.endsWith("__") || field.includes(PIVOT_SEPARATOR);
|
|
494
|
+
const OPTIONS = 500;
|
|
495
|
+
const AGGREGATION_FUNCTIONS = 32;
|
|
496
|
+
const OPERATORS = 64;
|
|
497
|
+
/**
|
|
498
|
+
* One read of a property of something the app gave, with the grid checked just before it: nothing
|
|
499
|
+
* the app holds is read once the grid has left the document.
|
|
500
|
+
*/
|
|
501
|
+
function at(grid, object, key) {
|
|
502
|
+
grid.still();
|
|
503
|
+
return object[key];
|
|
504
|
+
}
|
|
505
|
+
/** At most `limit` elements of an array, each read once by index: no iterator, nothing past the limit. */
|
|
506
|
+
function firstOf(grid, given, limit) {
|
|
507
|
+
if (!Array.isArray(given)) return [];
|
|
508
|
+
const length = Math.min(Number(at(grid, given, "length")) || 0, limit);
|
|
509
|
+
const copy = [];
|
|
510
|
+
for (let i = 0; i < length; i++) copy.push(at(grid, given, i));
|
|
511
|
+
return copy;
|
|
512
|
+
}
|
|
513
|
+
/** Calls one of the app's column functions as MUI does: as the column's method. */
|
|
514
|
+
function call(grid, fn, column, argument) {
|
|
515
|
+
grid.still();
|
|
516
|
+
return fn.call(column, argument);
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* A select column's options, read as MUI reads them: `valueOptions` called as the column's method
|
|
520
|
+
* with `{ field }`, then the column's `getOptionValue` and `getOptionLabel` as its methods, once
|
|
521
|
+
* per option, for at most the first 500 options. Without them, MUI's defaults for the type.
|
|
522
|
+
*/
|
|
523
|
+
function readOptions(grid, column, field) {
|
|
524
|
+
const valueOptions = at(grid, column, "valueOptions");
|
|
525
|
+
const getValue = at(grid, column, "getOptionValue");
|
|
526
|
+
const getLabel = at(grid, column, "getOptionLabel");
|
|
527
|
+
const given = typeof valueOptions === "function" ? call(grid, valueOptions, column, { field }) : valueOptions;
|
|
528
|
+
const options = [];
|
|
529
|
+
for (const option of firstOf(grid, given, OPTIONS)) {
|
|
530
|
+
const object = isRecord(option);
|
|
531
|
+
const value = typeof getValue === "function" ? call(grid, getValue, column, option) : object ? at(grid, option, "value") : option;
|
|
532
|
+
const label = typeof getLabel === "function" ? call(grid, getLabel, column, option) : object ? at(grid, option, "label") : String(option);
|
|
533
|
+
const text = typeof label === "number" ? String(label) : label;
|
|
534
|
+
if (typeof text !== "string" || text.length > 255) continue;
|
|
535
|
+
if (typeof value === "number" || typeof value === "string" && value.length <= 255) options.push({
|
|
536
|
+
value,
|
|
537
|
+
label: text
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
return options;
|
|
541
|
+
}
|
|
542
|
+
/** Copies what the description needs from one column, reading each property once. */
|
|
543
|
+
function copyColumn(grid, column) {
|
|
544
|
+
const field = at(grid, column, "field");
|
|
545
|
+
if (typeof field !== "string" || isGenerated(field) || field.length > 255) return void 0;
|
|
546
|
+
const type = at(grid, column, "type");
|
|
547
|
+
const limits = {};
|
|
548
|
+
for (const flag of [
|
|
549
|
+
"filterable",
|
|
550
|
+
"sortable",
|
|
551
|
+
"groupable",
|
|
552
|
+
"pivotable",
|
|
553
|
+
"aggregable"
|
|
554
|
+
]) if (at(grid, column, flag) === false) limits[flag] = false;
|
|
555
|
+
const available = at(grid, column, "availableAggregationFunctions");
|
|
556
|
+
if (Array.isArray(available)) limits.aggregationFunctions = firstOf(grid, available, AGGREGATION_FUNCTIONS).filter((fn) => typeof fn === "string" && fn.length <= 64);
|
|
557
|
+
if (type === "singleSelect" || type === "multiSelect") {
|
|
558
|
+
const options = readOptions(grid, column, field);
|
|
559
|
+
if (options.length > 0) limits.options = options;
|
|
560
|
+
}
|
|
561
|
+
return {
|
|
562
|
+
field,
|
|
563
|
+
limits,
|
|
564
|
+
operators: firstOf(grid, at(grid, column, "filterOperators"), OPERATORS).map((operator) => isRecord(operator) ? {
|
|
565
|
+
value: at(grid, operator, "value"),
|
|
566
|
+
requiresFilterValue: at(grid, operator, "requiresFilterValue")
|
|
567
|
+
} : {
|
|
568
|
+
value: void 0,
|
|
569
|
+
requiresFilterValue: void 0
|
|
570
|
+
})
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* MUI's column context with each option list cut to its first 500 options, each to its value and
|
|
575
|
+
* label: what else an app or `getPivotDerivedColumns` attaches to an option stays in the browser.
|
|
576
|
+
* A context with no option list goes exactly as the grid built it.
|
|
577
|
+
*/
|
|
578
|
+
function boundedContext(context) {
|
|
579
|
+
let columns;
|
|
580
|
+
try {
|
|
581
|
+
columns = JSON.parse(context);
|
|
582
|
+
} catch {
|
|
583
|
+
return context;
|
|
584
|
+
}
|
|
585
|
+
if (!Array.isArray(columns) || !columns.some((c) => isRecord(c) && "valueOptions" in c)) return context;
|
|
586
|
+
return JSON.stringify(columns.map((column) => {
|
|
587
|
+
if (!isRecord(column) || !("valueOptions" in column)) return column;
|
|
588
|
+
const { valueOptions, ...rest } = column;
|
|
589
|
+
if (!Array.isArray(valueOptions)) return rest;
|
|
590
|
+
const options = valueOptions.slice(0, OPTIONS).flatMap((option) => {
|
|
591
|
+
const plain = (value) => [
|
|
592
|
+
"string",
|
|
593
|
+
"number",
|
|
594
|
+
"boolean"
|
|
595
|
+
].includes(typeof value);
|
|
596
|
+
if (!isRecord(option)) return plain(option) ? [option] : [];
|
|
597
|
+
const { value, label } = option;
|
|
598
|
+
return plain(value) && (label === void 0 || plain(label)) ? [{
|
|
599
|
+
value,
|
|
600
|
+
label
|
|
601
|
+
}] : [];
|
|
602
|
+
});
|
|
603
|
+
return {
|
|
604
|
+
...rest,
|
|
605
|
+
valueOptions: options
|
|
606
|
+
};
|
|
607
|
+
}));
|
|
608
|
+
}
|
|
609
|
+
function toFilterValue(value) {
|
|
610
|
+
if (typeof value === "string" || typeof value === "boolean") return value;
|
|
611
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
612
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? void 0 : value.toISOString();
|
|
613
|
+
if (!Array.isArray(value)) return void 0;
|
|
614
|
+
const items = Array.from({ length: value.length }, (_, i) => value[i]);
|
|
615
|
+
if (items.every((item) => typeof item === "number")) return items;
|
|
616
|
+
const texts = items.map(toText);
|
|
617
|
+
return texts.every((text) => text !== void 0) ? texts : void 0;
|
|
618
|
+
}
|
|
619
|
+
/** An element of a filter value as text, or undefined unless it is text, a number, a boolean or a date. */
|
|
620
|
+
function toText(value) {
|
|
621
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? void 0 : value.toISOString();
|
|
622
|
+
return [
|
|
623
|
+
"string",
|
|
624
|
+
"number",
|
|
625
|
+
"boolean"
|
|
626
|
+
].includes(typeof value) ? String(value) : void 0;
|
|
627
|
+
}
|
|
628
|
+
function readFilters(items, operators) {
|
|
629
|
+
return items.flatMap((item) => {
|
|
630
|
+
if (isGenerated(item.field)) return [];
|
|
631
|
+
const valueless = operators.get(item.field)?.find((o) => o.value === item.operator)?.requiresFilterValue === false;
|
|
632
|
+
const value = valueless ? "" : toFilterValue(item.value);
|
|
633
|
+
if (value === void 0 || !valueless && (value === "" || Array.isArray(value) && !value.length)) return [];
|
|
634
|
+
return [{
|
|
635
|
+
column: item.field,
|
|
636
|
+
operator: item.operator,
|
|
637
|
+
value
|
|
638
|
+
}];
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* The grid's current view, or undefined when part of it cannot be read: a partial state would
|
|
643
|
+
* tell the server the missing part is empty, so it is left out whole.
|
|
644
|
+
*/
|
|
645
|
+
function readState(grid, operators) {
|
|
646
|
+
const filter = grid.filterModel();
|
|
647
|
+
const sortModel = grid.sortModel();
|
|
648
|
+
const rowGrouping = grid.rowGroupingModel();
|
|
649
|
+
const aggregation = grid.aggregationModel();
|
|
650
|
+
const active = grid.pivotActive();
|
|
651
|
+
const model = active ? grid.pivotModel() : void 0;
|
|
652
|
+
if (!filter || !sortModel || !rowGrouping || !aggregation || active === void 0) return void 0;
|
|
653
|
+
if (active && !model) return void 0;
|
|
654
|
+
const state = {};
|
|
655
|
+
const filters = grid.column(() => readFilters(filter.items, operators));
|
|
656
|
+
if (filters.length > 0) state.filters = filters;
|
|
657
|
+
if (filters.length > 1 && filter.or) state.filterOperator = "or";
|
|
658
|
+
const grouping = active ? [] : rowGrouping.filter((field) => !isGenerated(field));
|
|
659
|
+
const sorts = sortModel.flatMap((item) => {
|
|
660
|
+
const column = item.field === "__row_group_by_columns_group__" ? grouping[0] : item.field.replace(/^__row_group_by_columns_group_(.+)__$/, "$1");
|
|
661
|
+
return item.sort && column && !isGenerated(column) ? [{
|
|
662
|
+
column,
|
|
663
|
+
direction: item.sort
|
|
664
|
+
}] : [];
|
|
665
|
+
});
|
|
666
|
+
if (sorts.length > 0) state.sorting = sorts;
|
|
667
|
+
if (model) {
|
|
668
|
+
state.pivoting = readPivot(model);
|
|
669
|
+
return state;
|
|
670
|
+
}
|
|
671
|
+
if (grouping.length > 0) state.grouping = grouping.map((column) => ({ column }));
|
|
672
|
+
const functions = Object.entries(aggregation).flatMap(([field, fn]) => isFunction(fn) && !isGenerated(field) ? [[field, fn]] : []);
|
|
673
|
+
if (functions.length > 0) state.aggregation = Object.fromEntries(functions);
|
|
674
|
+
return state;
|
|
675
|
+
}
|
|
676
|
+
function readPivot(model) {
|
|
677
|
+
return {
|
|
678
|
+
columns: model.columns.filter((c) => !c.hidden && !isGenerated(c.field)).map((c) => ({
|
|
679
|
+
column: c.field,
|
|
680
|
+
direction: c.sort ?? "asc"
|
|
681
|
+
})),
|
|
682
|
+
rows: model.rows.filter((r) => !r.hidden && !isGenerated(r.field)).map((r) => r.field),
|
|
683
|
+
values: model.values.flatMap((v) => !v.hidden && !isGenerated(v.field) && isFunction(v.aggFunc) ? [{ [v.field]: v.aggFunc }] : [])
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
function switchedOff(on) {
|
|
687
|
+
const off = [];
|
|
688
|
+
if (!on.filtering) off.push("filtering");
|
|
689
|
+
if (!on.sorting) off.push("sorting");
|
|
690
|
+
if (!on.grouping) off.push("grouping");
|
|
691
|
+
if (!on.aggregation) off.push("aggregation");
|
|
692
|
+
if (!on.pivoting) off.push("pivoting");
|
|
693
|
+
if (!on.selection) off.push("selection");
|
|
694
|
+
return off;
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* What the grid allows and shows, from its columns, leaving out everything at its default and
|
|
698
|
+
* whatever of the grid's own state cannot be read.
|
|
699
|
+
*/
|
|
700
|
+
function readSnapshot(grid, allColumns, on) {
|
|
701
|
+
const disabled = [];
|
|
702
|
+
if (on) disabled.push(...switchedOff(on));
|
|
703
|
+
if (grid.activeChart() === "") disabled.push("charts");
|
|
704
|
+
const copied = grid.column(() => {
|
|
705
|
+
return firstOf(grid, allColumns, Number.POSITIVE_INFINITY).flatMap((column) => copyColumn(grid, column) ?? []);
|
|
706
|
+
});
|
|
707
|
+
const columns = {};
|
|
708
|
+
for (const { field, limits } of copied) if (Object.keys(limits).length > 0) columns[field] = limits;
|
|
709
|
+
const state = readState(grid, new Map(copied.map((c) => [c.field, c.operators])));
|
|
710
|
+
const snapshot = {};
|
|
711
|
+
if (disabled.length > 0) snapshot.disabled = disabled;
|
|
712
|
+
if (Object.keys(columns).length > 0) snapshot.columns = columns;
|
|
713
|
+
if (state) snapshot.state = state;
|
|
714
|
+
return snapshot;
|
|
715
|
+
}
|
|
716
|
+
// src/index.ts
|
|
717
|
+
const CONNECTION_FAILED = core.CONNECTION_FAILED;
|
|
718
|
+
const INVALID_ANSWER = core.INVALID_ANSWER;
|
|
719
|
+
const NOT_JSON = core.NOT_JSON;
|
|
720
|
+
const UNAUTHENTICATED_USER = core.UNAUTHENTICATED_USER;
|
|
721
|
+
function hold(member, error) {
|
|
722
|
+
let text;
|
|
723
|
+
try {
|
|
724
|
+
text = error instanceof Error ? `${error.name}: ${error.message}\n${error.stack ?? ""}` : String(error);
|
|
725
|
+
} catch {
|
|
726
|
+
text = "An error that could not be read.";
|
|
727
|
+
}
|
|
728
|
+
return {
|
|
729
|
+
member,
|
|
730
|
+
error: typeof error === "object" && error !== null ? new WeakRef(error) : void 0,
|
|
731
|
+
text
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
const thrownOf = (held) => held.error?.deref() ?? held.text;
|
|
735
|
+
/** These options admit an explicit `undefined`; core's, as published, do not: such entries go. */
|
|
736
|
+
function requestOptionsOf(options) {
|
|
737
|
+
const result = {};
|
|
738
|
+
for (const [key, value] of Object.entries(options)) if (value !== void 0) Object.assign(result, { [key]: value });
|
|
739
|
+
return result;
|
|
740
|
+
}
|
|
741
|
+
/** Replaces `unstable_gridDefaultPromptResolver` as the grid's `onPrompt`. */
|
|
742
|
+
function createPromptResolver(options) {
|
|
743
|
+
const { url, apiRef } = options;
|
|
744
|
+
const requestOptions = requestOptionsOf(options);
|
|
745
|
+
const promptOptions = promptOptionsOf(requestOptions);
|
|
746
|
+
let holder;
|
|
747
|
+
const owner = /* @__PURE__ */ new Map();
|
|
748
|
+
async function send(query, context, conversationId, api) {
|
|
749
|
+
const failures = [];
|
|
750
|
+
const flush = () => {
|
|
751
|
+
const mine = failures.filter((f) => owner.get(f.member) === failures);
|
|
752
|
+
if (mine.length === 0) return;
|
|
753
|
+
if (holder === failures) {
|
|
754
|
+
console.warn(gridWarning(mine.map((f) => f.member)), ...mine.map(thrownOf));
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
const printed = /* @__PURE__ */ new Set();
|
|
758
|
+
for (const held of mine) {
|
|
759
|
+
const { member } = held;
|
|
760
|
+
if (printed.has(member)) continue;
|
|
761
|
+
printed.add(member);
|
|
762
|
+
console.warn(`@gridsay/mui-x-data-grid: ${member} could not be read or changed; skipped.`, thrownOf(held));
|
|
763
|
+
}
|
|
764
|
+
};
|
|
765
|
+
/** Logs, then lets go of what was thrown: an error can hold on to a grid that is gone. */
|
|
766
|
+
const report = () => {
|
|
767
|
+
flush();
|
|
768
|
+
failures.length = 0;
|
|
769
|
+
};
|
|
770
|
+
const grid = api ? new Grid(api, (caught) => {
|
|
771
|
+
const failure = hold(caught.member, caught.error);
|
|
772
|
+
failures.push(failure);
|
|
773
|
+
if (!owner.has(failure.member)) owner.set(failure.member, failures);
|
|
774
|
+
holder ??= failures;
|
|
775
|
+
}) : null;
|
|
776
|
+
try {
|
|
777
|
+
const sent = await ask(grid, query, context, conversationId);
|
|
778
|
+
return {
|
|
779
|
+
...sent,
|
|
780
|
+
applied: sent.applied.finally(report)
|
|
781
|
+
};
|
|
782
|
+
} catch (error) {
|
|
783
|
+
report();
|
|
784
|
+
if (error instanceof GridsayError$1) throw error;
|
|
785
|
+
throw new GridsayError$1(INVALID_ANSWER, {
|
|
786
|
+
code: UNEXPECTED_ERROR_CODE$1,
|
|
787
|
+
cause: error
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
async function ask(grid, query, context, conversationId) {
|
|
792
|
+
const headers = await requestHeaders(requestOptions);
|
|
793
|
+
const body = {
|
|
794
|
+
context: boundedContext(context),
|
|
795
|
+
query,
|
|
796
|
+
options: promptOptions
|
|
797
|
+
};
|
|
798
|
+
if (conversationId !== void 0) body.conversationId = conversationId;
|
|
799
|
+
if (grid?.connected()) try {
|
|
800
|
+
const described = readSnapshot(grid, grid.columns(), grid.switches());
|
|
801
|
+
if (!grid.detached && grid.connected()) body.grid = described;
|
|
802
|
+
} catch (error) {
|
|
803
|
+
grid.undescribed(error);
|
|
804
|
+
}
|
|
805
|
+
const init = {
|
|
806
|
+
method: "POST",
|
|
807
|
+
headers,
|
|
808
|
+
body: JSON.stringify(body)
|
|
809
|
+
};
|
|
810
|
+
let response;
|
|
811
|
+
try {
|
|
812
|
+
response = await fetch(url, init);
|
|
813
|
+
} catch (cause) {
|
|
814
|
+
throw new GridsayError$1(CONNECTION_FAILED, {
|
|
815
|
+
code: CONNECTION_FAILED_CODE$1,
|
|
816
|
+
cause
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
return finish(grid, await readResponse(response));
|
|
820
|
+
}
|
|
821
|
+
let unreadable = false;
|
|
822
|
+
const gridOf = () => {
|
|
823
|
+
try {
|
|
824
|
+
return apiRef?.current ?? null;
|
|
825
|
+
} catch (error) {
|
|
826
|
+
if (!unreadable) console.warn(gridWarning(["apiRef.current"]), error);
|
|
827
|
+
unreadable = true;
|
|
828
|
+
return null;
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
return oneAtATime(send, gridOf);
|
|
832
|
+
}
|
|
833
|
+
export { CONNECTION_FAILED, CONNECTION_FAILED_CODE, GridsayError, INVALID_ANSWER, INVALID_ANSWER_CODE, NOT_JSON, NOT_JSON_CODE, UNAUTHENTICATED_USER, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE, createPromptResolver };
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gridsay/mui-x-data-grid",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Gridsay prompt resolver for the MUI X Data Grid Premium AI Assistant.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"gridsay",
|
|
7
|
+
"ai",
|
|
8
|
+
"mui",
|
|
9
|
+
"mui-x",
|
|
10
|
+
"data-grid",
|
|
11
|
+
"ai-assistant"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://gridsay.com/docs/browser-keys",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/gridsay/gridsay/issues"
|
|
16
|
+
},
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/gridsay/gridsay.git",
|
|
20
|
+
"directory": "packages/mui-x-data-grid"
|
|
21
|
+
},
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"type": "module",
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"default": "./dist/index.js"
|
|
29
|
+
},
|
|
30
|
+
"./package.json": "./package.json"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist"
|
|
34
|
+
],
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@gridsay/core": "0.1.1"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@mui/x-data-grid-premium": "^9.18.0"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public",
|
|
43
|
+
"provenance": true
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@emotion/react": "11.14.0",
|
|
47
|
+
"@emotion/styled": "11.14.1",
|
|
48
|
+
"@mui/material": "9.6.0",
|
|
49
|
+
"@mui/x-data-grid-premium": "9.18.0",
|
|
50
|
+
"@types/react": "19.3.3",
|
|
51
|
+
"@types/react-dom": "19.3.0",
|
|
52
|
+
"react": "19.3.1",
|
|
53
|
+
"react-dom": "19.3.1",
|
|
54
|
+
"zod": "4.6.7"
|
|
55
|
+
},
|
|
56
|
+
"scripts": {
|
|
57
|
+
"build": "tsdown",
|
|
58
|
+
"typecheck": "tsc && tsc -p tsconfig.exact.json",
|
|
59
|
+
"test": "vitest run",
|
|
60
|
+
"check:package": "publint --strict && attw --pack . --profile esm-only",
|
|
61
|
+
"compare": "vitest run --config compat/vitest.compare.config.ts"
|
|
62
|
+
}
|
|
6
63
|
}
|