@gridsay/mui-x-data-grid 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,28 +1,340 @@
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 { 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
3
  import { isRecord, promptOptionsOf, readResponse, requestHeaders } from "@gridsay/core/internal";
4
+ // src/boundary.ts
5
+ /** Root props the grid always fills in, with its defaults, in the tested release. */
6
+ const SWITCHES = [
7
+ "disableColumnFilter",
8
+ "disableColumnSorting",
9
+ "disableRowGrouping",
10
+ "disableAggregation",
11
+ "disablePivoting",
12
+ "rowSelection",
13
+ "rowGroupingColumnMode"
14
+ ];
15
+ /** How often a wait checks that its grid's root is still in the document. */
16
+ const DETACH_CHECK_MS = 50;
17
+ const fail = (what) => {
18
+ throw new TypeError(`${what} is missing or not in the shape the tested grid release has`);
19
+ };
20
+ const isString = (value) => typeof value === "string";
21
+ const list = (value, what) => Array.isArray(value) ? value : fail(what);
22
+ const record = (value, what) => isRecord(value) ? value : fail(what);
23
+ const string = (value, what) => isString(value) ? value : fail(what);
24
+ const optional = (value, check, what) => value === void 0 || check(value) ? value : fail(what);
25
+ const isDirection = (value) => value === "asc" || value === "desc";
26
+ const isBoolean = (value) => typeof value === "boolean";
27
+ /**
28
+ * The one boundary between the helper and the grid, for one question on one grid. Every call
29
+ * goes through `use`, which never throws: a call that throws, or a part that is missing or in
30
+ * another shape, is handed to `failed` with what was thrown, and gives nothing. Nothing is called
31
+ * once the grid is no longer the one on `apiRef`.
32
+ */
33
+ /**
34
+ * Thrown inside the helper when the grid cannot be described: it was found detached, or the app's
35
+ * column functions threw. The question then goes out without a description, as from MUI's resolver.
36
+ */
37
+ var Undescribed = class extends Error {};
38
+ /** For the generated test: how deep inside the one gate to the grid the helper is now. */
39
+ const gate = { depth: 0 };
40
+ var Grid = class {
41
+ failed;
42
+ /** Set once any access found the grid detached: a description read so far is then dropped. */
43
+ detached = false;
44
+ ref;
45
+ constructor(api, failed) {
46
+ this.failed = failed;
47
+ this.ref = api instanceof WeakRef ? api : new WeakRef(api);
48
+ }
49
+ /**
50
+ * The grid, when it can take the helper's reads and writes: its root element exists and is in
51
+ * the document. Checked immediately before every access, which all go through `use` and
52
+ * `column`. With React 19.3.1, hiding the grid under `<Activity>` clears its root ref, so a
53
+ * hidden grid counts as not connected and gets the stock handling. The helper never decides
54
+ * that a grid is gone.
55
+ */
56
+ live() {
57
+ const api = this.ref.deref();
58
+ if (!api) return void 0;
59
+ try {
60
+ const ref = record(api.rootElementRef, "rootElementRef");
61
+ if (!("current" in ref)) fail("rootElementRef.current");
62
+ const root = ref.current;
63
+ if (isRecord(root) && root.isConnected === true) return api;
64
+ } catch (error) {
65
+ this.failed({
66
+ member: "rootElementRef",
67
+ error
68
+ });
69
+ }
70
+ this.detached = true;
71
+ }
72
+ connected() {
73
+ return this.live() !== void 0;
74
+ }
75
+ /** The one gate to the grid: checks that it is connected, then calls; never throws. */
76
+ use(member, call) {
77
+ const api = this.live();
78
+ if (!api) return void 0;
79
+ gate.depth += 1;
80
+ try {
81
+ return { value: call(api) };
82
+ } catch (error) {
83
+ this.failed({
84
+ member,
85
+ error
86
+ });
87
+ return;
88
+ } finally {
89
+ gate.depth -= 1;
90
+ }
91
+ }
92
+ /**
93
+ * Reads from the app's own column definitions and functions (`valueOptions`, `getOptionValue`,
94
+ * `getOptionLabel`), and everything read from what they return, through the same gate. A
95
+ * detached grid, or anything thrown there, makes the grid undescribed: the throw is reported,
96
+ * and the question goes out without a description.
97
+ */
98
+ column(read) {
99
+ if (!this.live()) throw new Undescribed();
100
+ gate.depth += 1;
101
+ try {
102
+ return read();
103
+ } catch (error) {
104
+ if (error instanceof Undescribed) throw error;
105
+ if (this.live()) this.failed({
106
+ member: "column functions",
107
+ error
108
+ });
109
+ throw new Undescribed();
110
+ } finally {
111
+ gate.depth -= 1;
112
+ }
113
+ }
114
+ /** Inside `column`: before each further call into the app's functions, the grid is still there. */
115
+ still() {
116
+ if (!this.live()) throw new Undescribed();
117
+ }
118
+ /** The columns. When they cannot be read, whatever was thrown, the grid is not described. */
119
+ columns() {
120
+ const api = this.live();
121
+ if (!api) throw new Undescribed();
122
+ gate.depth += 1;
123
+ try {
124
+ const columns = api.getAllColumns();
125
+ return Array.isArray(columns) ? columns : fail("getAllColumns()");
126
+ } catch (error) {
127
+ if (this.live()) this.failed({
128
+ member: "getAllColumns",
129
+ error
130
+ });
131
+ throw new Undescribed();
132
+ } finally {
133
+ gate.depth -= 1;
134
+ }
135
+ }
136
+ /** Anything else thrown while describing the grid: reported, and the grid is not described. */
137
+ undescribed(error) {
138
+ if (!(error instanceof Undescribed)) this.failed({
139
+ member: "the description",
140
+ error
141
+ });
142
+ }
143
+ /**
144
+ * Grid-wide props. The public API does not expose them, so they are read from the private API
145
+ * the grid keeps on `apiRef.current`. When any cannot be read, nothing is guessed.
146
+ */
147
+ switches() {
148
+ const props = this.use("privateApi", (api) => {
149
+ const symbol = Object.getOwnPropertySymbols(api).find((s) => s.description === "mui.api_private");
150
+ const privateApi = symbol ? Reflect.get(api, symbol) : void 0;
151
+ return record(record(privateApi, "the private API").rootProps, "the private API");
152
+ })?.value;
153
+ if (!props) return void 0;
154
+ const values = {};
155
+ let complete = true;
156
+ for (const key of SWITCHES) {
157
+ const read = this.use(`rootProps.${key}`, () => {
158
+ const value = key in props ? props[key] : fail(key);
159
+ return (key === "rowGroupingColumnMode" ? value === void 0 || value === "single" || value === "multiple" : value === void 0 || isBoolean(value)) ? value : fail(key);
160
+ });
161
+ if (read) values[key] = read.value;
162
+ else complete = false;
163
+ }
164
+ const dataSource = this.use("rootProps.dataSource", () => props.dataSource != null);
165
+ if (!complete || !dataSource) return void 0;
166
+ return {
167
+ filtering: values.disableColumnFilter !== true,
168
+ sorting: values.disableColumnSorting !== true,
169
+ grouping: values.disableRowGrouping !== true,
170
+ aggregation: values.disableAggregation !== true,
171
+ pivoting: values.disablePivoting !== true,
172
+ selection: values.rowSelection === true,
173
+ multipleGroupingColumns: values.rowGroupingColumnMode === "multiple",
174
+ dataSource: dataSource.value
175
+ };
176
+ }
177
+ filterModel() {
178
+ return this.use("state.filter.filterModel", (api) => {
179
+ const model = record(api.state.filter.filterModel, "filterModel");
180
+ return {
181
+ items: list(model.items, "filterModel.items").map((item) => {
182
+ const { field, operator, value } = record(item, "a filter item");
183
+ return {
184
+ field: string(field, "a filter item"),
185
+ operator: string(operator, "a filter item"),
186
+ value
187
+ };
188
+ }),
189
+ or: model.logicOperator === "or"
190
+ };
191
+ })?.value;
192
+ }
193
+ sortModel() {
194
+ return this.use("state.sorting.sortModel", (api) => list(api.state.sorting.sortModel, "sortModel").map((item) => {
195
+ const { field, sort } = record(item, "a sort item");
196
+ return {
197
+ field: string(field, "a sort item"),
198
+ sort: isDirection(sort) ? sort : null
199
+ };
200
+ }))?.value;
201
+ }
202
+ rowGroupingModel() {
203
+ return this.use("state.rowGrouping.model", (api) => list(api.state.rowGrouping.model, "rowGrouping.model").map((f) => string(f, "a grouping")))?.value;
204
+ }
205
+ aggregationModel() {
206
+ return this.use("state.aggregation.model", (api) => {
207
+ const model = record(api.state.aggregation.model, "aggregation.model");
208
+ return Object.fromEntries(Object.entries(model).map(([field, fn]) => [field, string(fn, "an aggregation")]));
209
+ })?.value;
210
+ }
211
+ pivotActive() {
212
+ return this.use("state.pivoting.active", (api) => {
213
+ const active = api.state.pivoting.active;
214
+ return isBoolean(active) ? active : fail("pivoting.active");
215
+ })?.value;
216
+ }
217
+ pivotModel() {
218
+ return this.use("state.pivoting.model", (api) => {
219
+ const model = record(api.state.pivoting.model, "pivoting.model");
220
+ const entry = (item) => {
221
+ const { field, hidden } = record(item, "a pivot entry");
222
+ return {
223
+ field: string(field, "a pivot entry"),
224
+ hidden: optional(hidden, isBoolean, "a pivot entry")
225
+ };
226
+ };
227
+ return {
228
+ columns: list(model.columns, "pivoting.model.columns").map((item) => ({
229
+ ...entry(item),
230
+ sort: optional(record(item, "a pivot column").sort, isDirection, "a pivot column")
231
+ })),
232
+ rows: list(model.rows, "pivoting.model.rows").map(entry),
233
+ values: list(model.values, "pivoting.model.values").map((item) => ({
234
+ ...entry(item),
235
+ aggFunc: string(record(item, "a pivot value").aggFunc, "a pivot value")
236
+ }))
237
+ };
238
+ })?.value;
239
+ }
240
+ /** The active chart's id, `''` for none. */
241
+ activeChart() {
242
+ return this.use("state.chartsIntegration.activeChartId", (api) => string(api.state.chartsIntegration.activeChartId, "activeChartId"))?.value;
243
+ }
244
+ rowsLoading() {
245
+ return this.use("state.rows.loading", (api) => {
246
+ const rows = record(api.state.rows, "state.rows");
247
+ if (!("loading" in rows)) fail("rows.loading");
248
+ return optional(rows.loading, isBoolean, "rows.loading") ?? false;
249
+ })?.value;
250
+ }
251
+ /** True once the grid took the call. */
252
+ leavePivot() {
253
+ return this.use("setPivotActive", (api) => api.setPivotActive(false)) !== void 0;
254
+ }
255
+ setAggregation(model) {
256
+ return this.use("setAggregationModel", (api) => api.setAggregationModel(model)) !== void 0;
257
+ }
258
+ /** Selects the first `count` visible leaf rows; true once the grid took the selection. */
259
+ selectTop(count) {
260
+ const ids = this.use("getSortedRowIds", (api) => list(api.getSortedRowIds(), "getSortedRowIds()").map((id) => isString(id) || typeof id === "number" ? id : fail("a row id")))?.value;
261
+ const lookup = this.use("state.filter.filteredRowsLookup", (api) => ({ ...record(api.state.filter.filteredRowsLookup, "filteredRowsLookup") }))?.value;
262
+ if (!ids || !lookup) return false;
263
+ const picked = [];
264
+ for (const id of ids) {
265
+ if (picked.length >= count) break;
266
+ if (lookup[id] === false) continue;
267
+ const node = this.use("getRowNode", (api) => api.getRowNode(id));
268
+ if (!node) return false;
269
+ const type = this.use("getRowNode().type", () => node.value === null ? null : string(record(node.value, "a row node").type, "a row node type"));
270
+ if (!type) return false;
271
+ if (type.value === "leaf") picked.push(id);
272
+ }
273
+ return this.use("setRowSelectionModel", (api) => api.setRowSelectionModel({
274
+ type: "include",
275
+ ids: new Set(picked)
276
+ })) !== void 0;
277
+ }
278
+ /**
279
+ * Waits for `event`, at most `timeout` ms, and always settles: on the event (when `onEvent`
280
+ * gives true or is left out), at the timeout, at once when the grid is detached, or when a call
281
+ * throws (`onEvent` gives undefined). It settles before cleaning up, so nothing thrown while
282
+ * unsubscribing can hold a question. `cancel` settles it as `failed`.
283
+ */
284
+ wait(event, timeout, onEvent = () => true) {
285
+ let finish = () => {};
286
+ let subscribed = false;
287
+ const settled = new Promise((resolve) => {
288
+ let done = false;
289
+ let unsubscribe;
290
+ let timer;
291
+ let watch;
292
+ finish = (result) => {
293
+ if (done) return;
294
+ done = true;
295
+ resolve(result);
296
+ clearTimeout(timer);
297
+ clearInterval(watch);
298
+ const off = unsubscribe?.value;
299
+ if (unsubscribe) try {
300
+ if (typeof off !== "function") return fail("the unsubscribe function");
301
+ off();
302
+ } catch (error) {
303
+ this.failed({
304
+ member: "unsubscribe",
305
+ error
306
+ });
307
+ }
308
+ };
309
+ if (!this.connected()) return finish("detached");
310
+ timer = setTimeout(() => finish("timeout"), timeout);
311
+ watch = setInterval(() => {
312
+ if (!this.connected()) finish("detached");
313
+ }, DETACH_CHECK_MS);
314
+ unsubscribe = this.use("subscribeEvent", (api) => api.subscribeEvent(event, () => {
315
+ if (done) return;
316
+ if (!this.connected()) return finish("detached");
317
+ const stop = onEvent();
318
+ if (stop === void 0) finish("failed");
319
+ else if (stop) finish("event");
320
+ }));
321
+ subscribed = unsubscribe !== void 0;
322
+ if (!unsubscribe) finish(this.connected() ? "failed" : "detached");
323
+ });
324
+ return Object.assign(settled, {
325
+ cancel: () => finish("failed"),
326
+ subscribed
327
+ });
328
+ }
329
+ };
3
330
  // src/grid.ts
4
331
  /** Generated grouping columns, as exported by the grid (`GRID_ROW_GROUPING_SINGLE_GROUPING_FIELD`). */
5
332
  const SINGLE_GROUPING_FIELD = "__row_group_by_columns_group__";
6
333
  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
- }
334
+ /** The grid release this helper release is tested with. */
335
+ const TESTED_GRID = "@mui/x-data-grid-premium 9.18.0";
336
+ /** Printed once per resolver, followed by what was thrown, when part of the grid failed. */
337
+ const gridWarning = (members) => `@gridsay/mui-x-data-grid: part of the grid could not be read or changed (${[...new Set(members)].join(", ")}). This helper is tested with ${TESTED_GRID}: the grid may be a version it was not tested with, or a callback of yours threw (what was thrown follows). The helper does not guess: until a helper release names your grid version as tested, it leaves that part out of what it sends and skips its own steps that depend on it (for the grid's settings or pivot mode: moving a grouped column's sort to the grouping column, selecting the top rows, keeping a chart's aggregation). Questions still go ahead, and the grid applies each answer as it does by default.`;
26
338
  const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
