@gridsay/tanstack-table 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +320 -2
- package/dist/index-yyGT4N9i.d.ts +180 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/react.d.ts +32 -0
- package/dist/react.js +56 -0
- package/dist/src-D4dDBjRk.js +890 -0
- package/package.json +66 -3
|
@@ -0,0 +1,890 @@
|
|
|
1
|
+
import { CANNOT_APPLY_CODE, CANNOT_APPLY_CODE as CANNOT_APPLY_CODE$1, 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 as INVALID_ANSWER$1, INVALID_ANSWER_CODE, NOT_JSON, NOT_JSON_CODE, UNAUTHENTICATED_USER, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE, UNEXPECTED_ERROR_CODE as UNEXPECTED_ERROR_CODE$1 } from "@gridsay/core";
|
|
2
|
+
import { isRecord, promptOptionsOf, readResponse, requestHeaders } from "@gridsay/core/internal";
|
|
3
|
+
import { constructRow, tableMemo } from "@tanstack/table-core";
|
|
4
|
+
// src/filter.ts
|
|
5
|
+
const COLUMN_TYPES = [
|
|
6
|
+
"string",
|
|
7
|
+
"number",
|
|
8
|
+
"date",
|
|
9
|
+
"dateTime",
|
|
10
|
+
"boolean",
|
|
11
|
+
"singleSelect"
|
|
12
|
+
];
|
|
13
|
+
const DATE_OPERATORS = [
|
|
14
|
+
"is",
|
|
15
|
+
"not",
|
|
16
|
+
"after",
|
|
17
|
+
"onOrAfter",
|
|
18
|
+
"before",
|
|
19
|
+
"onOrBefore"
|
|
20
|
+
];
|
|
21
|
+
const OPERATORS = {
|
|
22
|
+
string: [
|
|
23
|
+
"contains",
|
|
24
|
+
"doesNotContain",
|
|
25
|
+
"equals",
|
|
26
|
+
"doesNotEqual",
|
|
27
|
+
"startsWith",
|
|
28
|
+
"endsWith",
|
|
29
|
+
"isEmpty",
|
|
30
|
+
"isNotEmpty",
|
|
31
|
+
"isAnyOf"
|
|
32
|
+
],
|
|
33
|
+
number: [
|
|
34
|
+
"=",
|
|
35
|
+
"!=",
|
|
36
|
+
">",
|
|
37
|
+
">=",
|
|
38
|
+
"<",
|
|
39
|
+
"<=",
|
|
40
|
+
"isEmpty",
|
|
41
|
+
"isNotEmpty",
|
|
42
|
+
"isAnyOf"
|
|
43
|
+
],
|
|
44
|
+
date: [
|
|
45
|
+
...DATE_OPERATORS,
|
|
46
|
+
"isEmpty",
|
|
47
|
+
"isNotEmpty"
|
|
48
|
+
],
|
|
49
|
+
dateTime: [
|
|
50
|
+
...DATE_OPERATORS,
|
|
51
|
+
"isEmpty",
|
|
52
|
+
"isNotEmpty"
|
|
53
|
+
],
|
|
54
|
+
boolean: ["is"],
|
|
55
|
+
singleSelect: [
|
|
56
|
+
"is",
|
|
57
|
+
"not",
|
|
58
|
+
"isAnyOf"
|
|
59
|
+
]
|
|
60
|
+
};
|
|
61
|
+
const isColumnType = (value) => COLUMN_TYPES.some((type) => type === value);
|
|
62
|
+
const isAssistantFilterValue = (value) => isRecord(value) && (value.logic === "and" || value.logic === "or") && Array.isArray(value.filters) && value.filters.every((filter) => isRecord(filter) && typeof filter.column === "string" && typeof filter.operator === "string" && isColumnType(filter.type));
|
|
63
|
+
const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
64
|
+
const collator$1 = new Intl.Collator(void 0, {
|
|
65
|
+
sensitivity: "base",
|
|
66
|
+
usage: "search"
|
|
67
|
+
});
|
|
68
|
+
const text = (value) => {
|
|
69
|
+
if (typeof value !== "string") throw new Error("Expected text");
|
|
70
|
+
return value.trim();
|
|
71
|
+
};
|
|
72
|
+
function stringTest(operator, value) {
|
|
73
|
+
if (operator === "isEmpty") return (cell) => cell === "" || cell == null;
|
|
74
|
+
if (operator === "isNotEmpty") return (cell) => !(cell === "" || cell == null);
|
|
75
|
+
if (operator === "isAnyOf") {
|
|
76
|
+
if (!Array.isArray(value) || value.length === 0) return null;
|
|
77
|
+
const wanted = value.map(text);
|
|
78
|
+
return (cell) => cell != null && wanted.some((item) => collator$1.compare(item, String(cell)) === 0);
|
|
79
|
+
}
|
|
80
|
+
if (!value) return null;
|
|
81
|
+
const wanted = text(value);
|
|
82
|
+
const negate = operator === "doesNotContain" || operator === "doesNotEqual";
|
|
83
|
+
switch (operator) {
|
|
84
|
+
case "contains":
|
|
85
|
+
case "doesNotContain": {
|
|
86
|
+
const pattern = new RegExp(escapeRegExp(wanted), "i");
|
|
87
|
+
return (cell) => cell == null ? negate : pattern.test(String(cell)) !== negate;
|
|
88
|
+
}
|
|
89
|
+
case "equals":
|
|
90
|
+
case "doesNotEqual": return (cell) => cell == null ? negate : collator$1.compare(wanted, String(cell)) === 0 !== negate;
|
|
91
|
+
case "startsWith":
|
|
92
|
+
case "endsWith": {
|
|
93
|
+
const source = operator === "startsWith" ? `^${escapeRegExp(wanted)}` : `${escapeRegExp(wanted)}$`;
|
|
94
|
+
const pattern = new RegExp(source, "i");
|
|
95
|
+
return (cell) => cell != null && pattern.test(String(cell));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
throw new Error(`Unknown operator ${operator}`);
|
|
99
|
+
}
|
|
100
|
+
const parseNumber = (value) => value === "" || value == null ? null : Number(value);
|
|
101
|
+
const cellNumber = (cell) => cell == null ? null : Number(cell);
|
|
102
|
+
function numberTest(operator, raw) {
|
|
103
|
+
if (operator === "isEmpty") return (cell) => cell == null;
|
|
104
|
+
if (operator === "isNotEmpty") return (cell) => cell != null;
|
|
105
|
+
const value = Array.isArray(raw) ? raw.map(parseNumber) : parseNumber(raw);
|
|
106
|
+
if (operator === "isAnyOf") {
|
|
107
|
+
if (!Array.isArray(value) || value.length === 0) return null;
|
|
108
|
+
return (cell) => cell != null && value.includes(Number(cell));
|
|
109
|
+
}
|
|
110
|
+
if (value == null || Number.isNaN(value)) return null;
|
|
111
|
+
const bound = Number(value);
|
|
112
|
+
switch (operator) {
|
|
113
|
+
case "=": return (cell) => cellNumber(cell) === value;
|
|
114
|
+
case "!=": return (cell) => cellNumber(cell) !== value;
|
|
115
|
+
case ">": return (cell) => cell != null && Number(cell) > bound;
|
|
116
|
+
case ">=": return (cell) => cell != null && Number(cell) >= bound;
|
|
117
|
+
case "<": return (cell) => cell != null && Number(cell) < bound;
|
|
118
|
+
case "<=": return (cell) => cell != null && Number(cell) <= bound;
|
|
119
|
+
}
|
|
120
|
+
throw new Error(`Unknown operator ${operator}`);
|
|
121
|
+
}
|
|
122
|
+
const DATE_ONLY$1 = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
123
|
+
/** A cell as a date. A `YYYY-MM-DD` string is that day in local time, the day the cell shows. */
|
|
124
|
+
function cellDate(cell) {
|
|
125
|
+
if (cell instanceof Date) return new Date(cell.getTime());
|
|
126
|
+
if (typeof cell === "string") {
|
|
127
|
+
const day = DATE_ONLY$1.exec(cell);
|
|
128
|
+
if (day) return new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3]));
|
|
129
|
+
return new Date(cell);
|
|
130
|
+
}
|
|
131
|
+
return new Date(typeof cell === "number" ? cell : NaN);
|
|
132
|
+
}
|
|
133
|
+
const COMPARE = {
|
|
134
|
+
is: (cell, bound) => cell === bound,
|
|
135
|
+
not: (cell, bound) => cell !== bound,
|
|
136
|
+
after: (cell, bound) => cell > bound,
|
|
137
|
+
onOrAfter: (cell, bound) => cell >= bound,
|
|
138
|
+
before: (cell, bound) => cell < bound,
|
|
139
|
+
onOrBefore: (cell, bound) => cell <= bound
|
|
140
|
+
};
|
|
141
|
+
function dateTest(operator, value, withTime) {
|
|
142
|
+
if (operator === "isEmpty") return (cell) => cell == null;
|
|
143
|
+
if (operator === "isNotEmpty") return (cell) => cell != null;
|
|
144
|
+
const compare = COMPARE[operator];
|
|
145
|
+
if (!compare) throw new Error(`Unknown operator ${operator}`);
|
|
146
|
+
if (!value) return null;
|
|
147
|
+
const bound = new Date(typeof value === "string" || typeof value === "number" ? value : typeof value === "boolean" ? Number(value) : String(value));
|
|
148
|
+
if (withTime) bound.setSeconds(0, 0);
|
|
149
|
+
else {
|
|
150
|
+
bound.setMinutes(bound.getMinutes() + bound.getTimezoneOffset());
|
|
151
|
+
bound.setHours(0, 0, 0, 0);
|
|
152
|
+
}
|
|
153
|
+
const time = bound.getTime();
|
|
154
|
+
const truncate = operator === "is" || operator === "not" || !withTime && operator !== "before";
|
|
155
|
+
return (cell) => {
|
|
156
|
+
if (!cell) return false;
|
|
157
|
+
const date = cellDate(cell);
|
|
158
|
+
if (truncate) {
|
|
159
|
+
if (withTime) date.setSeconds(0, 0);
|
|
160
|
+
else date.setHours(0, 0, 0, 0);
|
|
161
|
+
}
|
|
162
|
+
return compare(date.getTime(), time);
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function booleanTest(operator, value) {
|
|
166
|
+
if (operator !== "is") throw new Error(`Unknown operator ${operator}`);
|
|
167
|
+
const wanted = String(value).toLowerCase();
|
|
168
|
+
if (wanted !== "true" && wanted !== "false") return null;
|
|
169
|
+
return (cell) => Boolean(cell) === (wanted === "true");
|
|
170
|
+
}
|
|
171
|
+
const optionValue = (value) => isRecord(value) ? value.value : value;
|
|
172
|
+
function singleSelectTest(operator, value) {
|
|
173
|
+
if (operator === "isAnyOf") {
|
|
174
|
+
if (!Array.isArray(value) || value.length === 0) return null;
|
|
175
|
+
const wanted = value.map(optionValue);
|
|
176
|
+
return (cell) => wanted.includes(optionValue(cell));
|
|
177
|
+
}
|
|
178
|
+
if (value == null || value === "") return null;
|
|
179
|
+
const wanted = optionValue(value);
|
|
180
|
+
if (operator === "is") return (cell) => optionValue(cell) === wanted;
|
|
181
|
+
if (operator === "not") return (cell) => optionValue(cell) !== wanted;
|
|
182
|
+
throw new Error(`Unknown operator ${operator}`);
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* The test one filter makes on a cell, as the MUI X Data Grid makes it. `null` when the grid
|
|
186
|
+
* would ignore the filter; throws when the grid could not apply it at all.
|
|
187
|
+
*/
|
|
188
|
+
function compileFilter(filter) {
|
|
189
|
+
const { operator, value, type } = filter;
|
|
190
|
+
if (!OPERATORS[type].includes(operator)) throw new Error(`Unknown operator ${operator}`);
|
|
191
|
+
switch (type) {
|
|
192
|
+
case "string": return stringTest(operator, value);
|
|
193
|
+
case "number": return numberTest(operator, value);
|
|
194
|
+
case "date":
|
|
195
|
+
case "dateTime": return dateTest(operator, value, type === "dateTime");
|
|
196
|
+
case "boolean": return booleanTest(operator, value);
|
|
197
|
+
case "singleSelect": return singleSelectTest(operator, value);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
function compile(value) {
|
|
201
|
+
try {
|
|
202
|
+
return {
|
|
203
|
+
logic: value.logic,
|
|
204
|
+
tests: value.filters.flatMap((filter) => {
|
|
205
|
+
const test = compileFilter(filter);
|
|
206
|
+
return test ? [{
|
|
207
|
+
column: filter.column,
|
|
208
|
+
test
|
|
209
|
+
}] : [];
|
|
210
|
+
})
|
|
211
|
+
};
|
|
212
|
+
} catch {
|
|
213
|
+
return {
|
|
214
|
+
logic: value.logic,
|
|
215
|
+
tests: []
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const isCompiled = (value) => isRecord(value) && Array.isArray(value.tests);
|
|
220
|
+
function run(row, { logic, tests }) {
|
|
221
|
+
if (tests.length === 0) return true;
|
|
222
|
+
const passes = ({ column, test }) => test(row.getValue(column));
|
|
223
|
+
return logic === "or" ? tests.some(passes) : tests.every(passes);
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* The plugin's filter function. Set it as `filterFn` on the columns the assistant may filter.
|
|
227
|
+
* It reads the plugin's own filter values and keeps every row for any other value.
|
|
228
|
+
*/
|
|
229
|
+
const assistantFilter = Object.assign((row, _columnId, filterValue) => {
|
|
230
|
+
if (isCompiled(filterValue)) return run(row, filterValue);
|
|
231
|
+
if (isAssistantFilterValue(filterValue)) return run(row, compile(filterValue));
|
|
232
|
+
return true;
|
|
233
|
+
}, { resolveFilterValue: (value) => isAssistantFilterValue(value) ? compile(value) : value });
|
|
234
|
+
// src/group.ts
|
|
235
|
+
const made = /* @__PURE__ */ new WeakSet();
|
|
236
|
+
/** True when the table forms its groups with `assistantGroupedRowModel`. */
|
|
237
|
+
const groupsLikeTheGrid = (features) => "groupedRowModel" in features && typeof features.groupedRowModel === "function" && made.has(features.groupedRowModel);
|
|
238
|
+
/** The grouping atom's value as it is, so that the memo sees when it changes. */
|
|
239
|
+
function groupingAtom(atoms) {
|
|
240
|
+
if (!("grouping" in atoms)) return void 0;
|
|
241
|
+
const atom = atoms.grouping;
|
|
242
|
+
if (typeof atom !== "object" || atom === null || !("get" in atom)) return void 0;
|
|
243
|
+
return typeof atom.get === "function" ? atom.get() : void 0;
|
|
244
|
+
}
|
|
245
|
+
const columnIds = (grouping) => Array.isArray(grouping) ? grouping.filter((id) => typeof id === "string") : [];
|
|
246
|
+
function resetRows(rows, depth, parentId) {
|
|
247
|
+
for (const row of rows) {
|
|
248
|
+
row.depth = depth;
|
|
249
|
+
row.parentId = parentId;
|
|
250
|
+
resetRows(row.subRows, depth + 1, row.id);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Forms groups as the MUI X Data Grid does: a row with no value for a grouping column skips that
|
|
255
|
+
* level, groups keep the order of the whole data whatever the filter, and at each level the rows
|
|
256
|
+
* come before the groups.
|
|
257
|
+
*/
|
|
258
|
+
function groupRows(table, grouping) {
|
|
259
|
+
const filtered = table.getPreGroupedRowModel();
|
|
260
|
+
const columns = grouping.filter((id) => table.getColumn(id));
|
|
261
|
+
if (filtered.rows.length === 0 || columns.length === 0) {
|
|
262
|
+
resetRows(filtered.rows, 0, void 0);
|
|
263
|
+
return filtered;
|
|
264
|
+
}
|
|
265
|
+
const kept = new Set(filtered.rows);
|
|
266
|
+
const root = {
|
|
267
|
+
column: "",
|
|
268
|
+
value: void 0,
|
|
269
|
+
first: 0,
|
|
270
|
+
members: [],
|
|
271
|
+
keys: /* @__PURE__ */ new Map(),
|
|
272
|
+
leaves: []
|
|
273
|
+
};
|
|
274
|
+
for (const row of table.getCoreRowModel().rows) {
|
|
275
|
+
const path = [];
|
|
276
|
+
let parent = root;
|
|
277
|
+
for (const column of columns) {
|
|
278
|
+
const value = row.getValue(column);
|
|
279
|
+
if (value == null) continue;
|
|
280
|
+
const key = `${column}:${String(value)}`;
|
|
281
|
+
let group = parent.keys.get(key);
|
|
282
|
+
if (!group) {
|
|
283
|
+
group = {
|
|
284
|
+
column,
|
|
285
|
+
value,
|
|
286
|
+
first: row.index,
|
|
287
|
+
members: [],
|
|
288
|
+
keys: /* @__PURE__ */ new Map(),
|
|
289
|
+
leaves: []
|
|
290
|
+
};
|
|
291
|
+
parent.keys.set(key, group);
|
|
292
|
+
parent.members.push({ group });
|
|
293
|
+
}
|
|
294
|
+
path.push(group);
|
|
295
|
+
parent = group;
|
|
296
|
+
}
|
|
297
|
+
if (!kept.has(row)) continue;
|
|
298
|
+
parent.members.push({ row });
|
|
299
|
+
for (const group of path) group.leaves.push(row);
|
|
300
|
+
}
|
|
301
|
+
const flatRows = [];
|
|
302
|
+
const rowsById = {};
|
|
303
|
+
const build = (parent, depth, parentId, values) => {
|
|
304
|
+
const rows = parent.members.flatMap((member) => "row" in member ? [member.row] : []);
|
|
305
|
+
const groups = parent.members.flatMap((member) => "group" in member && member.group.leaves.length > 0 ? [member.group] : []);
|
|
306
|
+
const shown = [];
|
|
307
|
+
for (const row of rows) {
|
|
308
|
+
row.depth = depth;
|
|
309
|
+
row.parentId = parentId;
|
|
310
|
+
resetRows(row.subRows, depth + 1, row.id);
|
|
311
|
+
flatRows.push(row);
|
|
312
|
+
rowsById[row.id] = row;
|
|
313
|
+
shown.push(row);
|
|
314
|
+
}
|
|
315
|
+
for (const group of groups) {
|
|
316
|
+
const id = `${parentId === void 0 ? "" : `${parentId}>`}${group.column}:${String(group.value)}`;
|
|
317
|
+
const first = group.leaves[0];
|
|
318
|
+
if (!first) continue;
|
|
319
|
+
const row = constructRow(table, id, first.original, group.first, depth, void 0, parentId);
|
|
320
|
+
flatRows.push(row);
|
|
321
|
+
rowsById[id] = row;
|
|
322
|
+
const own = new Map(values).set(group.column, group.value);
|
|
323
|
+
row.subRows = build(group, depth + 1, id, own);
|
|
324
|
+
const aggregates = /* @__PURE__ */ new Map();
|
|
325
|
+
Object.assign(row, {
|
|
326
|
+
groupingColumnId: group.column,
|
|
327
|
+
groupingValue: group.value,
|
|
328
|
+
leafRows: group.leaves,
|
|
329
|
+
getValue: (columnId) => {
|
|
330
|
+
if (own.has(columnId)) return own.get(columnId);
|
|
331
|
+
if (!aggregates.has(columnId)) {
|
|
332
|
+
const column = table.getColumn(columnId);
|
|
333
|
+
const value = column && "getAggregationValue" in column ? column.getAggregationValue({ rows: group.leaves }) : void 0;
|
|
334
|
+
aggregates.set(columnId, value);
|
|
335
|
+
}
|
|
336
|
+
return aggregates.get(columnId);
|
|
337
|
+
}
|
|
338
|
+
});
|
|
339
|
+
shown.push(row);
|
|
340
|
+
}
|
|
341
|
+
return shown;
|
|
342
|
+
};
|
|
343
|
+
return {
|
|
344
|
+
rows: build(root, 0, void 0, /* @__PURE__ */ new Map()),
|
|
345
|
+
flatRows,
|
|
346
|
+
rowsById
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Register in place of `createGroupedRowModel()` so that grouped rows match the MUI X Data Grid.
|
|
351
|
+
* The assistant groups only a table that has it.
|
|
352
|
+
*/
|
|
353
|
+
function assistantGroupedRowModel() {
|
|
354
|
+
const create = (table) => {
|
|
355
|
+
let previous;
|
|
356
|
+
return tableMemo({
|
|
357
|
+
feature: "columnGroupingFeature",
|
|
358
|
+
table,
|
|
359
|
+
fnName: "table.getGroupedRowModel",
|
|
360
|
+
memoDeps: () => [
|
|
361
|
+
groupingAtom(table.atoms),
|
|
362
|
+
table.getPreGroupedRowModel(),
|
|
363
|
+
table.getCoreRowModel(),
|
|
364
|
+
table.options.columns
|
|
365
|
+
],
|
|
366
|
+
fn: (grouping) => groupRows(table, columnIds(grouping)),
|
|
367
|
+
onAfterUpdate: () => {
|
|
368
|
+
const inputs = [groupingAtom(table.atoms), table.getPreGroupedRowModel()];
|
|
369
|
+
const changed = previous?.some((input, index) => input !== inputs[index]) ?? false;
|
|
370
|
+
previous = inputs;
|
|
371
|
+
if (!changed) return;
|
|
372
|
+
if ("autoResetExpanded" in table) table.autoResetExpanded();
|
|
373
|
+
if ("autoResetPageIndex" in table) table.autoResetPageIndex();
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
};
|
|
377
|
+
made.add(create);
|
|
378
|
+
return create;
|
|
379
|
+
}
|
|
380
|
+
// src/infer.ts
|
|
381
|
+
const SAMPLE = 100;
|
|
382
|
+
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
|
|
383
|
+
const DATE_TIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
|
|
384
|
+
const isMidnight = (date) => date.getHours() === 0 && date.getMinutes() === 0 && date.getSeconds() === 0 && date.getMilliseconds() === 0;
|
|
385
|
+
/** The type the values suggest: all numbers, all booleans, or all dates; text otherwise. */
|
|
386
|
+
function inferType(values) {
|
|
387
|
+
const present = values.filter((value) => value != null);
|
|
388
|
+
const all = (check) => present.length > 0 && present.every(check);
|
|
389
|
+
if (all((value) => typeof value === "number")) return "number";
|
|
390
|
+
if (all((value) => typeof value === "boolean")) return "boolean";
|
|
391
|
+
if (all((value) => value instanceof Date && !Number.isNaN(value.getTime()))) return all((value) => value instanceof Date && isMidnight(value)) ? "date" : "dateTime";
|
|
392
|
+
if (all((value) => typeof value === "string" && DATE_ONLY.test(value))) return "date";
|
|
393
|
+
if (all((value) => typeof value === "string" && (DATE_ONLY.test(value) || DATE_TIME.test(value)))) return "dateTime";
|
|
394
|
+
return "string";
|
|
395
|
+
}
|
|
396
|
+
function sample(column, rows) {
|
|
397
|
+
const values = [];
|
|
398
|
+
for (const row of rows.slice(0, SAMPLE)) values.push(row.getValue(column.id));
|
|
399
|
+
return values;
|
|
400
|
+
}
|
|
401
|
+
const metaOf = (column) => {
|
|
402
|
+
const meta = isRecord(column.columnDef.meta) ? column.columnDef.meta.assistant : void 0;
|
|
403
|
+
return isRecord(meta) ? meta : {};
|
|
404
|
+
};
|
|
405
|
+
/** The column's type: the one in `meta.assistant`, or else the one its first rows suggest. */
|
|
406
|
+
function columnType(column, rows) {
|
|
407
|
+
const { type } = metaOf(column);
|
|
408
|
+
return isColumnType(type) ? type : inferType(sample(column, rows));
|
|
409
|
+
}
|
|
410
|
+
// src/sort.ts
|
|
411
|
+
const collator = new Intl.Collator();
|
|
412
|
+
const types = /* @__PURE__ */ new WeakMap();
|
|
413
|
+
/** The column's type, worked out once per set of rows rather than once per comparison. */
|
|
414
|
+
function typeOf(row, columnId) {
|
|
415
|
+
const column = row.table.getColumn(columnId);
|
|
416
|
+
if (!column) return "string";
|
|
417
|
+
const rows = row.table.getCoreRowModel().flatRows;
|
|
418
|
+
const known = types.get(column);
|
|
419
|
+
if (known?.rows === rows) return known.type;
|
|
420
|
+
const type = columnType(column, rows);
|
|
421
|
+
types.set(column, {
|
|
422
|
+
rows,
|
|
423
|
+
type
|
|
424
|
+
});
|
|
425
|
+
return type;
|
|
426
|
+
}
|
|
427
|
+
/** Orders two cells as the MUI X Data Grid does: empty first, then by number, time or text. */
|
|
428
|
+
function compareCells(a, b, type) {
|
|
429
|
+
if (a == null) return b == null ? 0 : -1;
|
|
430
|
+
if (b == null) return 1;
|
|
431
|
+
let difference;
|
|
432
|
+
if (type === "number" || type === "boolean") difference = Number(a) - Number(b);
|
|
433
|
+
else if (type === "date" || type === "dateTime") difference = cellDate(a).getTime() - cellDate(b).getTime();
|
|
434
|
+
else difference = collator.compare(String(a), String(b));
|
|
435
|
+
return Number.isNaN(difference) ? 0 : difference;
|
|
436
|
+
}
|
|
437
|
+
const sortValue = (row, columnId) => row.getIsGrouped?.() ? void 0 : row.getValue(columnId);
|
|
438
|
+
/**
|
|
439
|
+
* The plugin's sort function, set by `assistantColumn`. Rows that tie keep the order of the data,
|
|
440
|
+
* as on the grid.
|
|
441
|
+
*/
|
|
442
|
+
const assistantSort = (rowA, rowB, columnId) => compareCells(sortValue(rowA, columnId), sortValue(rowB, columnId), typeOf(rowA, columnId));
|
|
443
|
+
// src/describe.ts
|
|
444
|
+
const EXAMPLES = 5;
|
|
445
|
+
function readOptions(raw) {
|
|
446
|
+
if (!Array.isArray(raw)) return [];
|
|
447
|
+
return raw.flatMap((option) => {
|
|
448
|
+
const value = isRecord(option) ? option.value : option;
|
|
449
|
+
const label = isRecord(option) ? option.label : option;
|
|
450
|
+
const text = typeof label === "number" ? String(label) : label;
|
|
451
|
+
if (typeof text !== "string" || text.length > 255) return [];
|
|
452
|
+
if (typeof value === "number" || typeof value === "string" && value.length <= 255) return [{
|
|
453
|
+
value,
|
|
454
|
+
label: text
|
|
455
|
+
}];
|
|
456
|
+
return [];
|
|
457
|
+
}).slice(0, 500);
|
|
458
|
+
}
|
|
459
|
+
function distinct(values) {
|
|
460
|
+
const seen = /* @__PURE__ */ new Set();
|
|
461
|
+
return values.filter((value) => {
|
|
462
|
+
if (value == null || value === "") return false;
|
|
463
|
+
const key = JSON.stringify(value);
|
|
464
|
+
if (seen.has(key) || seen.size >= EXAMPLES) return false;
|
|
465
|
+
seen.add(key);
|
|
466
|
+
return true;
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
/** True when the column sorts with `assistantSort`, as `assistantColumn` sets it up. */
|
|
470
|
+
const sortsLikeTheGrid = (column) => column.getSortFn?.() === assistantSort && column.columnDef.sortUndefined === false && !column.columnDef.invertSorting;
|
|
471
|
+
/** Which features the table has registered and switched on. */
|
|
472
|
+
function readFeatures(table) {
|
|
473
|
+
const { options } = table;
|
|
474
|
+
return {
|
|
475
|
+
filtering: !!table.setColumnFilters && !options.manualFiltering && "filteredRowModel" in options.features,
|
|
476
|
+
sorting: !!table.setSorting && (!!options.manualSorting || "sortedRowModel" in options.features),
|
|
477
|
+
grouping: !!table.setGrouping && (!!options.manualGrouping || groupsLikeTheGrid(options.features)),
|
|
478
|
+
selection: !!table.setRowSelection && options.enableRowSelection !== false
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
/** The table's data columns. A type in `meta.assistant` wins over the one inferred from the rows. */
|
|
482
|
+
function readColumns(table) {
|
|
483
|
+
const on = readFeatures(table);
|
|
484
|
+
const rows = table.getCoreRowModel().flatRows;
|
|
485
|
+
return table.getAllLeafColumns().filter((column) => !!column.accessorFn && column.id.length <= 255).map((column) => {
|
|
486
|
+
const stated = metaOf(column);
|
|
487
|
+
const values = sample(column, rows);
|
|
488
|
+
const type = columnType(column, rows);
|
|
489
|
+
const info = {
|
|
490
|
+
id: column.id,
|
|
491
|
+
type,
|
|
492
|
+
options: type === "singleSelect" ? readOptions(stated.options) : [],
|
|
493
|
+
filterable: on.filtering && (column.getCanFilter?.() ?? false) && column.getFilterFn?.() === assistantFilter,
|
|
494
|
+
sortable: on.sorting && (column.getCanSort?.() ?? false) && (!!table.options.manualSorting || sortsLikeTheGrid(column)),
|
|
495
|
+
groupable: on.grouping && (column.getCanGroup?.() ?? false)
|
|
496
|
+
};
|
|
497
|
+
const { header } = column.columnDef;
|
|
498
|
+
if (typeof header === "string") info.header = header;
|
|
499
|
+
if (typeof stated.description === "string") info.description = stated.description;
|
|
500
|
+
if (stated.examples === true) info.examples = distinct(values);
|
|
501
|
+
else if (Array.isArray(stated.examples)) info.examples = stated.examples.slice(0, 20);
|
|
502
|
+
return info;
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
/** The `context` of the request: one entry per column. */
|
|
506
|
+
function readContext(columns) {
|
|
507
|
+
return columns.map((column) => {
|
|
508
|
+
const entry = {
|
|
509
|
+
field: column.id,
|
|
510
|
+
type: column.type,
|
|
511
|
+
allowedOperators: column.filterable ? [...OPERATORS[column.type]] : []
|
|
512
|
+
};
|
|
513
|
+
if (column.header !== void 0) entry.headerName = column.header;
|
|
514
|
+
if (column.description !== void 0) entry.description = column.description;
|
|
515
|
+
if (column.examples !== void 0) entry.examples = column.examples;
|
|
516
|
+
return entry;
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
function readFilters(table) {
|
|
520
|
+
const entries = (table.store.get().columnFilters ?? []).flatMap((entry) => isAssistantFilterValue(entry.value) ? [entry.value] : []);
|
|
521
|
+
const filters = entries.flatMap((entry) => entry.filters.map(({ column, operator, value }) => ({
|
|
522
|
+
column,
|
|
523
|
+
operator,
|
|
524
|
+
value
|
|
525
|
+
})));
|
|
526
|
+
return {
|
|
527
|
+
filters,
|
|
528
|
+
or: filters.length > 1 && entries.some((entry) => entry.logic === "or")
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
/** What the table allows and shows. Aggregation, pivoting and charts are not TanStack state. */
|
|
532
|
+
function readSnapshot(table, columns) {
|
|
533
|
+
const on = readFeatures(table);
|
|
534
|
+
const disabled = [];
|
|
535
|
+
if (!columns.some((c) => c.filterable)) disabled.push("filtering");
|
|
536
|
+
if (!columns.some((c) => c.sortable)) disabled.push("sorting");
|
|
537
|
+
if (!columns.some((c) => c.groupable)) disabled.push("grouping");
|
|
538
|
+
disabled.push("aggregation", "pivoting");
|
|
539
|
+
if (!on.selection) disabled.push("selection");
|
|
540
|
+
disabled.push("charts");
|
|
541
|
+
const limits = {};
|
|
542
|
+
for (const column of columns) {
|
|
543
|
+
const limit = {};
|
|
544
|
+
if (!disabled.includes("filtering") && !column.filterable) limit.filterable = false;
|
|
545
|
+
if (!disabled.includes("sorting") && !column.sortable) limit.sortable = false;
|
|
546
|
+
if (!disabled.includes("grouping") && !column.groupable) limit.groupable = false;
|
|
547
|
+
if (column.options.length > 0) limit.options = column.options;
|
|
548
|
+
if (Object.keys(limit).length > 0) limits[column.id] = limit;
|
|
549
|
+
}
|
|
550
|
+
const state = {};
|
|
551
|
+
const { filters, or } = readFilters(table);
|
|
552
|
+
if (filters.length > 0) state.filters = filters;
|
|
553
|
+
if (or) state.filterOperator = "or";
|
|
554
|
+
const { sorting = [], grouping = [] } = table.store.get();
|
|
555
|
+
if (sorting.length > 0) state.sorting = sorting.map((sort) => ({
|
|
556
|
+
column: sort.id,
|
|
557
|
+
direction: sort.desc ? "desc" : "asc"
|
|
558
|
+
}));
|
|
559
|
+
if (grouping.length > 0) state.grouping = grouping.map((column) => ({ column }));
|
|
560
|
+
const snapshot = {
|
|
561
|
+
table: "tanstack-table",
|
|
562
|
+
disabled
|
|
563
|
+
};
|
|
564
|
+
if (Object.keys(limits).length > 0) snapshot.columns = limits;
|
|
565
|
+
snapshot.state = state;
|
|
566
|
+
return snapshot;
|
|
567
|
+
}
|
|
568
|
+
// src/index.ts
|
|
569
|
+
/** `ask` rejects with this, code `RESET_CODE`, when `reset()` was called before its answer arrived. */
|
|
570
|
+
const RESET = "The conversation was reset before this answer arrived.";
|
|
571
|
+
const RESET_CODE = "reset";
|
|
572
|
+
/** `ask` rejects with this, code `CANNOT_APPLY_CODE`, when the table cannot take the answer. */
|
|
573
|
+
const CANNOT_APPLY = "This answer could not be applied to the table.";
|
|
574
|
+
/**
|
|
575
|
+
* The one line a table needs: `defaultColumn: assistantColumn`, or spread it into the columns the
|
|
576
|
+
* assistant may filter and sort. Filters and sorts as the MUI X Data Grid does.
|
|
577
|
+
*/
|
|
578
|
+
const assistantColumn = {
|
|
579
|
+
filterFn: assistantFilter,
|
|
580
|
+
sortFn: assistantSort,
|
|
581
|
+
sortUndefined: false
|
|
582
|
+
};
|
|
583
|
+
/** How long a table that owns its state outside TanStack (React state, say) has to take an answer. */
|
|
584
|
+
const SETTLE_TIMEOUT = 1e3;
|
|
585
|
+
const KEYS = [
|
|
586
|
+
"columnFilters",
|
|
587
|
+
"globalFilter",
|
|
588
|
+
"sorting",
|
|
589
|
+
"grouping",
|
|
590
|
+
"rowSelection"
|
|
591
|
+
];
|
|
592
|
+
function cannotApply(detail) {
|
|
593
|
+
throw new GridsayError$1(CANNOT_APPLY, {
|
|
594
|
+
code: CANNOT_APPLY_CODE$1,
|
|
595
|
+
detail
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
const VERBS = {
|
|
599
|
+
filterable: "filtered",
|
|
600
|
+
sortable: "sorted",
|
|
601
|
+
groupable: "grouped"
|
|
602
|
+
};
|
|
603
|
+
/** The column `id` names, or a throw naming the part of the answer when it cannot be used for it. */
|
|
604
|
+
function usable(part, id, column, can) {
|
|
605
|
+
const name = JSON.stringify(id);
|
|
606
|
+
if (!column) return cannotApply(`${part}: no column ${name}`);
|
|
607
|
+
if (!column[can]) return cannotApply(`${part}: column ${name} cannot be ${VERBS[can]}`);
|
|
608
|
+
return column;
|
|
609
|
+
}
|
|
610
|
+
/** A singleSelect filter names an option by its label; the table holds its value. */
|
|
611
|
+
function storedValue(column, value) {
|
|
612
|
+
if (column.type !== "singleSelect" || Array.isArray(value)) return value;
|
|
613
|
+
return column.options.find((option) => option.label === value)?.value ?? value;
|
|
614
|
+
}
|
|
615
|
+
/** One entry per column for AND; one entry holding every filter for OR. */
|
|
616
|
+
function filterEntries(filters, or) {
|
|
617
|
+
if (or && filters.length > 1) {
|
|
618
|
+
const value = {
|
|
619
|
+
logic: "or",
|
|
620
|
+
filters
|
|
621
|
+
};
|
|
622
|
+
return [{
|
|
623
|
+
id: filters[0]?.column ?? "",
|
|
624
|
+
value
|
|
625
|
+
}];
|
|
626
|
+
}
|
|
627
|
+
const byColumn = /* @__PURE__ */ new Map();
|
|
628
|
+
for (const filter of filters) {
|
|
629
|
+
const list = byColumn.get(filter.column);
|
|
630
|
+
if (list) list.push(filter);
|
|
631
|
+
else byColumn.set(filter.column, [filter]);
|
|
632
|
+
}
|
|
633
|
+
return [...byColumn].map(([id, list]) => {
|
|
634
|
+
return {
|
|
635
|
+
id,
|
|
636
|
+
value: {
|
|
637
|
+
logic: "and",
|
|
638
|
+
filters: list
|
|
639
|
+
}
|
|
640
|
+
};
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
/** The state the answer sets, or a `CANNOT_APPLY` naming what the table cannot take. */
|
|
644
|
+
function plan(table, data) {
|
|
645
|
+
if (Object.keys(data.aggregation).length > 0) cannotApply("aggregation: not supported");
|
|
646
|
+
if ("columns" in data.pivoting) cannotApply("pivoting: not supported");
|
|
647
|
+
if (data.chart) cannotApply("chart: not supported");
|
|
648
|
+
const on = readFeatures(table);
|
|
649
|
+
const columns = new Map(readColumns(table).map((column) => [column.id, column]));
|
|
650
|
+
const next = {};
|
|
651
|
+
const filters = data.filters.map((filter) => {
|
|
652
|
+
const column = usable("filters", filter.column, columns.get(filter.column), "filterable");
|
|
653
|
+
const stored = {
|
|
654
|
+
...filter,
|
|
655
|
+
value: storedValue(column, filter.value),
|
|
656
|
+
type: column.type
|
|
657
|
+
};
|
|
658
|
+
try {
|
|
659
|
+
compileFilter(stored);
|
|
660
|
+
} catch {
|
|
661
|
+
const name = `column ${JSON.stringify(column.id)} (${column.type})`;
|
|
662
|
+
const operator = JSON.stringify(filter.operator);
|
|
663
|
+
cannotApply(OPERATORS[column.type].includes(filter.operator) ? `filters: ${name} cannot take that value for ${operator}` : `filters: ${name} has no operator ${operator}`);
|
|
664
|
+
}
|
|
665
|
+
return stored;
|
|
666
|
+
});
|
|
667
|
+
if (on.filtering) {
|
|
668
|
+
next.columnFilters = filterEntries(filters, data.filterOperator === "or");
|
|
669
|
+
if (table.setGlobalFilter) next.globalFilter = void 0;
|
|
670
|
+
}
|
|
671
|
+
for (const sort of data.sorting) usable("sorting", sort.column, columns.get(sort.column), "sortable");
|
|
672
|
+
if (on.sorting) next.sorting = data.sorting.map((sort) => ({
|
|
673
|
+
id: sort.column,
|
|
674
|
+
desc: sort.direction === "desc"
|
|
675
|
+
}));
|
|
676
|
+
for (const group of data.grouping) usable("grouping", group.column, columns.get(group.column), "groupable");
|
|
677
|
+
if (on.grouping) next.grouping = data.grouping.map((group) => group.column);
|
|
678
|
+
if (data.select > 0 && !on.selection) cannotApply("select: row selection is off");
|
|
679
|
+
return next;
|
|
680
|
+
}
|
|
681
|
+
function write(table, slices) {
|
|
682
|
+
if (slices.columnFilters) table.setColumnFilters?.([...slices.columnFilters]);
|
|
683
|
+
if ("globalFilter" in slices) table.setGlobalFilter?.(slices.globalFilter);
|
|
684
|
+
if (slices.sorting) table.setSorting?.([...slices.sorting]);
|
|
685
|
+
if (slices.grouping) table.setGrouping?.([...slices.grouping]);
|
|
686
|
+
if (slices.rowSelection) table.setRowSelection?.({ ...slices.rowSelection });
|
|
687
|
+
}
|
|
688
|
+
/** The current value of each slice `keys` names, with the page and the expanded rows. */
|
|
689
|
+
function pick(table, keys) {
|
|
690
|
+
const state = table.store.get();
|
|
691
|
+
const before = {};
|
|
692
|
+
if (keys.columnFilters) before.columnFilters = state.columnFilters ?? [];
|
|
693
|
+
if ("globalFilter" in keys) before.globalFilter = state.globalFilter;
|
|
694
|
+
if (keys.sorting) before.sorting = state.sorting ?? [];
|
|
695
|
+
if (keys.grouping) before.grouping = state.grouping ?? [];
|
|
696
|
+
if (keys.rowSelection) before.rowSelection = state.rowSelection ?? {};
|
|
697
|
+
if (state.pagination) before.pagination = state.pagination;
|
|
698
|
+
if (state.expanded !== void 0) before.expanded = state.expanded;
|
|
699
|
+
return before;
|
|
700
|
+
}
|
|
701
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
702
|
+
/** Resolves once the table shows `target`, which a state owner outside TanStack does on its next render. */
|
|
703
|
+
async function settle(table, target) {
|
|
704
|
+
const deadline = Date.now() + SETTLE_TIMEOUT;
|
|
705
|
+
const shows = () => {
|
|
706
|
+
const state = table.store.get();
|
|
707
|
+
return KEYS.every((key) => !(key in target) || same(state[key], target[key]));
|
|
708
|
+
};
|
|
709
|
+
while (!shows()) {
|
|
710
|
+
if (Date.now() > deadline) cannotApply("state: the table did not show the answer within 1 second");
|
|
711
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
715
|
+
/**
|
|
716
|
+
* Puts `before` back. A change to filters, sorting or grouping sends the table to its first page
|
|
717
|
+
* and folds its rows once its row models recompute, so the page and the expanded rows go back after.
|
|
718
|
+
* Stops at the first wait after which `live` is false (a reset).
|
|
719
|
+
*/
|
|
720
|
+
async function restore(table, before, live) {
|
|
721
|
+
if (!live()) return;
|
|
722
|
+
write(table, before);
|
|
723
|
+
try {
|
|
724
|
+
await settle(table, before);
|
|
725
|
+
} catch {}
|
|
726
|
+
if (!live()) return;
|
|
727
|
+
table.getRowModel();
|
|
728
|
+
await tick();
|
|
729
|
+
if (!live()) return;
|
|
730
|
+
if (before.pagination) table.setPagination?.({ ...before.pagination });
|
|
731
|
+
const { expanded } = before;
|
|
732
|
+
if (expanded !== void 0) table.setExpanded?.(expanded === true ? true : { ...expanded });
|
|
733
|
+
}
|
|
734
|
+
/** The first `count` data rows in the order shown, inside groups too, as the grid selects them. */
|
|
735
|
+
function firstRows(table, count) {
|
|
736
|
+
const selection = {};
|
|
737
|
+
let left = count;
|
|
738
|
+
const visit = (rows) => {
|
|
739
|
+
for (const row of rows) {
|
|
740
|
+
if (left === 0) return;
|
|
741
|
+
if (row.subRows.length > 0) visit(row.subRows);
|
|
742
|
+
else {
|
|
743
|
+
selection[row.id] = true;
|
|
744
|
+
left -= 1;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
};
|
|
748
|
+
visit(table.getSortedRowModel().rows);
|
|
749
|
+
return selection;
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Applies all of the answer or none of it, and returns the state it replaced. Once `live` is false
|
|
753
|
+
* (a reset), it writes nothing more, not even to put the view back.
|
|
754
|
+
*/
|
|
755
|
+
async function apply(table, data, live) {
|
|
756
|
+
const next = plan(table, data);
|
|
757
|
+
const before = pick(table, {
|
|
758
|
+
...next,
|
|
759
|
+
...data.select > 0 ? { rowSelection: {} } : {}
|
|
760
|
+
});
|
|
761
|
+
try {
|
|
762
|
+
write(table, next);
|
|
763
|
+
await settle(table, next);
|
|
764
|
+
if (data.select > 0 && live()) {
|
|
765
|
+
const selected = { rowSelection: firstRows(table, data.select) };
|
|
766
|
+
write(table, selected);
|
|
767
|
+
await settle(table, selected);
|
|
768
|
+
}
|
|
769
|
+
} catch (cause) {
|
|
770
|
+
try {
|
|
771
|
+
await restore(table, before, live);
|
|
772
|
+
} catch {}
|
|
773
|
+
if (cause instanceof GridsayError$1) throw cause;
|
|
774
|
+
throw new GridsayError$1(CANNOT_APPLY, {
|
|
775
|
+
code: CANNOT_APPLY_CODE$1,
|
|
776
|
+
detail: "state: the table threw on the answer",
|
|
777
|
+
cause
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
return before;
|
|
781
|
+
}
|
|
782
|
+
/** A promise that rejects with `RESET` when tripped, for every question asked before it was. */
|
|
783
|
+
function tripwire() {
|
|
784
|
+
let trip = () => {};
|
|
785
|
+
const tripped = new Promise((_, reject) => {
|
|
786
|
+
trip = () => reject(new GridsayError$1(RESET, { code: RESET_CODE }));
|
|
787
|
+
});
|
|
788
|
+
tripped.catch(() => void 0);
|
|
789
|
+
return {
|
|
790
|
+
trip,
|
|
791
|
+
tripped
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
/** True when the table could filter but no column has the plugin's filter function. */
|
|
795
|
+
function unwired(table) {
|
|
796
|
+
const columns = table.getAllLeafColumns().filter((column) => column.getCanFilter?.());
|
|
797
|
+
return readFeatures(table).filtering && columns.length > 0 && columns.every((column) => column.getFilterFn?.() !== assistantFilter);
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* The TanStack Table counterpart of `createPromptResolver`: give it the table, ask in words.
|
|
801
|
+
* Columns the assistant may filter and sort need `assistantColumn`.
|
|
802
|
+
*/
|
|
803
|
+
function createTableAssistant(table, options) {
|
|
804
|
+
let conversationId;
|
|
805
|
+
let last;
|
|
806
|
+
let queue = Promise.resolve();
|
|
807
|
+
let warned = false;
|
|
808
|
+
let generation = 0;
|
|
809
|
+
let wire = tripwire();
|
|
810
|
+
let pending = 0;
|
|
811
|
+
async function send(query, live) {
|
|
812
|
+
const stale = () => {
|
|
813
|
+
if (!live()) throw new GridsayError$1(RESET, { code: RESET_CODE });
|
|
814
|
+
};
|
|
815
|
+
stale();
|
|
816
|
+
if (!warned && unwired(table)) {
|
|
817
|
+
warned = true;
|
|
818
|
+
console.warn("Gridsay: no column has `filterFn: assistantFilter`, so the assistant cannot filter. Add `defaultColumn: assistantColumn` to the table's options.");
|
|
819
|
+
}
|
|
820
|
+
const columns = readColumns(table);
|
|
821
|
+
const body = {
|
|
822
|
+
query,
|
|
823
|
+
context: JSON.stringify(readContext(columns)),
|
|
824
|
+
conversationId,
|
|
825
|
+
options: promptOptionsOf(options),
|
|
826
|
+
grid: readSnapshot(table, columns)
|
|
827
|
+
};
|
|
828
|
+
const init = {
|
|
829
|
+
method: "POST",
|
|
830
|
+
headers: await requestHeaders(options),
|
|
831
|
+
body: JSON.stringify(body)
|
|
832
|
+
};
|
|
833
|
+
stale();
|
|
834
|
+
let response;
|
|
835
|
+
try {
|
|
836
|
+
response = await fetch(options.url, init);
|
|
837
|
+
} catch (cause) {
|
|
838
|
+
throw new GridsayError$1(CONNECTION_FAILED$1, {
|
|
839
|
+
code: CONNECTION_FAILED_CODE$1,
|
|
840
|
+
cause
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
const data = await readResponse(response);
|
|
844
|
+
stale();
|
|
845
|
+
conversationId = data.conversationId;
|
|
846
|
+
const before = await apply(table, data, live);
|
|
847
|
+
stale();
|
|
848
|
+
last = before;
|
|
849
|
+
}
|
|
850
|
+
return {
|
|
851
|
+
get canUndo() {
|
|
852
|
+
return last !== void 0 && pending === 0;
|
|
853
|
+
},
|
|
854
|
+
ask(question) {
|
|
855
|
+
const own = generation;
|
|
856
|
+
const live = () => own === generation;
|
|
857
|
+
const result = queue.then(() => send(question, live)).catch((cause) => {
|
|
858
|
+
if (cause instanceof GridsayError$1) throw cause;
|
|
859
|
+
throw new GridsayError$1(INVALID_ANSWER$1, {
|
|
860
|
+
code: UNEXPECTED_ERROR_CODE$1,
|
|
861
|
+
cause
|
|
862
|
+
});
|
|
863
|
+
});
|
|
864
|
+
queue = result.catch(() => void 0);
|
|
865
|
+
pending += 1;
|
|
866
|
+
return Promise.race([result, wire.tripped]).finally(() => {
|
|
867
|
+
if (live()) pending -= 1;
|
|
868
|
+
});
|
|
869
|
+
},
|
|
870
|
+
undo() {
|
|
871
|
+
if (!last || pending > 0) return false;
|
|
872
|
+
const before = last;
|
|
873
|
+
last = void 0;
|
|
874
|
+
write(table, before);
|
|
875
|
+
const own = generation;
|
|
876
|
+
queue = queue.then(() => restore(table, before, () => own === generation)).catch(() => void 0);
|
|
877
|
+
return true;
|
|
878
|
+
},
|
|
879
|
+
reset() {
|
|
880
|
+
generation += 1;
|
|
881
|
+
conversationId = void 0;
|
|
882
|
+
last = void 0;
|
|
883
|
+
pending = 0;
|
|
884
|
+
queue = Promise.resolve();
|
|
885
|
+
wire.trip();
|
|
886
|
+
wire = tripwire();
|
|
887
|
+
}
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
export { assistantSort as _, GridsayError as a, NOT_JSON as c, RESET_CODE as d, UNAUTHENTICATED_USER as f, createTableAssistant as g, assistantColumn as h, CONNECTION_FAILED_CODE as i, NOT_JSON_CODE as l, UNEXPECTED_ERROR_CODE as m, CANNOT_APPLY_CODE as n, INVALID_ANSWER as o, UNAUTHENTICATED_USER_CODE as p, CONNECTION_FAILED as r, INVALID_ANSWER_CODE as s, CANNOT_APPLY as t, RESET as u, assistantGroupedRowModel as v, assistantFilter as y };
|