@gridsay/mui-x-data-grid 0.1.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/dist/index.js CHANGED
@@ -1,28 +1,406 @@
1
- import { CONNECTION_FAILED, CONNECTION_FAILED as CONNECTION_FAILED$1, CONNECTION_FAILED_CODE, CONNECTION_FAILED_CODE as CONNECTION_FAILED_CODE$1, GridsayError, GridsayError as GridsayError$1, INVALID_ANSWER, INVALID_ANSWER_CODE, NOT_JSON, NOT_JSON_CODE, UNAUTHENTICATED_USER, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE } from "@gridsay/core";
1
+ import * as core 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";
2
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
+ * 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
+ /**
39
+ * The one boundary between the helper and the grid, for one question on one grid. Every call
40
+ * goes through `use`, which never throws: a call that throws, or a part that is missing or in
41
+ * another shape, is handed to `failed` with what was thrown, and gives nothing. Nothing is called
42
+ * once the grid is no longer the one on `apiRef`.
43
+ */
44
+ /**
45
+ * Thrown inside the helper when the grid cannot be described: it was found detached, or the app's
46
+ * column functions threw. The question then goes out without a description, as from MUI's resolver.
47
+ */
48
+ var Undescribed = class extends Error {};
49
+ /** For the generated test: how deep inside the one gate to the grid the helper is now. */
50
+ const gate = { depth: 0 };
51
+ var Grid = class {
52
+ failed;
53
+ /** Set once any access found the grid detached: a description read so far is then dropped. */
54
+ detached = false;
55
+ ref;
56
+ constructor(api, failed) {
57
+ this.failed = failed;
58
+ this.ref = api instanceof WeakRef ? api : new WeakRef(api);
59
+ }
60
+ /**
61
+ * The grid, when it can take the helper's reads and writes: its root element exists and is in
62
+ * the document. Checked immediately before every access, which all go through `use` and
63
+ * `column`. With React 19.3.1, hiding the grid under `<Activity>` clears its root ref, so a
64
+ * hidden grid counts as not connected and gets the stock handling. The helper never decides
65
+ * that a grid is gone.
66
+ */
67
+ live() {
68
+ const api = this.ref.deref();
69
+ if (!api) return void 0;
70
+ try {
71
+ const ref = record(api.rootElementRef, "rootElementRef");
72
+ if (!("current" in ref)) fail("rootElementRef.current");
73
+ const root = ref.current;
74
+ if (isRecord(root) && root.isConnected === true) return api;
75
+ } catch (error) {
76
+ this.failed({
77
+ member: "rootElementRef",
78
+ error
79
+ });
80
+ }
81
+ this.detached = true;
82
+ }
83
+ connected() {
84
+ return this.live() !== void 0;
85
+ }
86
+ /** The one gate to the grid: checks that it is connected, then calls; never throws. */
87
+ use(member, call) {
88
+ const api = this.live();
89
+ if (!api) return void 0;
90
+ gate.depth += 1;
91
+ try {
92
+ return { value: call(api) };
93
+ } catch (error) {
94
+ this.failed({
95
+ member,
96
+ error
97
+ });
98
+ return;
99
+ } finally {
100
+ gate.depth -= 1;
101
+ }
102
+ }
103
+ /**
104
+ * Reads from the app's own column definitions and functions (`valueOptions`, `getOptionValue`,
105
+ * `getOptionLabel`), and everything read from what they return, through the same gate. A
106
+ * detached grid, or anything thrown there, makes the grid undescribed: the throw is reported,
107
+ * and the question goes out without a description.
108
+ */
109
+ column(read) {
110
+ if (!this.live()) throw new Undescribed();
111
+ gate.depth += 1;
112
+ try {
113
+ return read();
114
+ } catch (error) {
115
+ if (error instanceof Undescribed) throw error;
116
+ if (this.live()) this.failed({
117
+ member: "column functions",
118
+ error
119
+ });
120
+ throw new Undescribed();
121
+ } finally {
122
+ gate.depth -= 1;
123
+ }
124
+ }
125
+ /** Inside `column`: before each further call into the app's functions, the grid is still there. */
126
+ still() {
127
+ if (!this.live()) throw new Undescribed();
128
+ }
129
+ /** The columns. When they cannot be read, whatever was thrown, the grid is not described. */
130
+ columns() {
131
+ const api = this.live();
132
+ if (!api) throw new Undescribed();
133
+ gate.depth += 1;
134
+ try {
135
+ const columns = api.getAllColumns();
136
+ return Array.isArray(columns) ? columns : fail("getAllColumns()");
137
+ } catch (error) {
138
+ if (this.live()) this.failed({
139
+ member: "getAllColumns",
140
+ error
141
+ });
142
+ throw new Undescribed();
143
+ } finally {
144
+ gate.depth -= 1;
145
+ }
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
+ }
166
+ /** Anything else thrown while describing the grid: reported, and the grid is not described. */
167
+ undescribed(error) {
168
+ if (!(error instanceof Undescribed)) this.failed({
169
+ member: "the description",
170
+ error
171
+ });
172
+ }
173
+ /**
174
+ * Grid-wide props. The public API does not expose them, so they are read from the private API
175
+ * the grid keeps on `apiRef.current`. When any cannot be read, nothing is guessed.
176
+ */
177
+ switches() {
178
+ const props = this.rootProps();
179
+ if (!props) return void 0;
180
+ const values = {};
181
+ let complete = true;
182
+ for (const key of SWITCHES) {
183
+ const read = this.use(`rootProps.${key}`, () => {
184
+ const value = key in props ? props[key] : fail(key);
185
+ return (key === "rowGroupingColumnMode" ? value === void 0 || value === "single" || value === "multiple" : value === void 0 || isBoolean(value)) ? value : fail(key);
186
+ });
187
+ if (read) values[key] = read.value;
188
+ else complete = false;
189
+ }
190
+ const dataSource = this.use("rootProps.dataSource", () => props.dataSource != null);
191
+ if (!complete || !dataSource) return void 0;
192
+ return {
193
+ filtering: values.disableColumnFilter !== true,
194
+ sorting: values.disableColumnSorting !== true,
195
+ grouping: values.disableRowGrouping !== true,
196
+ aggregation: values.disableAggregation !== true,
197
+ pivoting: values.disablePivoting !== true,
198
+ selection: values.rowSelection === true,
199
+ multipleGroupingColumns: values.rowGroupingColumnMode === "multiple",
200
+ dataSource: dataSource.value
201
+ };
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
+ }
220
+ filterModel() {
221
+ return this.use("state.filter.filterModel", (api) => {
222
+ const model = record(api.state.filter.filterModel, "filterModel");
223
+ return {
224
+ items: list(model.items, "filterModel.items").map((item) => {
225
+ const { field, operator, value } = record(item, "a filter item");
226
+ return {
227
+ field: string(field, "a filter item"),
228
+ operator: string(operator, "a filter item"),
229
+ value
230
+ };
231
+ }),
232
+ or: model.logicOperator === "or"
233
+ };
234
+ })?.value;
235
+ }
236
+ sortModel() {
237
+ return this.use("state.sorting.sortModel", (api) => list(api.state.sorting.sortModel, "sortModel").map((item) => {
238
+ const { field, sort } = record(item, "a sort item");
239
+ return {
240
+ field: string(field, "a sort item"),
241
+ sort: isDirection(sort) ? sort : null
242
+ };
243
+ }))?.value;
244
+ }
245
+ rowGroupingModel() {
246
+ return this.use("state.rowGrouping.model", (api) => list(api.state.rowGrouping.model, "rowGrouping.model").map((f) => string(f, "a grouping")))?.value;
247
+ }
248
+ aggregationModel() {
249
+ return this.use("state.aggregation.model", (api) => {
250
+ const model = record(api.state.aggregation.model, "aggregation.model");
251
+ return Object.fromEntries(Object.entries(model).map(([field, fn]) => [field, string(fn, "an aggregation")]));
252
+ })?.value;
253
+ }
254
+ pivotActive() {
255
+ return this.use("state.pivoting.active", (api) => {
256
+ const active = api.state.pivoting.active;
257
+ return isBoolean(active) ? active : fail("pivoting.active");
258
+ })?.value;
259
+ }
260
+ pivotModel() {
261
+ return this.use("state.pivoting.model", (api) => {
262
+ const model = record(api.state.pivoting.model, "pivoting.model");
263
+ const entry = (item) => {
264
+ const { field, hidden } = record(item, "a pivot entry");
265
+ return {
266
+ field: string(field, "a pivot entry"),
267
+ hidden: optional(hidden, isBoolean, "a pivot entry")
268
+ };
269
+ };
270
+ return {
271
+ columns: list(model.columns, "pivoting.model.columns").map((item) => ({
272
+ ...entry(item),
273
+ sort: optional(record(item, "a pivot column").sort, isDirection, "a pivot column")
274
+ })),
275
+ rows: list(model.rows, "pivoting.model.rows").map(entry),
276
+ values: list(model.values, "pivoting.model.values").map((item) => ({
277
+ ...entry(item),
278
+ aggFunc: string(record(item, "a pivot value").aggFunc, "a pivot value")
279
+ }))
280
+ };
281
+ })?.value;
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
+ }
306
+ /** The active chart's id, `''` for none. */
307
+ activeChart() {
308
+ return this.use("state.chartsIntegration.activeChartId", (api) => string(api.state.chartsIntegration.activeChartId, "activeChartId"))?.value;
309
+ }
310
+ rowsLoading() {
311
+ return this.use("state.rows.loading", (api) => {
312
+ const rows = record(api.state.rows, "state.rows");
313
+ if (!("loading" in rows)) fail("rows.loading");
314
+ return optional(rows.loading, isBoolean, "rows.loading") ?? false;
315
+ })?.value;
316
+ }
317
+ /** True once the grid took the call. */
318
+ leavePivot() {
319
+ return this.use("setPivotActive", (api) => api.setPivotActive(false)) !== void 0;
320
+ }
321
+ setAggregation(model) {
322
+ return this.use("setAggregationModel", (api) => api.setAggregationModel(model)) !== void 0;
323
+ }
324
+ /** Selects the first `count` visible leaf rows; true once the grid took the selection. */
325
+ selectTop(count) {
326
+ const ids = this.use("getSortedRowIds", (api) => list(api.getSortedRowIds(), "getSortedRowIds()").map((id) => isString(id) || typeof id === "number" ? id : fail("a row id")))?.value;
327
+ const lookup = this.use("state.filter.filteredRowsLookup", (api) => ({ ...record(api.state.filter.filteredRowsLookup, "filteredRowsLookup") }))?.value;
328
+ if (!ids || !lookup) return false;
329
+ const picked = [];
330
+ for (const id of ids) {
331
+ if (picked.length >= count) break;
332
+ if (lookup[id] === false) continue;
333
+ const node = this.use("getRowNode", (api) => api.getRowNode(id));
334
+ if (!node) return false;
335
+ const type = this.use("getRowNode().type", () => node.value === null ? null : string(record(node.value, "a row node").type, "a row node type"));
336
+ if (!type) return false;
337
+ if (type.value === "leaf") picked.push(id);
338
+ }
339
+ return this.use("setRowSelectionModel", (api) => api.setRowSelectionModel({
340
+ type: "include",
341
+ ids: new Set(picked)
342
+ })) !== void 0;
343
+ }
344
+ /**
345
+ * Waits for `event`, at most `timeout` ms, and always settles: on the event (when `onEvent`
346
+ * gives true or is left out), at the timeout, at once when the grid is detached, or when a call
347
+ * throws (`onEvent` gives undefined). It settles before cleaning up, so nothing thrown while
348
+ * unsubscribing can hold a question. `cancel` settles it as `failed`.
349
+ */
350
+ wait(event, timeout, onEvent = () => true) {
351
+ let finish = () => {};
352
+ let subscribed = false;
353
+ const settled = new Promise((resolve) => {
354
+ let done = false;
355
+ let unsubscribe;
356
+ let timer;
357
+ let watch;
358
+ finish = (result) => {
359
+ if (done) return;
360
+ done = true;
361
+ resolve(result);
362
+ clearTimeout(timer);
363
+ clearInterval(watch);
364
+ const off = unsubscribe?.value;
365
+ if (unsubscribe) try {
366
+ if (typeof off !== "function") return fail("the unsubscribe function");
367
+ off();
368
+ } catch (error) {
369
+ this.failed({
370
+ member: "unsubscribe",
371
+ error
372
+ });
373
+ }
374
+ };
375
+ if (!this.connected()) return finish("detached");
376
+ timer = setTimeout(() => finish("timeout"), timeout);
377
+ watch = setInterval(() => {
378
+ if (!this.connected()) finish("detached");
379
+ }, DETACH_CHECK_MS);
380
+ unsubscribe = this.use("subscribeEvent", (api) => api.subscribeEvent(event, () => {
381
+ if (done) return;
382
+ if (!this.connected()) return finish("detached");
383
+ const stop = onEvent();
384
+ if (stop === void 0) finish("failed");
385
+ else if (stop) finish("event");
386
+ }));
387
+ subscribed = unsubscribe !== void 0;
388
+ if (!unsubscribe) finish(this.connected() ? "failed" : "detached");
389
+ });
390
+ return Object.assign(settled, {
391
+ cancel: () => finish("failed"),
392
+ subscribed
393
+ });
394
+ }
395
+ };
3
396
  // src/grid.ts