27
339
  /** Sorting a grouped column must target the grouping column, or group headers keep their order. */
28
340
  function sortGroups(data, multiple) {
@@ -39,103 +351,131 @@ function sortGroups(data, multiple) {
39
351
  }];
40
352
  });
41
353
  }
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
- });
354
+ /**
355
+ * Leaves pivot mode and waits for the grid to restore its rows. True only once the grid is seen
356
+ * out of pivot mode: the steps after it assume that.
357
+ */
358
+ async function leavePivot(grid) {
359
+ const restored = grid.wait("rowsSet", 1e3);
360
+ if (!restored.subscribed) return false;
361
+ if (!grid.leavePivot() && grid.pivotActive() !== false) {
362
+ restored.cancel();
363
+ return false;
364
+ }
365
+ const result = await restored;
366
+ if (result === "failed" || result === "detached") return false;
367
+ await tick();
368
+ return grid.connected() && grid.pivotActive() === false;
48
369
  }
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
- });
370
+ /** Selects the top rows once they are this answer's: never rows of a page still loading. */
371
+ async function selectWhenLoaded(grid, top, dataSource) {
372
+ if (dataSource) {
373
+ await tick();
374
+ if (!grid.connected()) return;
375
+ const loading = grid.rowsLoading();
376
+ if (loading === void 0) return;
377
+ if (loading) {
378
+ if (await grid.wait("rowsSet", 15e3) !== "event") return;
379
+ await tick();
380
+ if (!grid.connected() || grid.rowsLoading() !== false) return;
381
+ }
382
+ }
383
+ if (grid.connected()) grid.selectTop(top);
59
384
  }
