@gridsay/mui-x-data-grid 1.0.0 → 1.1.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/README.md CHANGED
@@ -28,7 +28,9 @@ With every question, the resolver posts to your `url`:
28
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
29
  only, the value and label of each of the first 500 options, the same whether data sampling is
30
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;
31
+ aggregation and pivot. With showing and hiding columns switched on (see
32
+ [below](#showing-and-hiding-columns)), also, of the columns a question can show or hide, those
33
+ set to `hideable: false` and those hidden now;
32
34
  - `additionalContext`, `privateMode` and `referenceId`, when you set them;
33
35
  - in the headers: always `content-type: application/json` (your own `headers` can replace it),
34
36
  then your own `headers`, `x-api-key` when you set `publishableKey`, and
@@ -76,6 +78,7 @@ from the browser, pass that URL with a `publishableKey` and `getToken`; see
76
78
  | `publishableKey` | A publishable key, sent as `x-api-key`. For calling the gateway from the browser. |
77
79
  | `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
80
  | `additionalContext`, `privateMode`, `referenceId` | Sent in the request's `options`, as the stock resolver sends them. |
81
+ | `features` | Abilities that are off unless you switch them on. `{ columnVisibility: true }` lets questions show and hide columns; see [Showing and hiding columns](#showing-and-hiding-columns). |
79
82
 
80
83
  ## Errors
81
84
 
@@ -95,6 +98,7 @@ The helper's own failures, each code exported as `<NAME>_CODE` beside its senten
95
98
  | `connection_failed` | `CONNECTION_FAILED`: "The connection was interrupted. Try again." | The request got no answer, or the answer was cut off. |
96
99
  | `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
100
  | `invalid_answer` | `INVALID_ANSWER` | The response was not an answer the helper can read, or an error without a sentence of its own. |
101
+ | `cannot_apply` | `INVALID_ANSWER` | An answer that shows or hides columns could not be applied: a column it changes was removed or locked while the question was out, the grid was in pivot mode by the time it came, or the grid did not take the change (what it threw is in `cause`). The grid gets nothing else of that answer. After a throw the helper tries once to put the columns back; if that fails too, the columns can stay as the answer set them, in part or in whole. |
98
102
 
99
103
  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
104
 
@@ -115,6 +119,8 @@ An error from the gateway keeps the gateway's own code, `status`, `retryAfter` a
115
119
  grid generates (single or multiple grouping-column mode); other sorts are kept.
116
120
  - **Leaving pivot mode** no longer brings back the grouping and aggregation from before the pivot.
117
121
  - **A chart follow-up** keeps the aggregation it asked for.
122
+ - **Questions can show and hide columns,** once you switch it on. See
123
+ [Showing and hiding columns](#showing-and-hiding-columns).
118
124
  - **One prompt at a time.** A prompt sent while another is running on the same grid waits for it,
119
125
  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
126
  so the two can interleave. A failed prompt does not block the next one. The request itself has no
@@ -127,6 +133,50 @@ An error from the gateway keeps the gateway's own code, `status`, `retryAfter` a
127
133
  difference is that with this helper the first prompt ends as successful instead of staying at
128
134
  "Processing…".
129
135
 
136
+ ## Showing and hiding columns
137
+
138
+ Off unless you switch it on:
139
+
140
+ ```ts
141
+ createPromptResolver({ url: '/api/ai-assistant', apiRef, features: { columnVisibility: true } });
142
+ ```
143
+
144
+ A question can then show and hide columns: "hide the email column", "show the region column
145
+ again", "only show name and amount", "show all columns". The helper offers it on a question when
146
+ all of these hold; otherwise, and whenever it is switched off, it sends what 1.0.0 sends, and a
147
+ question cannot show or hide columns:
148
+
149
+ - you pass `apiRef`, the grid is in the document, and its settings and current view could be read;
150
+ - the grid is not in pivot mode;
151
+ - the column panel is on (`disableColumnSelector` is not set);
152
+ - the grid has its column visibility model, as a plain object of booleans, and
153
+ `setColumnVisibilityModel`, as 9.18.0 does;
154
+ - at most 500 of the grid's columns are hidden, its own (such as the checkbox column) included;
155
+ - at least one column a question can change can be hidden.
156
+
157
+ **Which columns a question can change.** The columns in the context the grid builds for the
158
+ question that are still in the grid when the question is asked, other than columns listed only as
159
+ derived from another for pivoting, the grid's own columns (checkbox, grouping, row reordering,
160
+ detail panel, tree data, formula row number), `actions` columns, and columns whose field is over
161
+ 255 characters, contains the pivot separator `>->`, or is `__proto__`. Set `hideable: false` on a column, as you do to take it out of the column menu
162
+ and panel, and the helper never shows or hides it: "show all columns" leaves it hidden if it is.
163
+ Every other column can be shown, including columns your app starts hidden, such as through
164
+ `initialState`, and every column can be hidden. The lock holds for the helper's own changes: with
165
+ MUI's `useKeepGroupedColumnsHidden`, the grid itself shows a grouped column when an answer removes
166
+ its grouping, locked or not.
167
+
168
+ **How the change is made.** The helper changes the column visibility model itself, with one
169
+ `setColumnVisibilityModel` call, before it hands the rest of the answer to the grid. It changes only
170
+ what the answer changed compared with what the question sent, so a column you show or hide by hand
171
+ while the question is out stays as you left it. Just before it writes, it reads your columns again
172
+ and checks each column it would change: if one has been removed or locked while the question was
173
+ out, it changes nothing and the question fails with `cannot_apply`. An answer that names a column
174
+ the question did not offer, or that shows or hides columns and pivots too, is refused with
175
+ `invalid_answer`. If the grid is in pivot mode by the time the answer comes, the question fails with
176
+ `cannot_apply`. If the grid throws on the change, the helper tries once to put the columns back and
177
+ the question fails with `cannot_apply`, so the grid gets nothing else of the answer; if putting them
178
+ back fails too, the columns can stay as the answer set them, in part or in whole.
179
+
130
180
  ## When something goes wrong after the answer arrives
131
181
 
132
182
  - **The grid refuses part of an answer.** The grid applies an answer itself, after the resolver
@@ -152,11 +202,12 @@ An error from the gateway keeps the gateway's own code, `status`, `retryAfter` a
152
202
  - **Part of the grid fails: an untested grid version, or a callback of yours.** Every call into the
153
203
  grid goes through one guarded path: reading its private API, its root props
154
204
  (`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
205
+ `disablePivoting`, `rowSelection`, `rowGroupingColumnMode`, `dataSource`,
206
+ `disableColumnSelector`) and its state (filters, sorting, row grouping, aggregation, pivot mode
207
+ and model, the active chart, whether rows are loading, the column visibility model), your column
208
+ definitions and functions (`valueOptions`, `getOptionValue`, `getOptionLabel`, and what they
209
+ return), and each of the helper's own steps on it (subscribing to its events, leaving pivot mode,
210
+ keeping a chart's aggregation, selecting the top rows, showing and hiding columns). The one
160
211
  thing the helper does on a grid that has left the document is remove its own listeners. A part
161
212
  that is missing, in another shape, or throws is a failure. An error thrown by the grid or by your
162
213
  own callbacks (such as `onPivotActiveChange`) during these steps is reported in the console and
@@ -167,7 +218,8 @@ An error from the gateway keeps the gateway's own code, `status`, `retryAfter` a
167
218
  filters leave) and keeping a chart's aggregation; it never selects rows of a page whose loading it
168
219
  could not see end. Every wait on the grid has a bound and always ends. The grid's current view is
169
220
  sent whole or not at all, so the server keeps the conversation's last answer rather than being
170
- told a part is empty.
221
+ told a part is empty. Showing and hiding columns is not skipped once offered: when the change an
222
+ answer makes cannot be read or made, that question fails with `cannot_apply`.
171
223
  - **The console warning.** Each part of the grid that fails is reported once per resolver, when
172
224
  the question that met it has settled, however it ended. The first question to meet a failure
173
225
  prints the full warning, naming every part it could not read or change, followed by each error
@@ -175,11 +227,15 @@ An error from the gateway keeps the gateway's own code, `status`, `retryAfter` a
175
227
  short line (the package, the part, "skipped", and the error). A part already reported is never
176
228
  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
229
  - **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
230
+ request (with showing and hiding columns on, once more before it shows or hides any), as MUI
231
+ reads them: `valueOptions` called with `{ field }`, then `getOptionValue` and
179
232
  `getOptionLabel` once per option, each as a method of its column. If reading them throws, or the
180
233
  grid has left the page by the end of that read, the question is sent without a description and
181
234
  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,
235
+ grid refuses a question. With showing and hiding columns on, this holds for what is read before
236
+ the request: a `hideable` (or `type`) that throws then is reported, the description is kept, and
237
+ the question cannot show or hide columns; a column that cannot be read again when the answer
238
+ arrives makes that answer fail with `cannot_apply`. Column definitions whose getters or functions throw only sometimes,
183
239
  return different values on each call, or change the grid while being read are outside what the
184
240
  helper supports. A change that makes nothing fail, such as a prop that keeps its name but changes
185
241
  its meaning, is not noticed.
@@ -207,6 +263,12 @@ An error from the gateway keeps the gateway's own code, `status`, `retryAfter` a
207
263
  conversation, has `select: -1` in place of the number asked for.
208
264
  - A chart's aggregation that you change by hand within half a second of an answer that set it is
209
265
  put back to the answer's.
266
+ - **Showing and hiding columns.** The change stays if the grid then refuses another part of the
267
+ same answer: the helper makes it before the grid applies the rest, and nothing undoes it. With a
268
+ controlled `columnVisibilityModel`, update it from `onColumnVisibilityModelChange`, or the grid
269
+ keeps your columns while the panel reports the answer applied. The assistant panel has no entry
270
+ for showing or hiding columns: in 9.18.0 it lists the other parts of the answer whenever they are
271
+ not empty, such as a sort the grid already had.
210
272
  - The description can be incomplete in three cases: an active filter whose operator needs no value
211
273
  and is past the column's 64th operator is left out; an option whose label is over 255 characters
212
274
  is left out and still counts toward the 500; an aggregation function name over 64 characters is
@@ -232,7 +294,7 @@ Everything the package exports, and nothing else, is covered by the versioning r
232
294
  | `PromptResolverOptions` (type) | The options in the table above. |
233
295
  | `GridsayError` | The class every rejection is an instance of (see Errors). |
234
296
  | `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. |
297
+ | `CANNOT_APPLY_CODE`, `CONNECTION_FAILED_CODE`, `INVALID_ANSWER_CODE`, `NOT_JSON_CODE`, `UNAUTHENTICATED_USER_CODE`, `UNEXPECTED_ERROR_CODE` | The codes. |
236
298
 
237
299
  Entry points: `@gridsay/mui-x-data-grid` (ESM, with its type declarations) and
238
300
  `@gridsay/mui-x-data-grid/package.json` (the package's manifest, for tools that read it).
@@ -240,7 +302,8 @@ Entry points: `@gridsay/mui-x-data-grid` (ESM, with its type declarations) and
240
302
  ## Versioning
241
303
 
242
304
  `@gridsay/mui-x-data-grid` follows semver from its first major release. It pins `@gridsay/core`
243
- exactly.
305
+ exactly. An app that imports `GridsayError` from `@gridsay/core` keeps that package at the version
306
+ this one pins (0.2.0 for 1.1.0), or imports it from `@gridsay/mui-x-data-grid`.
244
307
 
245
308
  - **Codes are the contract; sentences are not.** Match on `error.code`. The sentences
246
309
  (`error.message`, and the exported `INVALID_ANSWER`, `CONNECTION_FAILED` and the others) are for
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { CONNECTION_FAILED_CODE, GridsayError, INVALID_ANSWER_CODE, NOT_JSON_CODE, PromptData, RequestHeaders, RequestOptions, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE } from "@gridsay/core";
1
+ import { CANNOT_APPLY_CODE, CONNECTION_FAILED_CODE, GridsayError, INVALID_ANSWER_CODE, NOT_JSON_CODE, PromptData, RequestHeaders, RequestOptions, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE } from "@gridsay/core";
2
2
  type RowId = string | number;
3
3
  type ValueOption = string | number | object;
4
4
  /** MUI's `GridFilterItem['operator']`: its operators, or any other string. */
@@ -12,6 +12,7 @@ type Column = {
12
12
  groupable?: boolean;
13
13
  pivotable?: boolean;
14
14
  aggregable?: boolean;
15
+ hideable?: boolean | undefined;
15
16
  availableAggregationFunctions?: string[];
16
17
  filterOperators?: readonly {
17
18
  value: string;
@@ -36,6 +37,7 @@ type GridApi = {
36
37
  }, reason?: 'singleRowSelection' | 'multipleRowsSelection') => void;
37
38
  setAggregationModel: (model: Record<string, string>) => void;
38
39
  setPivotActive: (active: boolean | ((prev: boolean) => boolean)) => void;
40
+ setColumnVisibilityModel?: ((model: Record<string, boolean>) => void) | undefined;
39
41
  subscribeEvent: (event: 'rowsSet' | 'aggregationModelChange', handler: () => void) => () => void;
40
42
  rootElementRef: {
41
43
  readonly current: {
@@ -92,6 +94,8 @@ type GridApi = {
92
94
  rows: {
93
95
  loading?: boolean;
94
96
  };
97
+ /** Read for its `columnVisibilityModel`: any value fits, as any did in 1.0.0. */
98
+ columns?: unknown;
95
99
  };
96
100
  };
97
101
  /**
@@ -120,7 +124,14 @@ export type PromptResolverOptions = {
120
124
  privateMode?: boolean | undefined;
121
125
  /** Your id for the end user. */
122
126
  referenceId?: string | undefined;
127
+ /**
128
+ * Abilities that are off unless switched on. `columnVisibility: true` lets questions show and
129
+ * hide columns, on a grid that can take it (see the README).
130
+ */
131
+ features?: {
132
+ columnVisibility?: boolean | undefined;
133
+ } | undefined;
123
134
  };
124
135
  /** Replaces `unstable_gridDefaultPromptResolver` as the grid's `onPrompt`. */
125
136
  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 };
137
+ export { CANNOT_APPLY_CODE, CONNECTION_FAILED_CODE, GridsayError, INVALID_ANSWER_CODE, NOT_JSON_CODE, type PromptResolver, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
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";
2
+ import { CANNOT_APPLY_CODE, CANNOT_APPLY_CODE as CANNOT_APPLY_CODE$1, CONNECTION_FAILED_CODE, CONNECTION_FAILED_CODE as CONNECTION_FAILED_CODE$1, GridsayError, GridsayError as GridsayError$1, INVALID_ANSWER as INVALID_ANSWER$1, INVALID_ANSWER_CODE, INVALID_ANSWER_CODE as INVALID_ANSWER_CODE$1, NOT_JSON_CODE, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE, UNEXPECTED_ERROR_CODE as UNEXPECTED_ERROR_CODE$1 } from "@gridsay/core";
3
3
  import { isRecord, promptOptionsOf, readResponse, requestHeaders } from "@gridsay/core/internal";
4
4
  // src/boundary.ts
5
5
  /** Root props the grid always fills in, with its defaults, in the tested release. */
@@ -25,6 +25,17 @@ const optional = (value, check, what) => value === void 0 || check(value) ? valu
25
25
  const isDirection = (value) => value === "asc" || value === "desc";
26
26
  const isBoolean = (value) => typeof value === "boolean";
27
27
  /**
28
+ * An object made as `{}` makes it, in this realm or another: not a Map, a Date, an array or any
29
+ * other class. Every own key is one `Object.entries` gives, so a copy leaves nothing out.
30
+ */
31
+ const plain = (value, what) => {
32
+ const object = record(value, what);
33
+ const prototype = Object.getPrototypeOf(object);
34
+ const made = prototype === null || Object.getPrototypeOf(prototype) === null;
35
+ const whole = Reflect.ownKeys(object).length === Object.keys(object).length;
36
+ return made && whole ? object : fail(what);
37
+ };
38
+ /**
28
39
  * The one boundary between the helper and the grid, for one question on one grid. Every call
29
40
  * goes through `use`, which never throws: a call that throws, or a part that is missing or in
30
41
  * another shape, is handed to `failed` with what was thrown, and gives nothing. Nothing is called
@@ -133,6 +144,25 @@ var Grid = class {
133
144
  gate.depth -= 1;
134
145
  }
135
146
  }
147
+ /**
148
+ * Reads from the app's column definitions that only showing and hiding columns needs: what is
149
+ * thrown there is reported, and gives nothing, so the rest of the description stays.
150
+ */
151
+ optional(read) {
152
+ if (!this.live()) return void 0;
153
+ gate.depth += 1;
154
+ try {
155
+ return { value: read() };
156
+ } catch (error) {
157
+ if (!(error instanceof Undescribed) && this.live()) this.failed({
158
+ member: "column functions",
159
+ error
160
+ });
161
+ return;
162
+ } finally {
163
+ gate.depth -= 1;
164
+ }
165
+ }
136
166
  /** Anything else thrown while describing the grid: reported, and the grid is not described. */
137
167
  undescribed(error) {
138
168
  if (!(error instanceof Undescribed)) this.failed({
@@ -145,11 +175,7 @@ var Grid = class {
145
175
  * the grid keeps on `apiRef.current`. When any cannot be read, nothing is guessed.
146
176
  */
147
177
  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;
178
+ const props = this.rootProps();
153
179
  if (!props) return void 0;
154
180
  const values = {};
155
181
  let complete = true;
@@ -174,6 +200,23 @@ var Grid = class {
174
200
  dataSource: dataSource.value
175
201
  };
176
202
  }
203
+ rootProps() {
204
+ return this.use("privateApi", (api) => {
205
+ const symbol = Object.getOwnPropertySymbols(api).find((s) => s.description === "mui.api_private");
206
+ const privateApi = symbol ? Reflect.get(api, symbol) : void 0;
207
+ return record(record(privateApi, "the private API").rootProps, "the private API");
208
+ })?.value;
209
+ }
210
+ /** The column panel is on. False also when that cannot be read. */
211
+ columnSelector() {
212
+ const props = this.rootProps();
213
+ if (!props) return false;
214
+ return this.use("rootProps.disableColumnSelector", () => {
215
+ const key = "disableColumnSelector";
216
+ const value = key in props ? props[key] : fail(key);
217
+ return value === void 0 || isBoolean(value) ? value !== true : fail(key);
218
+ })?.value === true;
219
+ }
177
220
  filterModel() {
178
221
  return this.use("state.filter.filterModel", (api) => {
179
222
  const model = record(api.state.filter.filterModel, "filterModel");
@@ -237,6 +280,29 @@ var Grid = class {
237
280
  };
238
281
  })?.value;
239
282
  }
283
+ /** A copy of the column visibility model: field to boolean, where only `false` hides. */
284
+ visibilityModel() {
285
+ return this.use("state.columns.columnVisibilityModel", (api) => {
286
+ const columns = record(api.state.columns, "state.columns");
287
+ const model = plain(columns.columnVisibilityModel, "columnVisibilityModel");
288
+ return Object.fromEntries(Object.entries(model).map(([field, visible]) => [field, isBoolean(visible) ? visible : fail("a column visibility")]));
289
+ })?.value;
290
+ }
291
+ canSetVisibility() {
292
+ return this.use("setColumnVisibilityModel", (api) => typeof api.setColumnVisibilityModel === "function" ? true : fail("setColumnVisibilityModel")) !== void 0;
293
+ }
294
+ /** Replaces the column visibility model; when the grid does not take it, what was thrown. */
295
+ setVisibility(model) {
296
+ let thrown;
297
+ return this.use("setColumnVisibilityModel", (api) => {
298
+ try {
299
+ return api.setColumnVisibilityModel ? api.setColumnVisibilityModel(model) : fail("setColumnVisibilityModel");
300
+ } catch (error) {
301
+ thrown = error;
302
+ throw error;
303
+ }
304
+ }) ? void 0 : { thrown };
305
+ }
240
306
  /** The active chart's id, `''` for none. */
241
307
  activeChart() {
242
308
  return this.use("state.chartsIntegration.activeChartId", (api) => string(api.state.chartsIntegration.activeChartId, "activeChartId"))?.value;
@@ -391,16 +457,57 @@ const keepAggregation = (grid, aggregation) => grid.wait("aggregationModelChange
391
457
  return false;
392
458
  });
393
459
  /**
460
+ * Applies what the answer changed against what the question sent, to a copy of the model as it is
461
+ * now, so a column shown or hidden by hand meanwhile stays so. Only columns that could change
462
+ * when the question was asked, and still can, change. One write; when the grid does not take it,
463
+ * one try to put the model back. Gives the error to reject with, if any.
464
+ */
465
+ function showAndHide(grid, sent, hidden) {
466
+ const refused = (cause) => new GridsayError$1(INVALID_ANSWER$1, {
467
+ code: CANNOT_APPLY_CODE$1,
468
+ cause
469
+ });
470
+ if (grid.pivotActive() !== false) return refused();
471
+ const model = grid.visibilityModel();
472
+ if (!model) return refused();
473
+ const next = { ...model };
474
+ const changing = [];
475
+ for (const field of sent.hideable) {
476
+ const hide = hidden.has(field);
477
+ if (hide === sent.hidden.has(field) || hide === (next[field] === false)) continue;
478
+ if (hide) next[field] = false;
479
+ else delete next[field];
480
+ changing.push(field);
481
+ }
482
+ if (changing.length === 0) return void 0;
483
+ const now = sent.changeable();
484
+ if (!now || changing.some((field) => !now.has(field))) return refused();
485
+ const failed = grid.setVisibility(next);
486
+ if (!failed) return void 0;
487
+ grid.setVisibility(model);
488
+ return refused(failed.thrown);
489
+ }
490
+ /**
394
491
  * Prepares a checked answer for the grid. `response` goes back to the grid, which applies it
395
492
  * synchronously; `applied` settles once the helper has finished its own changes after that.
396
493
  * Each step runs only on what the steps before it confirmed; the rest is left to the grid.
494
+ * `visibility`: what the question sent, when it let the answer show and hide columns.
397
495
  */
398
- async function adapt(grid, data) {
496
+ async function adapt(grid, answer, visibility) {
497
+ const { hiddenColumns, ...data } = answer;
498
+ const sent = hiddenColumns && visibility;
499
+ const hidden = new Set(hiddenColumns);
500
+ if (sent && ("columns" in data.pivoting || [...hidden].some((field) => !sent.described.has(field)))) throw new GridsayError$1(INVALID_ANSWER$1, { code: INVALID_ANSWER_CODE$1 });
399
501
  const asItIs = {
400
502
  response: data,
401
503
  applied: Promise.resolve()
402
504
  };
403
505
  if (!grid.connected()) return asItIs;
506
+ if (sent) {
507
+ const refused = showAndHide(grid, sent, hidden);
508
+ if (!grid.connected()) return asItIs;
509
+ if (refused) throw refused;
510
+ }
404
511
  const on = grid.switches();
405
512
  const pivots = (on ? on.pivoting : true) && "columns" in data.pivoting;
406
513
  let layoutKnown = true;
@@ -432,9 +539,11 @@ async function adapt(grid, data) {
432
539
  }
433
540
  // src/queue.ts
434
541
  /** 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,
542
+ async function finish(grid, answer, visibility) {
543
+ if (grid) return adapt(grid, answer, visibility);
544
+ const { hiddenColumns, ...response } = answer;
545
+ return {
546
+ response,
438
547
  applied: Promise.resolve()
439
548
  };
440
549
  }
@@ -491,7 +600,23 @@ const isFunction = (fn) => FUNCTIONS.includes(fn);
491
600
  const PIVOT_SEPARATOR = ">->";
492
601
  /** A column the grid generated, or one named after cell values: never written into the description. */
493
602
  const isGenerated = (field) => field.startsWith("__") && field.endsWith("__") || field.includes(PIVOT_SEPARATOR);
603
+ /** The grid's own columns, by their fields in the tested release; grouping columns by prefix. */
604
+ const OWN_COLUMNS = /* @__PURE__ */ new Set([
605
+ "__check__",
606
+ "__detail_panel_toggle__",
607
+ "__reorder__",
608
+ "__tree_data_group__",
609
+ "__formula_row_number__"
610
+ ]);
611
+ const GROUPING_PREFIX = "__row_group_by_columns_group";
612
+ /**
613
+ * A column no question shows or hides: the grid's own, its pivot value columns, one too long to
614
+ * send, and `__proto__`, which no model can hold as a column.
615
+ */
616
+ const isControl = (field) => OWN_COLUMNS.has(field) || field.startsWith(GROUPING_PREFIX) || field.includes(PIVOT_SEPARATOR) || field.length > 255 || field === "__proto__";
494
617
  const OPTIONS = 500;
618
+ /** The gateway's cap on the hidden columns a grid sends. */
619
+ const HIDDEN = 500;
495
620
  const AGGREGATION_FUNCTIONS = 32;
496
621
  const OPERATORS = 64;
497
622
  /**
@@ -540,9 +665,8 @@ function readOptions(grid, column, field) {
540
665
  return options;
541
666
  }
542
667
  /** 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;
668
+ function copyColumn(grid, column, field) {
669
+ if (isGenerated(field) || field.length > 255) return void 0;
546
670
  const type = at(grid, column, "type");
547
671
  const limits = {};
548
672
  for (const flag of [
@@ -560,6 +684,7 @@ function copyColumn(grid, column) {
560
684
  }
561
685
  return {
562
686
  field,
687
+ type,
563
688
  limits,
564
689
  operators: firstOf(grid, at(grid, column, "filterOperators"), OPERATORS).map((operator) => isRecord(operator) ? {
565
690
  value: at(grid, operator, "value"),
@@ -571,6 +696,44 @@ function copyColumn(grid, column) {
571
696
  };
572
697
  }
573
698
  /**
699
+ * Reads what showing and hiding columns needs of a column, besides what `copyColumn` read: a read
700
+ * that throws leaves `hideable` unknown, and the rest of the description as it is.
701
+ */
702
+ function liveColumn(grid, column, field, copied) {
703
+ if (isControl(field)) return {
704
+ field,
705
+ control: true,
706
+ hideable: false
707
+ };
708
+ const read = (key) => grid.optional(() => at(grid, column, key));
709
+ const type = copied ? { value: copied.type } : read("type");
710
+ const hideable = read("hideable");
711
+ return {
712
+ field,
713
+ control: type?.value === "actions",
714
+ hideable: type && hideable ? hideable.value !== false : void 0
715
+ };
716
+ }
717
+ /** The columns a question may show or hide now, read again; undefined when they cannot be. */
718
+ function changeableNow(grid) {
719
+ const live = grid.optional(() => firstOf(grid, grid.columns(), Number.POSITIVE_INFINITY).flatMap((column) => {
720
+ const field = at(grid, column, "field");
721
+ return typeof field === "string" ? [liveColumn(grid, column, field)] : [];
722
+ }))?.value;
723
+ return live && new Set(live.filter((c) => !c.control && c.hideable).map((c) => c.field));
724
+ }
725
+ /** The fields the posted context lists as data columns, not only as derived from another column. */
726
+ function dataColumnsOf(context) {
727
+ let entries;
728
+ try {
729
+ entries = JSON.parse(context);
730
+ } catch {
731
+ return /* @__PURE__ */ new Set();
732
+ }
733
+ if (!Array.isArray(entries)) return /* @__PURE__ */ new Set();
734
+ return new Set(entries.flatMap((entry) => isRecord(entry) && typeof entry.field === "string" && entry.derivedFrom === void 0 ? [entry.field] : []));
735
+ }
736
+ /**
574
737
  * MUI's column context with each option list cut to its first 500 options, each to its value and
575
738
  * label: what else an app or `getPivotDerivedColumns` attaches to an option stays in the browser.
576
739
  * A context with no option list goes exactly as the grid built it.
@@ -694,24 +857,71 @@ function switchedOff(on) {
694
857
  return off;
695
858
  }
696
859
  /**
860
+ * What showing and hiding columns needs, when the grid can take it: the columns a question may
861
+ * name are those the posted context lists as data columns and the grid has, other than its own
862
+ * columns and actions columns; at least one of them must be one a question may change.
863
+ */
864
+ function readVisibility(grid, live, context) {
865
+ if (!grid.columnSelector()) return void 0;
866
+ const model = grid.visibilityModel();
867
+ if (!model || !grid.canSetVisibility()) return void 0;
868
+ if (live.filter((c) => model[c.field] === false).length > HIDDEN) return void 0;
869
+ const listed = dataColumnsOf(context);
870
+ const columns = live.filter((c) => !c.control && listed.has(c.field));
871
+ if (columns.some((c) => c.hideable === void 0)) return void 0;
872
+ const hideable = new Set(columns.filter((c) => c.hideable).map((c) => c.field));
873
+ if (hideable.size === 0) return void 0;
874
+ return {
875
+ described: new Set(columns.map((c) => c.field)),
876
+ hideable,
877
+ hidden: new Set(columns.filter((c) => model[c.field] === false).map((c) => c.field)),
878
+ changeable: () => changeableNow(grid)
879
+ };
880
+ }
881
+ /**
697
882
  * 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.
883
+ * whatever of the grid's own state cannot be read. `context`, the context the request posts, is
884
+ * given only when the app switched on showing and hiding columns; `visibility` is then set when the
885
+ * grid can take it.
699
886
  */
700
- function readSnapshot(grid, allColumns, on) {
887
+ function readSnapshot(grid, allColumns, on, context) {
701
888
  const disabled = [];
702
889
  if (on) disabled.push(...switchedOff(on));
703
890
  if (grid.activeChart() === "") disabled.push("charts");
891
+ const live = [];
704
892
  const copied = grid.column(() => {
705
- return firstOf(grid, allColumns, Number.POSITIVE_INFINITY).flatMap((column) => copyColumn(grid, column) ?? []);
893
+ return firstOf(grid, allColumns, Number.POSITIVE_INFINITY).flatMap((column) => {
894
+ const field = at(grid, column, "field");
895
+ if (typeof field !== "string") return [];
896
+ const copy = copyColumn(grid, column, field);
897
+ if (context !== void 0) live.push(liveColumn(grid, column, field, copy));
898
+ return copy ?? [];
899
+ });
706
900
  });
707
- const columns = {};
708
- for (const { field, limits } of copied) if (Object.keys(limits).length > 0) columns[field] = limits;
709
901
  const state = readState(grid, new Map(copied.map((c) => [c.field, c.operators])));
902
+ const visibility = context !== void 0 && on && state && !state.pivoting ? readVisibility(grid, live, context) : void 0;
903
+ const locked = new Set([...visibility?.described ?? []].filter((field) => !visibility?.hideable.has(field)));
904
+ const columns = {};
905
+ for (const { field, limits } of copied) {
906
+ const entry = locked.has(field) ? {
907
+ ...limits,
908
+ hideable: false
909
+ } : limits;
910
+ if (Object.keys(entry).length > 0) columns[field] = entry;
911
+ }
912
+ for (const field of locked) if (!Object.hasOwn(columns, field)) columns[field] = { hideable: false };
710
913
  const snapshot = {};
914
+ if (visibility) snapshot.accepts = ["hiddenColumns"];
711
915
  if (disabled.length > 0) snapshot.disabled = disabled;
712
916
  if (Object.keys(columns).length > 0) snapshot.columns = columns;
713
- if (state) snapshot.state = state;
714
- return snapshot;
917
+ if (state) {
918
+ if (visibility?.hidden.size) state.hiddenColumns = [...visibility.hidden];
919
+ snapshot.state = state;
920
+ }
921
+ return {
922
+ snapshot,
923
+ visibility
924
+ };
715
925
  }
716
926
  // src/index.ts
717
927
  const CONNECTION_FAILED = core.CONNECTION_FAILED;
@@ -732,6 +942,14 @@ function hold(member, error) {
732
942
  };
733
943
  }
734
944
  const thrownOf = (held) => held.error?.deref() ?? held.text;
945
+ /** Off when the flag cannot be read: the request is then what 1.0.0 sends. */
946
+ function columnVisibilityOn(options) {
947
+ try {
948
+ return options.features?.columnVisibility === true;
949
+ } catch {
950
+ return false;
951
+ }
952
+ }
735
953
  /** These options admit an explicit `undefined`; core's, as published, do not: such entries go. */
736
954
  function requestOptionsOf(options) {
737
955
  const result = {};
@@ -796,9 +1014,14 @@ function createPromptResolver(options) {
796
1014
  options: promptOptions
797
1015
  };
798
1016
  if (conversationId !== void 0) body.conversationId = conversationId;
1017
+ let visibility;
1018
+ const offer = columnVisibilityOn(options) ? body.context : void 0;
799
1019
  if (grid?.connected()) try {
800
- const described = readSnapshot(grid, grid.columns(), grid.switches());
801
- if (!grid.detached && grid.connected()) body.grid = described;
1020
+ const described = readSnapshot(grid, grid.columns(), grid.switches(), offer);
1021
+ if (!grid.detached && grid.connected()) {
1022
+ body.grid = described.snapshot;
1023
+ visibility = described.visibility;
1024
+ }
802
1025
  } catch (error) {
803
1026
  grid.undescribed(error);
804
1027
  }
@@ -816,7 +1039,7 @@ function createPromptResolver(options) {
816
1039
  cause
817
1040
  });
818
1041
  }
819
- return finish(grid, await readResponse(response));
1042
+ return finish(grid, await readResponse(response), visibility);
820
1043
  }
821
1044
  let unreadable = false;
822
1045
  const gridOf = () => {
@@ -830,4 +1053,4 @@ function createPromptResolver(options) {
830
1053
  };
831
1054
  return oneAtATime(send, gridOf);
832
1055
  }
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 };
1056
+ export { CANNOT_APPLY_CODE, 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,6 @@
1
1
  {
2
2
  "name": "@gridsay/mui-x-data-grid",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Gridsay prompt resolver for the MUI X Data Grid Premium AI Assistant.",
5
5
  "keywords": [
6
6
  "gridsay",
@@ -33,7 +33,7 @@
33
33
  "dist"
34
34
  ],
35
35
  "dependencies": {
36
- "@gridsay/core": "0.1.1"
36
+ "@gridsay/core": "0.2.0"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "@mui/x-data-grid-premium": "^9.18.0"