@gridsay/tanstack-table 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @gridsay/tanstack-table
2
2
 
3
- Your users ask a TanStack Table in plain words: "orders over 500 from Germany, newest first". The helper describes your table to Gridsay, sends the question, and applies the answer to the table: filters, sorting, grouping, or the top rows selected. All of the answer, or none of it, unless `reset()` comes while it is being applied. Where this stands: [gridsay.com/features#status](https://gridsay.com/features#status). More: [gridsay.com/product/tanstack-table](https://gridsay.com/product/tanstack-table) and [gridsay.com/docs/tanstack-table](https://gridsay.com/docs/tanstack-table).
3
+ Your users ask a TanStack Table in plain words: "orders over 500 from Germany, newest first". The helper describes your table to Gridsay, sends the question, and applies the answer to the table: filters, sorting, grouping, the columns shown, or the top rows selected. All of the answer, or none of it, unless `reset()` comes while it is being applied, or a setter of your table throws while the answer is being put back: then the columns or another part can stay changed, and the error you get is the first one. Where this stands: [gridsay.com/features#status](https://gridsay.com/features#status). More: [gridsay.com/product/tanstack-table](https://gridsay.com/product/tanstack-table) and [gridsay.com/docs/tanstack-table](https://gridsay.com/docs/tanstack-table).
4
4
 
5
5
  TanStack Table is headless, and so is this package: it ships no interface. You bring the input box (step 4).
6
6
 
@@ -213,7 +213,7 @@ A caller your route turns away gets status 401, code `unauthenticated_user` and
213
213
  `useTableAssistant(table, options)` returns:
214
214
 
215
215
  - `ask(question)`: resolves `true` when the answer is on the table, `false` when it is not. Then `error` says why, except after `reset()`.
216
- - `undo()`: puts back what the last answer changed and returns `true`. It does nothing and returns `false` when there is nothing to undo, or while a question is pending. It undoes one answer; it does not stack.
216
+ - `undo()`: puts back what the last answer changed and returns `true`. It does nothing and returns `false` when there is nothing to undo, or while a question is pending. It undoes one answer; it does not stack. If a setter of your table throws, `undo()` throws the first error once the other setters have run, and can be called again.
217
217
  - `reset()`: starts a new conversation. The next question does not build on earlier ones, `undo` forgets, and the table stays as it is. It does not cancel a request already sent: Gridsay may still answer it, and charge for it. A question still waiting for its answer changes nothing on the table afterwards.
218
218
  - `canUndo`: true after an applied answer; a refusal leaves it as it was. It is `false` while a question is pending.
219
219
  - `pending`: true while a question is being answered.
@@ -248,6 +248,7 @@ assistant.undo(); // false when there is nothing to undo, or while a question is
248
248
  | `additionalContext` | Extra text for the assistant about your table. |
249
249
  | `privateMode` | Sent to Gridsay as `options.privateMode`. |
250
250
  | `referenceId` | Your id for the end user. |
251
+ | `features` | What questions may change beyond filters, sorting, grouping and selection, each off unless `true`. `{ columnVisibility: true }` lets them hide and show columns; see What an answer changes. |
251
252
 
252
253
  ## Errors
253
254
 
@@ -274,31 +275,36 @@ What the helper itself reports, with no request to blame:
274
275
  | `connection_failed` | The request did not complete: no network, or the connection broke while the answer was read. | Ask again. |
275
276
  | `not_json` | Your route answered with something that is not JSON, often because its path does not exist. `status` says which. | Check `url` and the route. |
276
277
  | `invalid_answer` | The response was not an answer the helper can read. | Return Gridsay's body and status from your route as they came. |
277
- | `cannot_apply` | The answer could not be applied to the table, so nothing changed. `detail` names what, such as `sorting: no column "total"`. | Check the column ids and the features you registered. Do not show `detail` to users. |
278
+ | `cannot_apply` | The answer could not be applied to the table, so nothing changed, unless a setter of your table also threw while it was being put back. `detail` names what, such as `sorting: no column "total"`. | Check the column ids and the features you registered. Do not show `detail` to users. |
278
279
  | `reset` | `reset()` was called while the question was waiting. The hook ignores it. | Nothing: no answer is wanted. |
279
280
 
280
281
  A question the assistant declines (422) is charged. A question Gridsay fails to answer (413, 429, 502) is not. An answer the helper cannot apply (`cannot_apply`) was already answered by Gridsay, so it is charged like any answer.
281
282
 
282
283
  ## What an answer changes
283
284
 
284
- An answer sets filters, sorting, grouping, and the selection of the first rows, each only when you registered what it needs:
285
+ An answer sets filters, sorting, grouping, which columns are hidden, and the selection of the first rows, each only when you registered what it needs:
285
286
 
286
287
  | Answer | Needs on the table |
287
288
  |---|---|
288
289
  | Filters | `columnFilteringFeature` and `filteredRowModel`, and not `manualFiltering` |
289
290
  | Sorting | `rowSortingFeature` and `sortedRowModel`, or `manualSorting` |
290
291
  | Grouping | `columnGroupingFeature` and `assistantGroupedRowModel()`, or `manualGrouping` |
292
+ | Hidden columns | `features: { columnVisibility: true }` in the options, `columnVisibilityFeature`, and a column that can hide |
291
293
  | Top rows selected | `rowSelectionFeature`, and `enableRowSelection` not `false` |
292
294
 
293
295
  Whatever is missing is reported to Gridsay as switched off, and a question that needs it gets a sentence back.
294
296
 
295
- It never changes totals, pivots or charts: a question that needs one gets a sentence back. It does not touch column visibility, order, pinning or sizing, or paging. An answer that changes filters, sorting or grouping sends the table to its first page, as TanStack does for any such change; undo puts the page and the open groups back as they were.
297
+ It never changes totals, pivots or charts: a question that needs one gets a sentence back. It does not touch column order, pinning or sizing, or paging. An answer that changes filters, sorting or grouping sends the table to its first page, as TanStack does for any such change; undo puts the page and the open groups back as they were.
296
298
 
297
299
  - **Filtering runs in the browser.** A table that filters on its server (`manualFiltering`) cannot be filtered by the assistant. With `manualSorting` or `manualGrouping` the assistant sets the sorting or grouping state, and fetching the rows in that order is your code.
298
300
  - **An answer is the whole filter.** It replaces the column filters, including any you set by hand, and clears a global filter, such as a search box. Every question sends the table's current sorting and grouping and the filters an earlier answer set, so a header click that sorts is part of the next question.
301
+ - **Hidden columns** are off unless you switch them on: `features: { columnVisibility: true }` in the options of `useTableAssistant` or `createTableAssistant`. With `columnVisibilityFeature` registered and a column that can hide, a question can then hide and show columns: "hide the country column", "show all columns". Only the columns the answer hides or shows change, so a column the user hides or shows while the question waits stays as they left it. "Show all columns" shows every column the assistant sees that can hide, those your app hid at the start too, and a question may hide every column. A column with `enableHiding: false` stays shown or hidden as it is, and with `enableHiding: false` on the table no column changes. Undo after an answer that changed the columns puts them back as they were; after any other answer it leaves them alone.
302
+ - **Render the visible columns**, with `getVisibleLeafColumns()` and `row.getVisibleCells()`: `getAllLeafColumns()` and `getAllCells()` show hidden columns too.
303
+ - **Where questions cannot hide or show columns**: while more than 500 of the columns the assistant sees are hidden; while one of the columns the assistant sees whose id Gridsay keeps for grid controls, such as `__check__`, is hidden (such a column is never hidden or shown by a question); and when one of the columns the assistant sees is named `__proto__` and cannot hide.
299
304
  - **State you own** (React state passed as `state` with `onSortingChange`, say) must show the answer within one second. Otherwise the table is put back and `ask` rejects with `cannot_apply`.
300
305
  - **Top rows** are the first rows of the table in the order shown, inside groups too.
301
306
  - **TanStack's own grouped row model** does not group for the assistant; use `assistantGroupedRowModel()`.
307
+ - **`groupedColumnMode: 'remove'`** takes a grouped column out of what is sent, so an answer that keeps that grouping is not applied, nor is one that groups by a column and also hides or shows it.
302
308
 
303
309
  ## Columns
304
310
 
@@ -308,11 +314,11 @@ The assistant sees the columns that have an accessor. Display columns are not se
308
314
  - **`assistantColumn`** is `filterFn: assistantFilter`, `sortFn: assistantSort` and `sortUndefined: false`. Set it as `defaultColumn` or spread it into a column. If no column has the filter function, the helper warns once in the browser console.
309
315
  - **A column with its own `filterFn` or `sortFn` is left to you**, and so is one with `enableColumnFilter`, `enableSorting` or `enableGrouping` set to `false`. The assistant is told it cannot filter, sort or group by it.
310
316
  - **`meta.assistant`** is `{ type, description, options, examples }`, all optional. `type` is `string`, `number`, `date`, `dateTime`, `boolean` or `singleSelect`; without one it is read from the first 100 rows, and anything unclear is `string`. A `singleSelect` needs its `options`: values, or `{ value, label }`. `examples` are sent only when you set them: a list, or `true` for up to five values from the rows.
311
- - **What is sent**: your question, each column's id, header, type and description, which features are on, and the table's current sorting and grouping and the filters an answer set. Your rows are not sent, apart from the `examples` you ask for and the options you list.
317
+ - **What is sent**: your question, each column's id, header, type and description, which features are on, and the table's current sorting and grouping and the filters an answer set. When questions may hide and show columns (`features: { columnVisibility: true }` and a table that can), it also sends which columns are hidden and which cannot hide. A hidden column is sent like any other. Your rows are not sent, apart from the `examples` you ask for and the options you list.
312
318
 
313
319
  ## Versions
314
320
 
315
- Before 1.0 a breaking change raises the minor version.
321
+ Before 1.0 a breaking change raises the minor version. An app that imports `GridsayError` from `@gridsay/core` upgrades it to 0.2.0 as well, or imports it from `@gridsay/tanstack-table`, so that `instanceof` still matches.
316
322
 
317
323
  ## Licence
318
324
 
@@ -51,6 +51,7 @@ type TableColumn = {
51
51
  getCanSort?: () => boolean;
52
52
  getSortFn?: () => unknown;
53
53
  getCanGroup?: () => boolean;
54
+ getCanHide?: () => boolean;
54
55
  };
55
56
  type Filter = {
56
57
  id: string;
@@ -65,6 +66,7 @@ type Pagination = {
65
66
  pageSize: number;
66
67
  };
67
68
  type Expanded = true | Readonly<Record<string, boolean>>;
69
+ type Visibility = Record<string, boolean>;
68
70
  /** The slices of table state the plugin reads and writes. */
69
71
  type TableSlices = {
70
72
  columnFilters?: readonly Filter[];
@@ -72,6 +74,12 @@ type TableSlices = {
72
74
  sorting?: readonly Sort[];
73
75
  grouping?: readonly string[];
74
76
  rowSelection?: Readonly<Record<string, true>>;
77
+ columnVisibility?: Readonly<Visibility>;
78
+ /** Columns to hide and show, made on whatever map the table holds when it takes them. */
79
+ visibilityChange?: {
80
+ hide: readonly string[];
81
+ show: readonly string[];
82
+ };
75
83
  pagination?: Readonly<Pagination>;
76
84
  expanded?: Expanded;
77
85
  };
@@ -103,6 +111,7 @@ type AssistantTable = {
103
111
  setSorting?: (sorting: Sort[]) => void;
104
112
  setGrouping?: (grouping: string[]) => void;
105
113
  setRowSelection?: (selection: Record<string, true>) => void;
114
+ setColumnVisibility?: (updater: (previous: Visibility) => Visibility) => void;
106
115
  setPagination?: (pagination: Pagination) => void;
107
116
  setExpanded?: (expanded: true | Record<string, boolean>) => void;
108
117
  };
@@ -135,16 +144,23 @@ declare const CANNOT_APPLY = "This answer could not be applied to the table.";
135
144
  type TableAssistantOptions = RequestOptions & {
136
145
  /** Where the prompt is posted: your own proxy route, or the Gridsay gateway. */
137
146
  url: string;
147
+ /** What questions may change beyond filters, sorting, grouping and selection. Each is off unless `true`. */
148
+ features?: {
149
+ /** Hide and show columns, on a table with `columnVisibilityFeature`. */
150
+ columnVisibility?: boolean;
151
+ };
138
152
  };
139
153
  type TableAssistant = {
140
154
  /**
141
155
  * Answers the question on the table. Rejects with a `GridsayError`; an answer the table cannot
142
- * take is not applied, or is taken back. After `reset()`, a part already applied stays.
156
+ * take is not applied, or is taken back. After `reset()`, a part already applied stays, and so
157
+ * does a part whose setter throws while it is taken back.
143
158
  */
144
159
  ask: (question: string) => Promise<void>;
145
160
  /**
146
161
  * Puts back what the last answer changed, leaving the rest of the table as it is now.
147
- * Returns false, doing nothing, when there is nothing to undo or a question is pending.
162
+ * Returns false, doing nothing, when there is nothing to undo or a question is pending. Throws
163
+ * the first error a setter threw, after the others ran; the undo can then be tried again.
148
164
  */
149
165
  undo: () => boolean;
150
166
  /**
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { C as ColumnType, S as AssistantTable, _ as assistantColumn, a as GridsayError, b as assistantSort, c as NOT_JSON, d as RESET_CODE, f as TableAssistant, g as UNEXPECTED_ERROR_CODE, h as UNAUTHENTICATED_USER_CODE, i as CONNECTION_FAILED_CODE, l as NOT_JSON_CODE, m as UNAUTHENTICATED_USER, n as CANNOT_APPLY_CODE, o as INVALID_ANSWER, p as TableAssistantOptions, r as CONNECTION_FAILED, s as INVALID_ANSWER_CODE, t as CANNOT_APPLY, u as RESET, v as createTableAssistant, w as assistantFilter, x as AssistantColumnMeta, y as assistantGroupedRowModel } from "./index-yyGT4N9i.js";
1
+ import { C as ColumnType, S as AssistantTable, _ as assistantColumn, a as GridsayError, b as assistantSort, c as NOT_JSON, d as RESET_CODE, f as TableAssistant, g as UNEXPECTED_ERROR_CODE, h as UNAUTHENTICATED_USER_CODE, i as CONNECTION_FAILED_CODE, l as NOT_JSON_CODE, m as UNAUTHENTICATED_USER, n as CANNOT_APPLY_CODE, o as INVALID_ANSWER, p as TableAssistantOptions, r as CONNECTION_FAILED, s as INVALID_ANSWER_CODE, t as CANNOT_APPLY, u as RESET, v as createTableAssistant, w as assistantFilter, x as AssistantColumnMeta, y as assistantGroupedRowModel } from "./index-WnXA4ljO.js";
2
2
  export { type AssistantColumnMeta, type AssistantTable, CANNOT_APPLY, CANNOT_APPLY_CODE, CONNECTION_FAILED, CONNECTION_FAILED_CODE, type ColumnType, GridsayError, INVALID_ANSWER, INVALID_ANSWER_CODE, NOT_JSON, NOT_JSON_CODE, RESET, RESET_CODE, TableAssistant, TableAssistantOptions, UNAUTHENTICATED_USER, UNAUTHENTICATED_USER_CODE, UNEXPECTED_ERROR_CODE, assistantColumn, assistantFilter, assistantGroupedRowModel, assistantSort, createTableAssistant };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { t as CANNOT_APPLY, n as CANNOT_APPLY_CODE, r as CONNECTION_FAILED, i as CONNECTION_FAILED_CODE, a as GridsayError, o as INVALID_ANSWER, s as INVALID_ANSWER_CODE, c as NOT_JSON, l as NOT_JSON_CODE, u as RESET, d as RESET_CODE, f as UNAUTHENTICATED_USER, p as UNAUTHENTICATED_USER_CODE, m as UNEXPECTED_ERROR_CODE, h as assistantColumn, y as assistantFilter, v as assistantGroupedRowModel, _ as assistantSort, g as createTableAssistant } from "./src-D4dDBjRk.js";
1
+ export { t as CANNOT_APPLY, n as CANNOT_APPLY_CODE, r as CONNECTION_FAILED, i as CONNECTION_FAILED_CODE, a as GridsayError, o as INVALID_ANSWER, s as INVALID_ANSWER_CODE, c as NOT_JSON, l as NOT_JSON_CODE, u as RESET, d as RESET_CODE, f as UNAUTHENTICATED_USER, p as UNAUTHENTICATED_USER_CODE, m as UNEXPECTED_ERROR_CODE, h as assistantColumn, y as assistantFilter, v as assistantGroupedRowModel, _ as assistantSort, g as createTableAssistant } from "./src-WEDZd3c4.js";
package/dist/react.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { GridsayError as GridsayError$1 } from "@gridsay/core";
2
- import { C as ColumnType, S as AssistantTable, _ as assistantColumn, a as GridsayError, b as assistantSort, c as NOT_JSON, d as RESET_CODE, f as TableAssistant, g as UNEXPECTED_ERROR_CODE, h as UNAUTHENTICATED_USER_CODE, i as CONNECTION_FAILED_CODE, l as NOT_JSON_CODE, m as UNAUTHENTICATED_USER, n as CANNOT_APPLY_CODE, o as INVALID_ANSWER, p as TableAssistantOptions, r as CONNECTION_FAILED, s as INVALID_ANSWER_CODE, t as CANNOT_APPLY, u as RESET, v as createTableAssistant, w as assistantFilter, x as AssistantColumnMeta, y as assistantGroupedRowModel } from "./index-yyGT4N9i.js";
2
+ import { C as ColumnType, S as AssistantTable, _ as assistantColumn, a as GridsayError, b as assistantSort, c as NOT_JSON, d as RESET_CODE, f as TableAssistant, g as UNEXPECTED_ERROR_CODE, h as UNAUTHENTICATED_USER_CODE, i as CONNECTION_FAILED_CODE, l as NOT_JSON_CODE, m as UNAUTHENTICATED_USER, n as CANNOT_APPLY_CODE, o as INVALID_ANSWER, p as TableAssistantOptions, r as CONNECTION_FAILED, s as INVALID_ANSWER_CODE, t as CANNOT_APPLY, u as RESET, v as createTableAssistant, w as assistantFilter, x as AssistantColumnMeta, y as assistantGroupedRowModel } from "./index-WnXA4ljO.js";
3
3
  export type TableAssistantState = {
4
4
  /**
5
5
  * Answers the question on the table. Resolves false when it could not; `error` then says why,
package/dist/react.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { GridsayError as GridsayError$1, INVALID_ANSWER as INVALID_ANSWER$1 } from "@gridsay/core";
2
2
  import { useCallback, useReducer, useRef, useState } from "react";
3
- import { _ as assistantSort, a as GridsayError, c as NOT_JSON, d as RESET_CODE, f as UNAUTHENTICATED_USER, g as createTableAssistant, h as assistantColumn, i as CONNECTION_FAILED_CODE, l as NOT_JSON_CODE, m as UNEXPECTED_ERROR_CODE, n as CANNOT_APPLY_CODE, o as INVALID_ANSWER, p as UNAUTHENTICATED_USER_CODE, r as CONNECTION_FAILED, s as INVALID_ANSWER_CODE, t as CANNOT_APPLY, u as RESET, v as assistantGroupedRowModel, y as assistantFilter } from "./src-D4dDBjRk.js";
3
+ import { _ as assistantSort, a as GridsayError, c as NOT_JSON, d as RESET_CODE, f as UNAUTHENTICATED_USER, g as createTableAssistant, h as assistantColumn, i as CONNECTION_FAILED_CODE, l as NOT_JSON_CODE, m as UNEXPECTED_ERROR_CODE, n as CANNOT_APPLY_CODE, o as INVALID_ANSWER, p as UNAUTHENTICATED_USER_CODE, r as CONNECTION_FAILED, s as INVALID_ANSWER_CODE, t as CANNOT_APPLY, u as RESET, v as assistantGroupedRowModel, y as assistantFilter } from "./src-WEDZd3c4.js";
4
4
  // src/react.ts
5
5
  /** Reads through to the latest value, so the assistant made on the first render follows the props. */
6
6
  function latest(ref) {
@@ -475,7 +475,8 @@ function readFeatures(table) {
475
475
  filtering: !!table.setColumnFilters && !options.manualFiltering && "filteredRowModel" in options.features,
476
476
  sorting: !!table.setSorting && (!!options.manualSorting || "sortedRowModel" in options.features),
477
477
  grouping: !!table.setGrouping && (!!options.manualGrouping || groupsLikeTheGrid(options.features)),
478
- selection: !!table.setRowSelection && options.enableRowSelection !== false
478
+ selection: !!table.setRowSelection && options.enableRowSelection !== false,
479
+ hiding: !!table.setColumnVisibility
479
480
  };
480
481
  }
481
482
  /** The table's data columns. A type in `meta.assistant` wins over the one inferred from the rows. */
@@ -492,7 +493,8 @@ function readColumns(table) {
492
493
  options: type === "singleSelect" ? readOptions(stated.options) : [],
493
494
  filterable: on.filtering && (column.getCanFilter?.() ?? false) && column.getFilterFn?.() === assistantFilter,
494
495
  sortable: on.sorting && (column.getCanSort?.() ?? false) && (!!table.options.manualSorting || sortsLikeTheGrid(column)),
495
- groupable: on.grouping && (column.getCanGroup?.() ?? false)
496
+ groupable: on.grouping && (column.getCanGroup?.() ?? false),
497
+ hideable: on.hiding && (column.getCanHide?.() ?? false)
496
498
  };
497
499
  const { header } = column.columnDef;
498
500
  if (typeof header === "string") info.header = header;
@@ -528,8 +530,11 @@ function readFilters(table) {
528
530
  or: filters.length > 1 && entries.some((entry) => entry.logic === "or")
529
531
  };
530
532
  }
531
- /** What the table allows and shows. Aggregation, pivoting and charts are not TanStack state. */
532
- function readSnapshot(table, columns) {
533
+ /**
534
+ * What the table allows and shows. Aggregation, pivoting and charts are not TanStack state.
535
+ * Hidden columns are offered only when `visibility` is switched on and the table can use it.
536
+ */
537
+ function readSnapshot(table, columns, visibility) {
533
538
  const on = readFeatures(table);
534
539
  const disabled = [];
535
540
  if (!columns.some((c) => c.filterable)) disabled.push("filtering");
@@ -538,12 +543,16 @@ function readSnapshot(table, columns) {
538
543
  disabled.push("aggregation", "pivoting");
539
544
  if (!on.selection) disabled.push("selection");
540
545
  disabled.push("charts");
546
+ const map = table.store.get().columnVisibility ?? {};
547
+ const hidden = columns.filter((c) => map[c.id] === false).map((c) => c.id);
548
+ const hiding = visibility && columns.some((c) => c.hideable) && !columns.some((c) => c.id === "__proto__" && !c.hideable) && hidden.length <= 500;
541
549
  const limits = {};
542
550
  for (const column of columns) {
543
551
  const limit = {};
544
552
  if (!disabled.includes("filtering") && !column.filterable) limit.filterable = false;
545
553
  if (!disabled.includes("sorting") && !column.sortable) limit.sortable = false;
546
554
  if (!disabled.includes("grouping") && !column.groupable) limit.groupable = false;
555
+ if (hiding && !column.hideable) limit.hideable = false;
547
556
  if (column.options.length > 0) limit.options = column.options;
548
557
  if (Object.keys(limit).length > 0) limits[column.id] = limit;
549
558
  }
@@ -557,10 +566,12 @@ function readSnapshot(table, columns) {
557
566
  direction: sort.desc ? "desc" : "asc"
558
567
  }));
559
568
  if (grouping.length > 0) state.grouping = grouping.map((column) => ({ column }));
569
+ if (hiding && hidden.length > 0) state.hiddenColumns = hidden;
560
570
  const snapshot = {
561
571
  table: "tanstack-table",
562
572
  disabled
563
573
  };
574
+ if (hiding) snapshot.accepts = ["hiddenColumns"];
564
575
  if (Object.keys(limits).length > 0) snapshot.columns = limits;
565
576
  snapshot.state = state;
566
577
  return snapshot;
@@ -640,8 +651,56 @@ function filterEntries(filters, or) {
640
651
  };
641
652
  });
642
653
  }
654
+ /**
655
+ * The columns the answer hid or showed, against the hidden ones the question sent; undefined when
656
+ * there are none. Each must still be a column that can hide now, or nothing is written.
657
+ */
658
+ function visibility(hidden, { columns, grid }, live) {
659
+ if (!grid.accepts?.includes("hiddenColumns")) cannotApply("hiddenColumns: column visibility is off");
660
+ const described = new Set(columns.map((column) => column.id));
661
+ for (const id of hidden) if (!described.has(id)) cannotApply(`hiddenColumns: no column ${JSON.stringify(id)}`);
662
+ const was = new Set(grid.state?.hiddenColumns);
663
+ const now = new Set(hidden);
664
+ const changed = columns.filter((column) => was.has(column.id) !== now.has(column.id));
665
+ for (const { id, hideable } of changed) {
666
+ const name = JSON.stringify(id);
667
+ const column = live.get(id);
668
+ if (!column) cannotApply(`hiddenColumns: no column ${name}`);
669
+ const verb = now.has(id) ? "hidden" : "shown";
670
+ if (!hideable || !column.hideable) cannotApply(`hiddenColumns: column ${name} cannot be ${verb}`);
671
+ }
672
+ if (changed.length === 0) return void 0;
673
+ return {
674
+ hide: changed.filter(({ id }) => now.has(id)).map(({ id }) => id),
675
+ show: changed.filter(({ id }) => was.has(id)).map(({ id }) => id)
676
+ };
677
+ }
678
+ /**
679
+ * `previous`, the map the owner holds when it runs the update, with the change made: hidden is
680
+ * `false`, shown is no entry, any id an own key. A column that can no longer hide stays as it is,
681
+ * so the answer does not settle and is refused. When the hidden columns change, `previous` is what
682
+ * a rollback and undo put back; a replayed update records it again.
683
+ */
684
+ function changeOn(table, previous, { hide, show }, before) {
685
+ const can = new Set(table.getAllLeafColumns().filter((column) => column.getCanHide?.()).map((column) => column.id));
686
+ const shown = new Set(show.filter((id) => can.has(id)));
687
+ const entries = Object.entries(previous).filter(([id]) => !shown.has(id));
688
+ for (const id of hide) if (can.has(id)) entries.push([id, false]);
689
+ const next = Object.fromEntries(entries);
690
+ const changes = !sameHidden(next, previous);
691
+ if (before) before.columnVisibility = changes ? previous : void 0;
692
+ return changes ? next : previous;
693
+ }
694
+ const hiddenIn = (map) => Object.keys(map).filter((id) => map[id] === false);
695
+ /** By which columns are hidden: an owner may order the map, or store `true`, as it likes. */
696
+ function sameHidden(map, target) {
697
+ const hidden = new Set(hiddenIn(map));
698
+ const wanted = hiddenIn(target);
699
+ return hidden.size === wanted.length && wanted.every((id) => hidden.has(id));
700
+ }
701
+ const takes = (map, { hide, show }) => hide.every((id) => map[id] === false) && show.every((id) => map[id] !== false);
643
702
  /** The state the answer sets, or a `CANNOT_APPLY` naming what the table cannot take. */
644
- function plan(table, data) {
703
+ function plan(table, data, sent) {
645
704
  if (Object.keys(data.aggregation).length > 0) cannotApply("aggregation: not supported");
646
705
  if ("columns" in data.pivoting) cannotApply("pivoting: not supported");
647
706
  if (data.chart) cannotApply("chart: not supported");
@@ -675,15 +734,40 @@ function plan(table, data) {
675
734
  }));
676
735
  for (const group of data.grouping) usable("grouping", group.column, columns.get(group.column), "groupable");
677
736
  if (on.grouping) next.grouping = data.grouping.map((group) => group.column);
737
+ if (data.hiddenColumns !== void 0) {
738
+ const change = visibility(data.hiddenColumns, sent, columns);
739
+ if (change) next.visibilityChange = change;
740
+ }
678
741
  if (data.select > 0 && !on.selection) cannotApply("select: row selection is off");
679
742
  return next;
680
743
  }
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 });
744
+ const call = (set) => set();
745
+ /** Runs each setter on its own and none after a reset; `failures` keeps what they threw, in order. */
746
+ function guarded(live) {
747
+ const failures = [];
748
+ const run = (set) => {
749
+ if (!live()) return;
750
+ try {
751
+ set();
752
+ } catch (error) {
753
+ failures.push(error);
754
+ }
755
+ };
756
+ return {
757
+ run,
758
+ failures
759
+ };
760
+ }
761
+ /** Writes `slices`; the visibility change records in `before` what it replaced. */
762
+ function write(table, slices, run = call, before) {
763
+ const { columnFilters, sorting, grouping, rowSelection, columnVisibility, visibilityChange } = slices;
764
+ if (columnFilters) run(() => table.setColumnFilters?.([...columnFilters]));
765
+ if ("globalFilter" in slices) run(() => table.setGlobalFilter?.(slices.globalFilter));
766
+ if (sorting) run(() => table.setSorting?.([...sorting]));
767
+ if (grouping) run(() => table.setGrouping?.([...grouping]));
768
+ if (rowSelection) run(() => table.setRowSelection?.({ ...rowSelection }));
769
+ if (columnVisibility) run(() => table.setColumnVisibility?.(() => ({ ...columnVisibility })));
770
+ if (visibilityChange) run(() => table.setColumnVisibility?.((previous) => changeOn(table, previous, visibilityChange, before)));
687
771
  }