60
385
  const sameAggregation = (a, b) => Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((k) => a[k] === b[k]);
61
386
  /** 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);
71
- });
72
- }
387
+ const keepAggregation = (grid, aggregation) => grid.wait("aggregationModelChange", 500, () => {
388
+ const model = grid.aggregationModel();
389
+ if (!model) return void 0;
390
+ if (!sameAggregation(model, aggregation) && !grid.setAggregation(aggregation)) return void 0;
391
+ return false;
392
+ });
73
393
  /**
74
394
  * Prepares a checked answer for the grid. `response` goes back to the grid, which applies it
75
395
  * synchronously; `applied` settles once the helper has finished its own changes after that.
396
+ * Each step runs only on what the steps before it confirmed; the rest is left to the grid.
76
397
  */
77
- async function adapt(api, data) {
78
- const on = readSwitches(api);
79
- const pivots = on.pivoting && "columns" in data.pivoting;
398
+ async function adapt(grid, data) {
399
+ const asItIs = {
400
+ response: data,
401
+ applied: Promise.resolve()
402
+ };
403
+ if (!grid.connected()) return asItIs;
404
+ const on = grid.switches();
405
+ const pivots = (on ? on.pivoting : true) && "columns" in data.pivoting;
406
+ let layoutKnown = true;
407
+ if (!pivots) {
408
+ const active = grid.pivotActive();
409
+ layoutKnown = active === false || active === true && await leavePivot(grid);
410
+ if (!grid.connected()) return asItIs;
411
+ }
80
412
  const response = {
81
413
  ...data,
82
414
  select: -1
83
415
  };
416
+ if (!on || !layoutKnown) return {
417
+ response,
418
+ applied: Promise.resolve()
419
+ };
84
420
  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
421
  const top = on.selection && data.select > 0 ? data.select : 0;
92
- const charted = data.chart && !pivots && on.aggregation && api.state.chartsIntegration.activeChartId;
422
+ const charted = data.chart && !pivots && on.aggregation && grid.activeChart();
93
423
  return {
94
424
  response,
95
425
  applied: (async () => {
96
- const kept = charted ? keepAggregation(api, data.aggregation) : void 0;
426
+ const kept = charted ? keepAggregation(grid, data.aggregation) : void 0;
97
427
  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
- }
428
+ if (top > 0 && grid.connected()) await selectWhenLoaded(grid, top, on.dataSource);
108
429
  await kept;
109
430
  })()
110
431
  };
111
432
  }