4
397
  /** Generated grouping columns, as exported by the grid (`GRID_ROW_GROUPING_SINGLE_GROUPING_FIELD`). */
5
398
  const SINGLE_GROUPING_FIELD = "__row_group_by_columns_group__";
6
399
  const groupingField = (column) => `__row_group_by_columns_group_${column}__`;
7
- /**
8
- * Grid-wide props. The public API does not expose them, so they are read from the private API
9
- * the grid keeps on `apiRef.current`; when that is missing, every feature counts as on.
10
- */
11
- function readSwitches(api) {
12
- const symbol = Object.getOwnPropertySymbols(api).find((s) => s.description === "mui.api_private");
13
- const privateApi = symbol && Reflect.get(api, symbol);
14
- const props = isRecord(privateApi) && isRecord(privateApi.rootProps) ? privateApi.rootProps : {};
15
- return {
16
- filtering: props.disableColumnFilter !== true,
17
- sorting: props.disableColumnSorting !== true,
18
- grouping: props.disableRowGrouping !== true,
19
- aggregation: props.disableAggregation !== true,
20
- pivoting: props.disablePivoting !== true,
21
- selection: props.rowSelection !== false,
22
- multipleGroupingColumns: props.rowGroupingColumnMode === "multiple",
23
- dataSource: props.dataSource != null
24
- };
25
- }
400
+ /** The grid release this helper release is tested with. */
401
+ const TESTED_GRID = "@mui/x-data-grid-premium 9.18.0";
402
+ /** Printed once per resolver, followed by what was thrown, when part of the grid failed. */
403
+ 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.`;
26
404
  const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
27
405
  /** Sorting a grouped column must target the grouping column, or group headers keep their order. */
28
406
  function sortGroups(data, multiple) {
@@ -39,103 +417,174 @@ function sortGroups(data, multiple) {
39
417
  }];
40
418
  });
41
419
  }
42
- function selectTop(api, count) {
43
- const ids = api.getSortedRowIds().filter((id) => api.state.filter.filteredRowsLookup[id] !== false && api.getRowNode(id)?.type === "leaf").slice(0, count);
44
- api.setRowSelectionModel({
45
- type: "include",
46
- ids: new Set(ids)
47
- });
420
+ /**
421
+ * Leaves pivot mode and waits for the grid to restore its rows. True only once the grid is seen
422
+ * out of pivot mode: the steps after it assume that.
423
+ */
424
+ async function leavePivot(grid) {
425
+ const restored = grid.wait("rowsSet", 1e3);
426
+ if (!restored.subscribed) return false;
427
+ if (!grid.leavePivot() && grid.pivotActive() !== false) {
428
+ restored.cancel();
429
+ return false;
430
+ }
431
+ const result = await restored;
432
+ if (result === "failed" || result === "detached") return false;
433
+ await tick();
434
+ return grid.connected() && grid.pivotActive() === false;
48
435
  }
49
- function rowsSet(api, timeout) {
50
- return new Promise((resolve) => {
51
- const done = () => {
52
- clearTimeout(timer);
53
- unsubscribe();
54
- resolve();
55
- };
56
- const timer = setTimeout(done, timeout);
57
- const unsubscribe = api.subscribeEvent("rowsSet", done);
58
- });
436
+ /** Selects the top rows once they are this answer's: never rows of a page still loading. */
437
+ async function selectWhenLoaded(grid, top, dataSource) {
438
+ if (dataSource) {
439
+ await tick();
440
+ if (!grid.connected()) return;
441
+ const loading = grid.rowsLoading();
442
+ if (loading === void 0) return;
443
+ if (loading) {
444
+ if (await grid.wait("rowsSet", 15e3) !== "event") return;
445
+ await tick();
446
+ if (!grid.connected() || grid.rowsLoading() !== false) return;
447
+ }
448
+ }
449
+ if (grid.connected()) grid.selectTop(top);
59
450
  }
60
451
  const sameAggregation = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((k) => a[k] === b[k]);
61
452
  /** The charts integration writes back a stale aggregation model a render after a chart update. */
62
- function keepAggregation(api, aggregation) {
63
- return new Promise((resolve) => {
64
- const unsubscribe = api.subscribeEvent("aggregationModelChange", () => {
65
- if (!sameAggregation(api.state.aggregation.model, aggregation)) api.setAggregationModel(aggregation);
66
- });
67
- setTimeout(() => {
68
- unsubscribe();
69
- resolve();
70
- }, 500);
453
+ const keepAggregation = (grid, aggregation) => grid.wait("aggregationModelChange", 500, () => {
454
+ const model = grid.aggregationModel();
455
+ if (!model) return void 0;
456
+ if (!sameAggregation(model, aggregation) && !grid.setAggregation(aggregation)) return void 0;
457
+ return false;
458
+ });
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
71
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);
72
489
  }
73
490
  /**
74
491
  * Prepares a checked answer for the grid. `response` goes back to the grid, which applies it
75
492
  * synchronously; `applied` settles once the helper has finished its own changes after that.
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.
76
495
  */
77
- async function adapt(api, data) {
78
- const on = readSwitches(api);
79
- const pivots = on.pivoting && "columns" in data.pivoting;
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 });
501
+ const asItIs = {
502
+ response: data,
503
+ applied: Promise.resolve()
504
+ };
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
+ }
511
+ const on = grid.switches();
512
+ const pivots = (on ? on.pivoting : true) && "columns" in data.pivoting;
513
+ let layoutKnown = true;
514
+ if (!pivots) {
515
+ const active = grid.pivotActive();
516
+ layoutKnown = active === false || active === true && await leavePivot(grid);
517
+ if (!grid.connected()) return asItIs;
518
+ }
80
519
  const response = {
81
520
  ...data,
82
521
  select: -1
83
522
  };
523
+ if (!on || !layoutKnown) return {
524
+ response,
525
+ applied: Promise.resolve()
526
+ };
84
527
  if (on.grouping && !pivots && !on.dataSource && data.grouping.length > 0) response.sorting = sortGroups(data, on.multipleGroupingColumns);
85
- if (!pivots && api.state.pivoting.active) {
86
- const restored = rowsSet(api, 1e3);
87
- api.setPivotActive(false);
88
- await restored;
89
- await tick();
90
- }
91
528
  const top = on.selection && data.select > 0 ? data.select : 0;
92
- const charted = data.chart && !pivots && on.aggregation && api.state.chartsIntegration.activeChartId;
529
+ const charted = data.chart && !pivots && on.aggregation && grid.activeChart();
93
530
  return {
94
531
  response,
95
532
  applied: (async () => {
96
- const kept = charted ? keepAggregation(api, data.aggregation) : void 0;
533
+ const kept = charted ? keepAggregation(grid, data.aggregation) : void 0;
97
534
  await tick();
98
- if (top > 0) {
99
- if (on.dataSource) {
100
- await tick();
101
- if (api.state.rows.loading) {
102
- await rowsSet(api, 15e3);
103
- await tick();
104
- }
105
- }
106
- selectTop(api, top);
107
- }
535
+ if (top > 0 && grid.connected()) await selectWhenLoaded(grid, top, on.dataSource);
108
536
  await kept;
109
537
  })()
110
538
  };
111
539
  }
112
540
  // src/queue.ts
113
- const finish = (api, data) => api ? adapt(api, data) : {
114
- response: data,
115
- applied: Promise.resolve()
541
+ /** The answer for the grid, adapted when there is a grid to adapt it to. */
542
+ async function finish(grid, answer, visibility) {
543
+ if (grid) return adapt(grid, answer, visibility);
544
+ const { hiddenColumns, ...response } = answer;
545
+ return {
546
+ response,
547
+ applied: Promise.resolve()
548
+ };
549
+ }
550
+ /**
551
+ * The one bound on the line: a question waits at most this long for the one before it on the same
552
+ * grid, then is sent anyway. The request itself, like MUI's own resolver's, has no time limit.
553
+ */
554
+ const QUEUE_WAIT_MS = 6e4;
555
+ /** `promise`, or nothing once `ms` have passed; the timer never outlives it. */
556
+ function atMost(promise, ms) {
557
+ let timer;
558
+ const elapsed = new Promise((resolve) => {
559
+ timer = setTimeout(resolve, ms);
560
+ });
561
+ return Promise.race([promise, elapsed]).finally(() => clearTimeout(timer));
562
+ }
563
+ /**
564
+ * One line per grid API instance, shared by every resolver created for that grid (the README's
565
+ * `useMemo` makes a new one when `apiRef` changes), kept weakly: a grid that is gone takes its line.
566
+ */
567
+ const lines = /* @__PURE__ */ new WeakMap();
568
+ const lineOf = (api) => {
569
+ let line = lines.get(api);
570
+ if (!line) {
571
+ line = { queue: Promise.resolve() };
572
+ lines.set(api, line);
573
+ }
574
+ return line;
116
575
  };
117
- /** One prompt at a time, so a follow-up is sent after the previous answer is on the grid. */
118
- function oneAtATime(send) {
119
- let queue = Promise.resolve();
120
- let pending;
576
+ /**
577
+ * One prompt at a time per grid, so a follow-up is sent after the previous answer is on it. Each
578
+ * question carries exactly the conversation id the grid gave it, as with MUI's own resolver.
579
+ */
580
+ function oneAtATime(send, grid) {
581
+ const unbound = { queue: Promise.resolve() };
121
582
  return (query, context, conversationId) => {
122
- const previous = {
123
- queue,
124
- call: pending
125
- };
126
- const call = { asked: conversationId };
127
- pending = call;
128
- const result = previous.queue.then(async () => {
129
- const prev = previous.call;
130
- const sent = await send(query, context, prev && prev.asked === conversationId ? prev.received ?? conversationId : conversationId);
131
- call.received = sent.response.conversationId;
132
- return sent;
133
- });
134
- const settle = () => {
135
- if (pending === call) pending = void 0;
136
- };
137
- result.then(settle, settle);
138
- queue = result.then((sent) => sent.applied).catch(() => void 0);
583
+ const api = grid();
584
+ const own = api ? lineOf(api) : unbound;
585
+ const weak = api ? new WeakRef(api) : null;
586
+ const result = atMost(own.queue, QUEUE_WAIT_MS).then(() => send(query, context, conversationId, weak));
587
+ own.queue = result.then((sent) => sent.applied).catch(() => void 0);
139
588
  return result.then((sent) => sent.response);
140
589
  };
141
590
  }
@@ -148,28 +597,77 @@ const FUNCTIONS = [
148
597
  "size"
149
598
  ];
150
599
  const isFunction = (fn) => FUNCTIONS.includes(fn);
151
- const isGenerated = (field) => field.startsWith("__") && field.endsWith("__");
152
- function readOptions(column) {
153
- if (!column.valueOptions) return [];
154
- let raw;
155
- try {
156
- raw = typeof column.valueOptions === "function" ? column.valueOptions({ field: column.field }) : column.valueOptions;
157
- } catch {
158
- return [];
159
- }
160
- return raw.flatMap((option) => {
161
- const value = column.getOptionValue ? column.getOptionValue(option) : isRecord(option) ? option.value : option;
162
- const label = column.getOptionLabel ? column.getOptionLabel(option) : isRecord(option) ? option.label : option;
600
+ const PIVOT_SEPARATOR = ">->";
601
+ /** A column the grid generated, or one named after cell values: never written into the description. */
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__";
617
+ const OPTIONS = 500;
618
+ /** The gateway's cap on the hidden columns a grid sends. */
619
+ const HIDDEN = 500;
620
+ const AGGREGATION_FUNCTIONS = 32;
621
+ const OPERATORS = 64;
622
+ /**
623
+ * One read of a property of something the app gave, with the grid checked just before it: nothing
624
+ * the app holds is read once the grid has left the document.
625
+ */
626
+ function at(grid, object, key) {
627
+ grid.still();
628
+ return object[key];
629
+ }
630
+ /** At most `limit` elements of an array, each read once by index: no iterator, nothing past the limit. */
631
+ function firstOf(grid, given, limit) {
632
+ if (!Array.isArray(given)) return [];
633
+ const length = Math.min(Number(at(grid, given, "length")) || 0, limit);
634
+ const copy = [];
635
+ for (let i = 0; i < length; i++) copy.push(at(grid, given, i));
636
+ return copy;
637
+ }
638
+ /** Calls one of the app's column functions as MUI does: as the column's method. */
639
+ function call(grid, fn, column, argument) {
640
+ grid.still();
641
+ return fn.call(column, argument);
642
+ }
643
+ /**
644
+ * A select column's options, read as MUI reads them: `valueOptions` called as the column's method
645
+ * with `{ field }`, then the column's `getOptionValue` and `getOptionLabel` as its methods, once
646
+ * per option, for at most the first 500 options. Without them, MUI's defaults for the type.
647
+ */
648
+ function readOptions(grid, column, field) {
649
+ const valueOptions = at(grid, column, "valueOptions");
650
+ const getValue = at(grid, column, "getOptionValue");
651
+ const getLabel = at(grid, column, "getOptionLabel");
652
+ const given = typeof valueOptions === "function" ? call(grid, valueOptions, column, { field }) : valueOptions;
653
+ const options = [];
654
+ for (const option of firstOf(grid, given, OPTIONS)) {
655
+ const object = isRecord(option);
656
+ const value = typeof getValue === "function" ? call(grid, getValue, column, option) : object ? at(grid, option, "value") : option;
657
+ const label = typeof getLabel === "function" ? call(grid, getLabel, column, option) : object ? at(grid, option, "label") : String(option);
163
658
  const text = typeof label === "number" ? String(label) : label;
164
- if (typeof text !== "string" || text.length > 255) return [];
165
- if (typeof value === "number" || typeof value === "string" && value.length <= 255) return [{
659
+ if (typeof text !== "string" || text.length > 255) continue;
660
+ if (typeof value === "number" || typeof value === "string" && value.length <= 255) options.push({
166
661
  value,
167
662
  label: text
168
- }];
169
- return [];
170
- }).slice(0, 500);
663
+ });
664
+ }
665
+ return options;
171
666
  }
172
- function readLimits(column) {
667
+ /** Copies what the description needs from one column, reading each property once. */
668
+ function copyColumn(grid, column, field) {
669
+ if (isGenerated(field) || field.length > 255) return void 0;
670
+ const type = at(grid, column, "type");
173
671
  const limits = {};
174
672
  for (const flag of [
175
673
  "filterable",
@@ -177,24 +675,123 @@ function readLimits(column) {
177
675
  "groupable",
178
676
  "pivotable",
179
677
  "aggregable"
180
- ]) if (column[flag] === false) limits[flag] = false;
181
- const functions = column.availableAggregationFunctions?.filter((fn) => fn.length <= 64);
182
- if (functions) limits.aggregationFunctions = functions.slice(0, 32);
183
- const options = readOptions(column);
184
- if (options.length > 0) limits.options = options;
185
- return limits;
678
+ ]) if (at(grid, column, flag) === false) limits[flag] = false;
679
+ const available = at(grid, column, "availableAggregationFunctions");
680
+ if (Array.isArray(available)) limits.aggregationFunctions = firstOf(grid, available, AGGREGATION_FUNCTIONS).filter((fn) => typeof fn === "string" && fn.length <= 64);
681
+ if (type === "singleSelect" || type === "multiSelect") {
682
+ const options = readOptions(grid, column, field);
683
+ if (options.length > 0) limits.options = options;
684
+ }
685
+ return {
686
+ field,
687
+ type,
688
+ limits,
689
+ operators: firstOf(grid, at(grid, column, "filterOperators"), OPERATORS).map((operator) => isRecord(operator) ? {
690
+ value: at(grid, operator, "value"),
691
+ requiresFilterValue: at(grid, operator, "requiresFilterValue")
692
+ } : {
693
+ value: void 0,
694
+ requiresFilterValue: void 0
695
+ })
696
+ };
697
+ }
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
+ /**
737
+ * MUI's column context with each option list cut to its first 500 options, each to its value and
738
+ * label: what else an app or `getPivotDerivedColumns` attaches to an option stays in the browser.
739
+ * A context with no option list goes exactly as the grid built it.
740
+ */
741
+ function boundedContext(context) {
742
+ let columns;
743
+ try {
744
+ columns = JSON.parse(context);
745
+ } catch {
746
+ return context;
747
+ }
748
+ if (!Array.isArray(columns) || !columns.some((c) => isRecord(c) && "valueOptions" in c)) return context;
749
+ return JSON.stringify(columns.map((column) => {
750
+ if (!isRecord(column) || !("valueOptions" in column)) return column;
751
+ const { valueOptions, ...rest } = column;
752
+ if (!Array.isArray(valueOptions)) return rest;
753
+ const options = valueOptions.slice(0, OPTIONS).flatMap((option) => {
754
+ const plain = (value) => [
755
+ "string",
756
+ "number",
757
+ "boolean"
758
+ ].includes(typeof value);
759
+ if (!isRecord(option)) return plain(option) ? [option] : [];
760
+ const { value, label } = option;
761
+ return plain(value) && (label === void 0 || plain(label)) ? [{
762
+ value,
763
+ label
764
+ }] : [];
765
+ });
766
+ return {
767
+ ...rest,
768
+ valueOptions: options
769
+ };
770
+ }));
186
771
  }
187
772
  function toFilterValue(value) {
188
773
  if (typeof value === "string" || typeof value === "boolean") return value;
189
774
  if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
190
775
  if (value instanceof Date) return Number.isNaN(value.getTime()) ? void 0 : value.toISOString();
191
776
  if (!Array.isArray(value)) return void 0;
192
- if (value.every((item) => typeof item === "number")) return value;
193
- return value.map(String);
777
+ const items = Array.from({ length: value.length }, (_, i) => value[i]);
778
+ if (items.every((item) => typeof item === "number")) return items;
779
+ const texts = items.map(toText);
780
+ return texts.every((text) => text !== void 0) ? texts : void 0;
781
+ }
782
+ /** An element of a filter value as text, or undefined unless it is text, a number, a boolean or a date. */
783
+ function toText(value) {
784
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? void 0 : value.toISOString();
785
+ return [
786
+ "string",
787
+ "number",
788
+ "boolean"
789
+ ].includes(typeof value) ? String(value) : void 0;
194
790
  }
195
- function readFilters(api, columns) {
196
- return api.state.filter.filterModel.items.flatMap((item) => {
197
- const valueless = columns.get(item.field)?.filterOperators?.find((o) => o.value === item.operator)?.requiresFilterValue === false;
791
+ function readFilters(items, operators) {
792
+ return items.flatMap((item) => {
793
+ if (isGenerated(item.field)) return [];
794
+ const valueless = operators.get(item.field)?.find((o) => o.value === item.operator)?.requiresFilterValue === false;
198
795
  const value = valueless ? "" : toFilterValue(item.value);
199
796
  if (value === void 0 || !valueless && (value === "" || Array.isArray(value) && !value.length)) return [];
200
797
  return [{
@@ -204,14 +801,25 @@ function readFilters(api, columns) {
204
801
  }];
205
802
  });
206
803
  }
207
- function readState(api, columns) {
208
- const { filter, sorting, rowGrouping, aggregation, pivoting } = api.state;
804
+ /**
805
+ * The grid's current view, or undefined when part of it cannot be read: a partial state would
806
+ * tell the server the missing part is empty, so it is left out whole.
807
+ */
808
+ function readState(grid, operators) {
809
+ const filter = grid.filterModel();
810
+ const sortModel = grid.sortModel();
811
+ const rowGrouping = grid.rowGroupingModel();
812
+ const aggregation = grid.aggregationModel();
813
+ const active = grid.pivotActive();
814
+ const model = active ? grid.pivotModel() : void 0;
815
+ if (!filter || !sortModel || !rowGrouping || !aggregation || active === void 0) return void 0;
816
+ if (active && !model) return void 0;
209
817
  const state = {};
210
- const filters = readFilters(api, columns);
818
+ const filters = grid.column(() => readFilters(filter.items, operators));
211
819
  if (filters.length > 0) state.filters = filters;
212
- if (filters.length > 1 && filter.filterModel.logicOperator === "or") state.filterOperator = "or";
213
- const grouping = pivoting.active ? [] : rowGrouping.model;
214
- const sorts = sorting.sortModel.flatMap((item) => {
820
+ if (filters.length > 1 && filter.or) state.filterOperator = "or";
821
+ const grouping = active ? [] : rowGrouping.filter((field) => !isGenerated(field));
822
+ const sorts = sortModel.flatMap((item) => {
215
823
  const column = item.field === "__row_group_by_columns_group__" ? grouping[0] : item.field.replace(/^__row_group_by_columns_group_(.+)__$/, "$1");
216
824
  return item.sort && column && !isGenerated(column) ? [{
217
825
  column,
@@ -219,78 +827,230 @@ function readState(api, columns) {
219
827
  }] : [];
220
828
  });
221
829
  if (sorts.length > 0) state.sorting = sorts;
222
- if (pivoting.active) {
223
- const model = pivoting.model;
224
- state.pivoting = {
225
- columns: model.columns.filter((c) => !c.hidden).map((c) => ({
226
- column: c.field,
227
- direction: c.sort ?? "asc"
228
- })),
229
- rows: model.rows.filter((r) => !r.hidden).map((r) => r.field),
230
- values: model.values.flatMap((v) => !v.hidden && isFunction(v.aggFunc) ? [{ [v.field]: v.aggFunc }] : [])
231
- };
830
+ if (model) {
831
+ state.pivoting = readPivot(model);
232
832
  return state;
233
833
  }
234
834
  if (grouping.length > 0) state.grouping = grouping.map((column) => ({ column }));
235
- const functions = Object.entries(aggregation.model).flatMap(([field, fn]) => isFunction(fn) ? [[field, fn]] : []);
835
+ const functions = Object.entries(aggregation).flatMap(([field, fn]) => isFunction(fn) && !isGenerated(field) ? [[field, fn]] : []);
236
836
  if (functions.length > 0) state.aggregation = Object.fromEntries(functions);
237
837
  return state;
238
838
  }
239
- /** What the grid allows and shows, leaving out everything at its default. */
240
- function readSnapshot(api) {
241
- const on = readSwitches(api);
839
+ function readPivot(model) {
840
+ return {
841
+ columns: model.columns.filter((c) => !c.hidden && !isGenerated(c.field)).map((c) => ({
842
+ column: c.field,
843
+ direction: c.sort ?? "asc"
844
+ })),
845
+ rows: model.rows.filter((r) => !r.hidden && !isGenerated(r.field)).map((r) => r.field),
846
+ values: model.values.flatMap((v) => !v.hidden && !isGenerated(v.field) && isFunction(v.aggFunc) ? [{ [v.field]: v.aggFunc }] : [])
847
+ };
848
+ }
849
+ function switchedOff(on) {
850
+ const off = [];
851
+ if (!on.filtering) off.push("filtering");
852
+ if (!on.sorting) off.push("sorting");
853
+ if (!on.grouping) off.push("grouping");
854
+ if (!on.aggregation) off.push("aggregation");
855
+ if (!on.pivoting) off.push("pivoting");
856
+ if (!on.selection) off.push("selection");
857
+ return off;
858
+ }
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
+ /**
882
+ * What the grid allows and shows, from its columns, leaving out everything at its default and
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.
886
+ */
887
+ function readSnapshot(grid, allColumns, on, context) {
242
888
  const disabled = [];
243
- if (!on.filtering) disabled.push("filtering");
244
- if (!on.sorting) disabled.push("sorting");
245
- if (!on.grouping) disabled.push("grouping");
246
- if (!on.aggregation) disabled.push("aggregation");
247
- if (!on.pivoting) disabled.push("pivoting");
248
- if (!on.selection) disabled.push("selection");
249
- if (!api.state.chartsIntegration.activeChartId) disabled.push("charts");
250
- const all = api.getAllColumns().filter((c) => !isGenerated(c.field) && c.field.length <= 255);
889
+ if (on) disabled.push(...switchedOff(on));
890
+ if (grid.activeChart() === "") disabled.push("charts");
891
+ const live = [];
892
+ const copied = 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
+ });
900
+ });
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)));
251
904
  const columns = {};
252
- for (const column of all) {
253
- const limits = readLimits(column);
254
- if (Object.keys(limits).length > 0) columns[column.field] = limits;
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;
255
911
  }
256
- const state = readState(api, new Map(all.map((c) => [c.field, c])));
912
+ for (const field of locked) if (!Object.hasOwn(columns, field)) columns[field] = { hideable: false };
257
913
  const snapshot = {};
914
+ if (visibility) snapshot.accepts = ["hiddenColumns"];
258
915
  if (disabled.length > 0) snapshot.disabled = disabled;
259
916
  if (Object.keys(columns).length > 0) snapshot.columns = columns;
260
- snapshot.state = state;
261
- 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
+ };
262
925
  }
263
926
  // src/index.ts
927
+ const CONNECTION_FAILED = core.CONNECTION_FAILED;
928
+ const INVALID_ANSWER = core.INVALID_ANSWER;
929
+ const NOT_JSON = core.NOT_JSON;
930
+ const UNAUTHENTICATED_USER = core.UNAUTHENTICATED_USER;
931
+ function hold(member, error) {
932
+ let text;
933
+ try {
934
+ text = error instanceof Error ? `${error.name}: ${error.message}\n${error.stack ?? ""}` : String(error);
935
+ } catch {
936
+ text = "An error that could not be read.";
937
+ }
938
+ return {
939
+ member,
940
+ error: typeof error === "object" && error !== null ? new WeakRef(error) : void 0,
941
+ text
942
+ };
943
+ }
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
+ }
953
+ /** These options admit an explicit `undefined`; core's, as published, do not: such entries go. */
954
+ function requestOptionsOf(options) {
955
+ const result = {};
956
+ for (const [key, value] of Object.entries(options)) if (value !== void 0) Object.assign(result, { [key]: value });
957
+ return result;
958
+ }
264
959
  /** Replaces `unstable_gridDefaultPromptResolver` as the grid's `onPrompt`. */
265
960
  function createPromptResolver(options) {
266
961
  const { url, apiRef } = options;
267
- const promptOptions = promptOptionsOf(options);
268
- async function send(query, context, conversationId) {
269
- const api = apiRef?.current ?? null;
962
+ const requestOptions = requestOptionsOf(options);
963
+ const promptOptions = promptOptionsOf(requestOptions);
964
+ let holder;
965
+ const owner = /* @__PURE__ */ new Map();
966
+ async function send(query, context, conversationId, api) {
967
+ const failures = [];
968
+ const flush = () => {
969
+ const mine = failures.filter((f) => owner.get(f.member) === failures);
970
+ if (mine.length === 0) return;
971
+ if (holder === failures) {
972
+ console.warn(gridWarning(mine.map((f) => f.member)), ...mine.map(thrownOf));
973
+ return;
974
+ }
975
+ const printed = /* @__PURE__ */ new Set();
976
+ for (const held of mine) {
977
+ const { member } = held;
978
+ if (printed.has(member)) continue;
979
+ printed.add(member);
980
+ console.warn(`@gridsay/mui-x-data-grid: ${member} could not be read or changed; skipped.`, thrownOf(held));
981
+ }
982
+ };
983
+ /** Logs, then lets go of what was thrown: an error can hold on to a grid that is gone. */
984
+ const report = () => {
985
+ flush();
986
+ failures.length = 0;
987
+ };
988
+ const grid = api ? new Grid(api, (caught) => {
989
+ const failure = hold(caught.member, caught.error);
990
+ failures.push(failure);
991
+ if (!owner.has(failure.member)) owner.set(failure.member, failures);
992
+ holder ??= failures;
993
+ }) : null;
994
+ try {
995
+ const sent = await ask(grid, query, context, conversationId);
996
+ return {
997
+ ...sent,
998
+ applied: sent.applied.finally(report)
999
+ };
1000
+ } catch (error) {
1001
+ report();
1002
+ if (error instanceof GridsayError$1) throw error;
1003
+ throw new GridsayError$1(INVALID_ANSWER, {
1004
+ code: UNEXPECTED_ERROR_CODE$1,
1005
+ cause: error
1006
+ });
1007
+ }
1008
+ }
1009
+ async function ask(grid, query, context, conversationId) {
1010
+ const headers = await requestHeaders(requestOptions);
270
1011
  const body = {
271
- context,
1012
+ context: boundedContext(context),
272
1013
  query,
273
- conversationId,
274
1014
  options: promptOptions
275
1015
  };
276
- if (api) body.grid = readSnapshot(api);
1016
+ if (conversationId !== void 0) body.conversationId = conversationId;
1017
+ let visibility;
1018
+ const offer = columnVisibilityOn(options) ? body.context : void 0;
1019
+ if (grid?.connected()) try {
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
+ }
1025
+ } catch (error) {
1026
+ grid.undescribed(error);
1027
+ }
277
1028
  const init = {
278
1029
  method: "POST",
279
- headers: await requestHeaders(options),
1030
+ headers,
280
1031
  body: JSON.stringify(body)
281
1032
  };
282
1033
  let response;
283
1034
  try {
284
1035
  response = await fetch(url, init);
285
1036
  } catch (cause) {
286
- throw new GridsayError$1(CONNECTION_FAILED$1, {
1037
+ throw new GridsayError$1(CONNECTION_FAILED, {
287
1038
  code: CONNECTION_FAILED_CODE$1,
288
1039
  cause
289
1040
  });
290
1041
  }
291
- const data = await readResponse(response);
292
- return finish(api, data);
1042
+ return finish(grid, await readResponse(response), visibility);
293
1043
  }
294
- return oneAtATime(send);
1044
+ let unreadable = false;
1045
+ const gridOf = () => {
1046
+ try {
1047
+ return apiRef?.current ?? null;
1048
+ } catch (error) {
1049
+ if (!unreadable) console.warn(gridWarning(["apiRef.current"]), error);
1050
+ unreadable = true;
1051
+ return null;
1052
+ }
1053
+ };
1054
+ return oneAtATime(send, gridOf);
295
1055
  }
296
- 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 };