688
772
  /** The current value of each slice `keys` names, with the page and the expanded rows. */
689
773
  function pick(table, keys) {
@@ -704,7 +788,8 @@ async function settle(table, target) {
704
788
  const deadline = Date.now() + SETTLE_TIMEOUT;
705
789
  const shows = () => {
706
790
  const state = table.store.get();
707
- return KEYS.every((key) => !(key in target) || same(state[key], target[key]));
791
+ const map = state.columnVisibility ?? {};
792
+ return KEYS.every((key) => !(key in target) || same(state[key], target[key])) && (!target.columnVisibility || sameHidden(map, target.columnVisibility)) && (!target.visibilityChange || takes(map, target.visibilityChange));
708
793
  };
709
794
  while (!shows()) {
710
795
  if (Date.now() > deadline) cannotApply("state: the table did not show the answer within 1 second");
@@ -715,21 +800,22 @@ const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
715
800
  /**
716
801
  * Puts `before` back. A change to filters, sorting or grouping sends the table to its first page
717
802
  * 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).
803
+ * Each setter runs on its own, so one that throws does not keep the others from putting their part
804
+ * back; none runs once `live` is false (a reset).
719
805
  */
720
806
  async function restore(table, before, live) {
721
807
  if (!live()) return;
722
- write(table, before);
808
+ const { run } = guarded(live);
809
+ write(table, before, run);
723
810
  try {
724
811
  await settle(table, before);
725
812
  } catch {}
726
813
  if (!live()) return;
727
814
  table.getRowModel();
728
815
  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 });
816
+ const { pagination, expanded } = before;
817
+ if (pagination) run(() => table.setPagination?.({ ...pagination }));
818
+ if (expanded !== void 0) run(() => table.setExpanded?.(expanded === true ? true : { ...expanded }));
733
819
  }
734
820
  /** The first `count` data rows in the order shown, inside groups too, as the grid selects them. */
735
821
  function firstRows(table, count) {
@@ -752,18 +838,21 @@ function firstRows(table, count) {
752
838
  * Applies all of the answer or none of it, and returns the state it replaced. Once `live` is false
753
839
  * (a reset), it writes nothing more, not even to put the view back.
754
840
  */
755
- async function apply(table, data, live) {
756
- const next = plan(table, data);
841
+ async function apply(table, data, sent, live) {
842
+ const next = plan(table, data, sent);
757
843
  const before = pick(table, {
758
844
  ...next,
759
845
  ...data.select > 0 ? { rowSelection: {} } : {}
760
846
  });
847
+ const unlessReset = (set) => {
848
+ if (live()) set();
849
+ };
761
850
  try {
762
- write(table, next);
851
+ write(table, next, unlessReset, before);
763
852
  await settle(table, next);
764
853
  if (data.select > 0 && live()) {
765
854
  const selected = { rowSelection: firstRows(table, data.select) };
766
- write(table, selected);
855
+ write(table, selected, unlessReset);
767
856
  await settle(table, selected);
768
857
  }
769
858
  } catch (cause) {
@@ -818,12 +907,13 @@ function createTableAssistant(table, options) {
818
907
  console.warn("Gridsay: no column has `filterFn: assistantFilter`, so the assistant cannot filter. Add `defaultColumn: assistantColumn` to the table's options.");
819
908
  }
820
909
  const columns = readColumns(table);
910
+ const grid = readSnapshot(table, columns, options.features?.columnVisibility === true);
821
911
  const body = {
822
912
  query,
823
913
  context: JSON.stringify(readContext(columns)),
824
914
  conversationId,
825
915
  options: promptOptionsOf(options),
826
- grid: readSnapshot(table, columns)
916
+ grid
827
917
  };
828
918
  const init = {
829
919
  method: "POST",
@@ -843,7 +933,10 @@ function createTableAssistant(table, options) {
843
933
  const data = await readResponse(response);
844
934
  stale();
845
935
  conversationId = data.conversationId;
846
- const before = await apply(table, data, live);
936
+ const before = await apply(table, data, {
937
+ columns,
938
+ grid
939
+ }, live);
847
940
  stale();
848
941
  last = before;
849
942
  }
@@ -870,10 +963,13 @@ function createTableAssistant(table, options) {
870
963
  undo() {
871
964
  if (!last || pending > 0) return false;
872
965
  const before = last;
873
- last = void 0;
874
- write(table, before);
875
966
  const own = generation;
876
- queue = queue.then(() => restore(table, before, () => own === generation)).catch(() => void 0);
967
+ const live = () => own === generation;
968
+ const { run, failures } = guarded(live);
969
+ write(table, before, run);
970
+ if (failures.length > 0) throw failures[0];
971
+ last = void 0;
972
+ queue = queue.then(() => restore(table, before, live)).catch(() => void 0);
877
973
  return true;
878
974
  },
879
975
  reset() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gridsay/tanstack-table",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Gridsay assistant for TanStack Table v9: ask a table in plain words. Not affiliated with TanStack.",
5
5
  "keywords": [
6
6
  "gridsay",
@@ -36,7 +36,7 @@
36
36
  "dist"
37
37
  ],
38
38
  "dependencies": {
39
- "@gridsay/core": "0.1.1"
39
+ "@gridsay/core": "0.2.0"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@tanstack/table-core": "^9.3.1",