112
433
  // src/queue.ts
113
- const finish = (api, data) => api ? adapt(api, data) : {
114
- response: data,
115
- applied: Promise.resolve()
434
+ /** The answer for the grid, adapted when there is a grid to adapt it to. */
435
+ async function finish(grid, data) {
436
+ return grid ? adapt(grid, data) : {
437
+ response: data,
438
+ applied: Promise.resolve()
439
+ };
440
+ }
441
+ /**
442
+ * The one bound on the line: a question waits at most this long for the one before it on the same
443
+ * grid, then is sent anyway. The request itself, like MUI's own resolver's, has no time limit.
444
+ */
445
+ const QUEUE_WAIT_MS = 6e4;
446
+ /** `promise`, or nothing once `ms` have passed; the timer never outlives it. */
447
+ function atMost(promise, ms) {
448
+ let timer;
449
+ const elapsed = new Promise((resolve) => {
450
+ timer = setTimeout(resolve, ms);
451
+ });
452
+ return Promise.race([promise, elapsed]).finally(() => clearTimeout(timer));
453
+ }
454
+ /**
455
+ * One line per grid API instance, shared by every resolver created for that grid (the README's
456
+ * `useMemo` makes a new one when `apiRef` changes), kept weakly: a grid that is gone takes its line.
457
+ */
458
+ const lines = /* @__PURE__ */ new WeakMap();
459
+ const lineOf = (api) => {
460
+ let line = lines.get(api);
461
+ if (!line) {
462
+ line = { queue: Promise.resolve() };
463
+ lines.set(api, line);
464
+ }
465
+ return line;
116
466
  };
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;
467
+ /**
468
+ * One prompt at a time per grid, so a follow-up is sent after the previous answer is on it. Each
469
+ * question carries exactly the conversation id the grid gave it, as with MUI's own resolver.
470
+ */
471
+ function oneAtATime(send, grid) {
472
+ const unbound = { queue: Promise.resolve() };
121
473
  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);
474
+ const api = grid();
475
+ const own = api ? lineOf(api) : unbound;
476
+ const weak = api ? new WeakRef(api) : null;
477
+ const result = atMost(own.queue, QUEUE_WAIT_MS).then(() => send(query, context, conversationId, weak));
478
+ own.queue = result.then((sent) => sent.applied).catch(() => void 0);
139
479
  return result.then((sent) => sent.response);
140
480
  };
141
481
  }
@@ -148,28 +488,62 @@ const FUNCTIONS = [
148
488
  "size"
149
489
  ];
150
490
  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;
491
+ const PIVOT_SEPARATOR = ">->";
492
+ /** A column the grid generated, or one named after cell values: never written into the description. */
493
+ const isGenerated = (field) => field.startsWith("__") && field.endsWith("__") || field.includes(PIVOT_SEPARATOR);
494
+ const OPTIONS = 500;
495
+ const AGGREGATION_FUNCTIONS = 32;
496
+ const OPERATORS = 64;
497
+ /**
498
+ * One read of a property of something the app gave, with the grid checked just before it: nothing
499
+ * the app holds is read once the grid has left the document.
500
+ */
501
+ function at(grid, object, key) {
502
+ grid.still();
503
+ return object[key];
504
+ }
505
+ /** At most `limit` elements of an array, each read once by index: no iterator, nothing past the limit. */
506
+ function firstOf(grid, given, limit) {
507
+ if (!Array.isArray(given)) return [];
508
+ const length = Math.min(Number(at(grid, given, "length")) || 0, limit);
509
+ const copy = [];
510
+ for (let i = 0; i < length; i++) copy.push(at(grid, given, i));
511
+ return copy;
512
+ }
513
+ /** Calls one of the app's column functions as MUI does: as the column's method. */
514
+ function call(grid, fn, column, argument) {
515
+ grid.still();
516
+ return fn.call(column, argument);
517
+ }
518
+ /**
519
+ * A select column's options, read as MUI reads them: `valueOptions` called as the column's method
520
+ * with `{ field }`, then the column's `getOptionValue` and `getOptionLabel` as its methods, once
521
+ * per option, for at most the first 500 options. Without them, MUI's defaults for the type.
522
+ */
523
+ function readOptions(grid, column, field) {
524
+ const valueOptions = at(grid, column, "valueOptions");
525
+ const getValue = at(grid, column, "getOptionValue");
526
+ const getLabel = at(grid, column, "getOptionLabel");
527
+ const given = typeof valueOptions === "function" ? call(grid, valueOptions, column, { field }) : valueOptions;
528
+ const options = [];
529
+ for (const option of firstOf(grid, given, OPTIONS)) {
530
+ const object = isRecord(option);
531
+ const value = typeof getValue === "function" ? call(grid, getValue, column, option) : object ? at(grid, option, "value") : option;
532
+ const label = typeof getLabel === "function" ? call(grid, getLabel, column, option) : object ? at(grid, option, "label") : String(option);
163
533
  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 [{
534
+ if (typeof text !== "string" || text.length > 255) continue;
535
+ if (typeof value === "number" || typeof value === "string" && value.length <= 255) options.push({
166
536
  value,
167
537
  label: text
168
- }];
169
- return [];
170
- }).slice(0, 500);
538
+ });
539
+ }
540
+ return options;
171
541
  }
172
- function readLimits(column) {
542
+ /** Copies what the description needs from one column, reading each property once. */
543
+ function copyColumn(grid, column) {
544
+ const field = at(grid, column, "field");
545
+ if (typeof field !== "string" || isGenerated(field) || field.length > 255) return void 0;
546
+ const type = at(grid, column, "type");
173
547
  const limits = {};
174
548
  for (const flag of [
175
549
  "filterable",
@@ -177,24 +551,84 @@ function readLimits(column) {
177
551
  "groupable",
178
552
  "pivotable",
179
553
  "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;
554
+ ]) if (at(grid, column, flag) === false) limits[flag] = false;
555
+ const available = at(grid, column, "availableAggregationFunctions");
556
+ if (Array.isArray(available)) limits.aggregationFunctions = firstOf(grid, available, AGGREGATION_FUNCTIONS).filter((fn) => typeof fn === "string" && fn.length <= 64);
557
+ if (type === "singleSelect" || type === "multiSelect") {
558
+ const options = readOptions(grid, column, field);
559
+ if (options.length > 0) limits.options = options;
560
+ }
561
+ return {
562
+ field,
563
+ limits,
564
+ operators: firstOf(grid, at(grid, column, "filterOperators"), OPERATORS).map((operator) => isRecord(operator) ? {
565
+ value: at(grid, operator, "value"),
566
+ requiresFilterValue: at(grid, operator, "requiresFilterValue")
567
+ } : {
568
+ value: void 0,
569
+ requiresFilterValue: void 0
570
+ })
571
+ };
572
+ }
573
+ /**
574
+ * MUI's column context with each option list cut to its first 500 options, each to its value and
575
+ * label: what else an app or `getPivotDerivedColumns` attaches to an option stays in the browser.
576
+ * A context with no option list goes exactly as the grid built it.
577
+ */
578
+ function boundedContext(context) {
579
+ let columns;
580
+ try {
581
+ columns = JSON.parse(context);
582
+ } catch {
583
+ return context;
584
+ }
585
+ if (!Array.isArray(columns) || !columns.some((c) => isRecord(c) && "valueOptions" in c)) return context;
586
+ return JSON.stringify(columns.map((column) => {
587
+ if (!isRecord(column) || !("valueOptions" in column)) return column;
588
+ const { valueOptions, ...rest } = column;
589
+ if (!Array.isArray(valueOptions)) return rest;
590
+ const options = valueOptions.slice(0, OPTIONS).flatMap((option) => {
591
+ const plain = (value) => [
592
+ "string",
593
+ "number",
594
+ "boolean"
595
+ ].includes(typeof value);
596
+ if (!isRecord(option)) return plain(option) ? [option] : [];
597
+ const { value, label } = option;
598
+ return plain(value) && (label === void 0 || plain(label)) ? [{
599
+ value,
600
+ label
601
+ }] : [];
602
+ });
603
+ return {
604
+ ...rest,
605
+ valueOptions: options
606
+ };
607
+ }));
186
608
  }
187
609
  function toFilterValue(value) {
188
610
  if (typeof value === "string" || typeof value === "boolean") return value;
189
611
  if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
190
612
  if (value instanceof Date) return Number.isNaN(value.getTime()) ? void 0 : value.toISOString();
191
613
  if (!Array.isArray(value)) return void 0;
192
- if (value.every((item) => typeof item === "number")) return value;
193
- return value.map(String);
614
+ const items = Array.from({ length: value.length }, (_, i) => value[i]);
615
+ if (items.every((item) => typeof item === "number")) return items;
616
+ const texts = items.map(toText);
617
+ return texts.every((text) => text !== void 0) ? texts : void 0;
194
618
  }
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;
619
+ /** An element of a filter value as text, or undefined unless it is text, a number, a boolean or a date. */
620
+ function toText(value) {
621
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? void 0 : value.toISOString();
622
+ return [
623
+ "string",
624
+ "number",
625
+ "boolean"
626
+ ].includes(typeof value) ? String(value) : void 0;
627
+ }
628
+ function readFilters(items, operators) {
629
+ return items.flatMap((item) => {
630
+ if (isGenerated(item.field)) return [];
631
+ const valueless = operators.get(item.field)?.find((o) => o.value === item.operator)?.requiresFilterValue === false;
198
632
  const value = valueless ? "" : toFilterValue(item.value);
199
633
  if (value === void 0 || !valueless && (value === "" || Array.isArray(value) && !value.length)) return [];
200
634
  return [{
@@ -204,14 +638,25 @@ function readFilters(api, columns) {
204
638
  }];
205
639
  });
206
640
  }
207
- function readState(api, columns) {
208
- const { filter, sorting, rowGrouping, aggregation, pivoting } = api.state;
641
+ /**
642
+ * The grid's current view, or undefined when part of it cannot be read: a partial state would
643
+ * tell the server the missing part is empty, so it is left out whole.
644
+ */
645
+ function readState(grid, operators) {
646
+ const filter = grid.filterModel();
647
+ const sortModel = grid.sortModel();
648
+ const rowGrouping = grid.rowGroupingModel();
649
+ const aggregation = grid.aggregationModel();
650
+ const active = grid.pivotActive();
651
+ const model = active ? grid.pivotModel() : void 0;
652
+ if (!filter || !sortModel || !rowGrouping || !aggregation || active === void 0) return void 0;
653
+ if (active && !model) return void 0;
209
654
  const state = {};
210
- const filters = readFilters(api, columns);
655
+ const filters = grid.column(() => readFilters(filter.items, operators));
211
656
  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) => {
657
+ if (filters.length > 1 && filter.or) state.filterOperator = "or";
658
+ const grouping = active ? [] : rowGrouping.filter((field) => !isGenerated(field));
659
+ const sorts = sortModel.flatMap((item) => {
215
660
  const column = item.field === "__row_group_by_columns_group__" ? grouping[0] : item.field.replace(/^__row_group_by_columns_group_(.+)__$/, "$1");
216
661
  return item.sort && column && !isGenerated(column) ? [{
217
662
  column,
@@ -219,78 +664,170 @@ function readState(api, columns) {
219
664
  }] : [];
220
665
  });
221
666
  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
- };
667
+ if (model) {
668
+ state.pivoting = readPivot(model);
232
669
  return state;
233
670
  }
234
671
  if (grouping.length > 0) state.grouping = grouping.map((column) => ({ column }));
235
- const functions = Object.entries(aggregation.model).flatMap(([field, fn]) => isFunction(fn) ? [[field, fn]] : []);
672
+ const functions = Object.entries(aggregation).flatMap(([field, fn]) => isFunction(fn) && !isGenerated(field) ? [[field, fn]] : []);
236
673
  if (functions.length > 0) state.aggregation = Object.fromEntries(functions);
237
674
  return state;
238
675
  }
239
- /** What the grid allows and shows, leaving out everything at its default. */
240
- function readSnapshot(api) {
241
- const on = readSwitches(api);
676
+ function readPivot(model) {
677
+ return {
678
+ columns: model.columns.filter((c) => !c.hidden && !isGenerated(c.field)).map((c) => ({
679
+ column: c.field,
680
+ direction: c.sort ?? "asc"
681
+ })),
682
+ rows: model.rows.filter((r) => !r.hidden && !isGenerated(r.field)).map((r) => r.field),
683
+ values: model.values.flatMap((v) => !v.hidden && !isGenerated(v.field) && isFunction(v.aggFunc) ? [{ [v.field]: v.aggFunc }] : [])
684
+ };
685
+ }
686
+ function switchedOff(on) {
687
+ const off = [];
688
+ if (!on.filtering) off.push("filtering");
689
+ if (!on.sorting) off.push("sorting");
690
+ if (!on.grouping) off.push("grouping");
691
+ if (!on.aggregation) off.push("aggregation");
692
+ if (!on.pivoting) off.push("pivoting");
693
+ if (!on.selection) off.push("selection");
694
+ return off;
695
+ }
696
+ /**
697
+ * What the grid allows and shows, from its columns, leaving out everything at its default and
698
+ * whatever of the grid's own state cannot be read.
699
+ */
700
+ function readSnapshot(grid, allColumns, on) {
242
701
  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);
702
+ if (on) disabled.push(...switchedOff(on));
703
+ if (grid.activeChart() === "") disabled.push("charts");
704
+ const copied = grid.column(() => {
705
+ return firstOf(grid, allColumns, Number.POSITIVE_INFINITY).flatMap((column) => copyColumn(grid, column) ?? []);
706
+ });
251
707
  const columns = {};
252
- for (const column of all) {
253
- const limits = readLimits(column);
254
- if (Object.keys(limits).length > 0) columns[column.field] = limits;
255
- }
256
- const state = readState(api, new Map(all.map((c) => [c.field, c])));
708
+ for (const { field, limits } of copied) if (Object.keys(limits).length > 0) columns[field] = limits;
709
+ const state = readState(grid, new Map(copied.map((c) => [c.field, c.operators])));
257
710
  const snapshot = {};
258
711
  if (disabled.length > 0) snapshot.disabled = disabled;
259
712
  if (Object.keys(columns).length > 0) snapshot.columns = columns;
260
- snapshot.state = state;
713
+ if (state) snapshot.state = state;
261
714
  return snapshot;
262
715
  }
263
716
  // src/index.ts
717
+ const CONNECTION_FAILED = core.CONNECTION_FAILED;
718
+ const INVALID_ANSWER = core.INVALID_ANSWER;
719
+ const NOT_JSON = core.NOT_JSON;
720
+ const UNAUTHENTICATED_USER = core.UNAUTHENTICATED_USER;
721
+ function hold(member, error) {
722
+ let text;
723
+ try {
724
+ text = error instanceof Error ? `${error.name}: ${error.message}\n${error.stack ?? ""}` : String(error);
725
+ } catch {
726
+ text = "An error that could not be read.";
727
+ }
728
+ return {
729
+ member,
730
+ error: typeof error === "object" && error !== null ? new WeakRef(error) : void 0,
731
+ text
732
+ };
733
+ }
734
+ const thrownOf = (held) => held.error?.deref() ?? held.text;
735
+ /** These options admit an explicit `undefined`; core's, as published, do not: such entries go. */
736
+ function requestOptionsOf(options) {
737
+ const result = {};
738
+ for (const [key, value] of Object.entries(options)) if (value !== void 0) Object.assign(result, { [key]: value });
739
+ return result;
740
+ }
264
741
  /** Replaces `unstable_gridDefaultPromptResolver` as the grid's `onPrompt`. */
265
742
  function createPromptResolver(options) {
266
743
  const { url, apiRef } = options;
267
- const promptOptions = promptOptionsOf(options);
268
- async function send(query, context, conversationId) {
269
- const api = apiRef?.current ?? null;
744
+ const requestOptions = requestOptionsOf(options);
745
+ const promptOptions = promptOptionsOf(requestOptions);
746
+ let holder;
747
+ const owner = /* @__PURE__ */ new Map();
748
+ async function send(query, context, conversationId, api) {
749
+ const failures = [];
750
+ const flush = () => {
751
+ const mine = failures.filter((f) => owner.get(f.member) === failures);
752
+ if (mine.length === 0) return;
753
+ if (holder === failures) {
754
+ console.warn(gridWarning(mine.map((f) => f.member)), ...mine.map(thrownOf));
755
+ return;
756
+ }
757
+ const printed = /* @__PURE__ */ new Set();
758
+ for (const held of mine) {
759
+ const { member } = held;
760
+ if (printed.has(member)) continue;
761
+ printed.add(member);
762
+ console.warn(`@gridsay/mui-x-data-grid: ${member} could not be read or changed; skipped.`, thrownOf(held));
763
+ }
764
+ };
765
+ /** Logs, then lets go of what was thrown: an error can hold on to a grid that is gone. */
766
+ const report = () => {
767
+ flush();
768
+ failures.length = 0;
769
+ };
770
+ const grid = api ? new Grid(api, (caught) => {
771
+ const failure = hold(caught.member, caught.error);
772
+ failures.push(failure);
773
+ if (!owner.has(failure.member)) owner.set(failure.member, failures);
774
+ holder ??= failures;
775
+ }) : null;
776
+ try {
777
+ const sent = await ask(grid, query, context, conversationId);
778
+ return {
779
+ ...sent,
780
+ applied: sent.applied.finally(report)
781
+ };
782
+ } catch (error) {
783
+ report();
784
+ if (error instanceof GridsayError$1) throw error;
785
+ throw new GridsayError$1(INVALID_ANSWER, {
786
+ code: UNEXPECTED_ERROR_CODE$1,
787
+ cause: error
788
+ });
789
+ }
790
+ }
791
+ async function ask(grid, query, context, conversationId) {
792
+ const headers = await requestHeaders(requestOptions);
270
793
  const body = {
271
- context,
794
+ context: boundedContext(context),
272
795
  query,
273
- conversationId,
274
796
  options: promptOptions
275
797
  };
276
- if (api) body.grid = readSnapshot(api);
798
+ if (conversationId !== void 0) body.conversationId = conversationId;
799
+ if (grid?.connected()) try {
800
+ const described = readSnapshot(grid, grid.columns(), grid.switches());
801
+ if (!grid.detached && grid.connected()) body.grid = described;
802
+ } catch (error) {
803
+ grid.undescribed(error);
804
+ }
277
805
  const init = {
278
806
  method: "POST",
279
- headers: await requestHeaders(options),
807
+ headers,
280
808
  body: JSON.stringify(body)
281
809
  };
282
810
  let response;
283
811
  try {
284
812
  response = await fetch(url, init);
285
813
  } catch (cause) {
286
- throw new GridsayError$1(CONNECTION_FAILED$1, {
814
+ throw new GridsayError$1(CONNECTION_FAILED, {
287
815
  code: CONNECTION_FAILED_CODE$1,
288
816
  cause
289
817
  });
290
818
  }
291
- const data = await readResponse(response);
292
- return finish(api, data);
819
+ return finish(grid, await readResponse(response));
293
820
  }
294
- return oneAtATime(send);
821
+ let unreadable = false;
822
+ const gridOf = () => {
823
+ try {
824
+ return apiRef?.current ?? null;
825
+ } catch (error) {
826
+ if (!unreadable) console.warn(gridWarning(["apiRef.current"]), error);
827
+ unreadable = true;
828
+ return null;
829
+ }
830
+ };
831
+ return oneAtATime(send, gridOf);
295
832
  }
296
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 };