@gridsay/tanstack-table
v0.2.0
Published
Gridsay assistant for TanStack Table v9: ask a table in plain words. Not affiliated with TanStack.
Maintainers
Readme
@gridsay/tanstack-table
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. More: gridsay.com/product/tanstack-table and gridsay.com/docs/tanstack-table.
TanStack Table is headless, and so is this package: it ships no interface. You bring the input box (step 4).
Before you start
- TanStack Table v9 only. The peer range is
@tanstack/table-core^9.3.1, and 9.3.1 is the version the tests run on. v8 is not supported, nor are Material React Table and Mantine React Table, which are built on v8. - React first. The hook in
@gridsay/tanstack-table/reactneeds React 18 or later. The core entry,@gridsay/tanstack-table, works with any v9 adapter, tested with React only. - A Gridsay secret key. Create one in the Gridsay console, under Keys. It stays on your server.
From nothing to a first answer
1. Install
npm install @gridsay/tanstack-table @tanstack/react-table@^9.3.12. Add your key
In .env.local, never in the browser:
GRIDSAY_SECRET_KEY=your-secret-key3. Add a server route
The route adds your secret key and refuses callers who are not signed in. Anyone who can reach it spends your credits, so keep the check. This one is for Next.js, at app/api/tanstack-table/route.ts; any server can do the same.
// Replace with your app's own sign-in check, such as a session cookie. As written it refuses everyone.
const isSignedIn = async (_request: Request) => false;
export async function POST(request: Request) {
if (!(await isSignedIn(request))) {
return Response.json(
{ ok: false, code: 'unauthenticated_user', message: 'Sign in to use the assistant.' },
{ status: 401 },
);
}
const response = await fetch('https://api.gridsay.com/api/v1/datagrid/prompt', {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-api-key': process.env.GRIDSAY_SECRET_KEY ?? '' },
body: await request.text(),
redirect: 'error', // never send the key on to a redirect target
});
return new Response(response.body, { status: response.status, headers: { 'content-type': 'application/json' } });
}To try it on your own machine, let the route through only in development, as the example's authorize.ts does. Put your real check back before you deploy.
const isSignedIn = async (_request: Request) => process.env.NODE_ENV === 'development';4. Set up the table, the hook and an input
Register the features the assistant may change, put assistantColumn on the columns, and call the hook. The input is yours: this one is a form with a text box.
'use client';
import {
assistantColumn,
assistantGroupedRowModel,
useTableAssistant,
} from '@gridsay/tanstack-table/react';
import {
columnFilteringFeature,
columnGroupingFeature,
createColumnHelper,
createExpandedRowModel,
createFilteredRowModel,
createSortedRowModel,
rowExpandingFeature,
rowSelectionFeature,
rowSortingFeature,
tableFeatures,
useTable,
} from '@tanstack/react-table';
import { useState } from 'react';
// The assistant changes only what you register here.
const features = tableFeatures({
columnFilteringFeature,
filteredRowModel: createFilteredRowModel(),
rowSortingFeature,
sortedRowModel: createSortedRowModel(),
columnGroupingFeature,
groupedRowModel: assistantGroupedRowModel(), // in place of createGroupedRowModel()
rowExpandingFeature,
expandedRowModel: createExpandedRowModel(),
rowSelectionFeature,
});
type Order = { customer: string; country: string; status: string; total: number; placedAt: Date };
const columnHelper = createColumnHelper<typeof features, Order>();
const columns = columnHelper.columns([
columnHelper.accessor('customer', { header: 'Customer' }),
columnHelper.accessor('country', { header: 'Country' }),
columnHelper.accessor('status', {
header: 'Status',
meta: { assistant: { type: 'singleSelect', options: ['open', 'paid', 'refunded'] } },
}),
columnHelper.accessor('total', {
header: 'Total',
meta: { assistant: { description: 'Order total in euros' } },
}),
columnHelper.accessor('placedAt', { header: 'Placed' }),
]);
export function Orders({ data }: { data: Order[] }) {
const table = useTable({
features,
columns,
data,
defaultColumn: assistantColumn, // the line that lets the assistant filter and sort
initialState: { expanded: true }, // groups the assistant makes show their rows...
autoResetExpanded: false, // ...and stay open after the next answer
});
const { ask, undo, canUndo, pending, error } = useTableAssistant(table, { url: '/api/tanstack-table' });
const [question, setQuestion] = useState('');
return (
<>
<form
onSubmit={async (event) => {
event.preventDefault();
if (await ask(question)) setQuestion('');
}}
>
<input
aria-label="Ask about the orders"
value={question}
onChange={(event) => setQuestion(event.target.value)}
readOnly={pending}
placeholder="Orders over 500 from Germany, newest first"
/>
<button type="submit" disabled={pending || !question.trim()}>
Ask
</button>
<button type="button" disabled={pending || !canUndo} onClick={() => undo()}>
Undo
</button>
</form>
{error ? <p role="alert">{error.message}</p> : null}
<table>
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th key={header.id}>
<table.FlexRender header={header} />
</th>
))}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.map((row) =>
row.getIsGrouped() ? (
<tr key={row.id}>
<th colSpan={columns.length}>
{String(row.groupingValue)} ({row.getLeafRows().length})
</th>
</tr>
) : (
<tr key={row.id} className={row.getIsSelected() ? 'selected' : undefined}>
{row.getAllCells().map((cell) => (
<td key={cell.id}>
<table.FlexRender cell={cell} />
</td>
))}
</tr>
),
)}
</tbody>
</table>
</>
);
}Save it as app/orders.tsx and render <Orders data={orders} /> from app/page.tsx, with your own orders.
5. Ask
Run your app and type "Orders over 500 from Germany, newest first". The table filters and sorts, and ask resolves true. Each answer's conversation goes with the next question, so a follow-up such as "only the ones over 1000" builds on the last answer. Undo puts back what the last answer changed.
6. See a refusal
Ask "make a chart of orders by country". The assistant cannot chart, so it declines: the table is unchanged, ask resolves false, and error holds a GridsayError: its message is the assistant's own sentence, which you can show your user, and the rest is for you: status 422, code query_not_understood.
import { CANNOT_APPLY_CODE, type GridsayError } from '@gridsay/tanstack-table/react';
// `error` is what `useTableAssistant` returns when a question failed.
export function report(error: GridsayError) {
console.warn(error.status, error.code, error.retryAfter, error.detail);
if (error.code === CANNOT_APPLY_CODE) console.warn('Not applied:', error.detail);
}A caller your route turns away gets status 401, code unauthenticated_user and "Sign in to use the assistant."
The hook
useTableAssistant(table, options) returns:
ask(question): resolvestruewhen the answer is on the table,falsewhen it is not. Thenerrorsays why, except afterreset().undo(): puts back what the last answer changed and returnstrue. It does nothing and returnsfalsewhen 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.reset(): starts a new conversation. The next question does not build on earlier ones,undoforgets, 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.canUndo: true after an applied answer; a refusal leaves it as it was. It isfalsewhile a question is pending.pending: true while a question is being answered.error: why the last question was not answered, as aGridsayError, ornull. Showerror.messageto your user; readcode,status,retryAfteranddetailto tell failures apart.
error clears when the next ask starts, when an undo puts something back, and on reset(). The conversation lasts as long as the component stays mounted.
Without React, createTableAssistant(table, options) from @gridsay/tanstack-table returns ask, undo, reset and a read-only canUndo. Read assistant.canUndo when you need it rather than destructuring it once. ask rejects with a GridsayError; after reset() a question still waiting rejects with code reset.
import { createTableAssistant, GridsayError } from '@gridsay/tanstack-table';
// `table` is the table your adapter made, with the features and columns of step 4.
const assistant = createTableAssistant(table, { url: '/api/tanstack-table' });
try {
await assistant.ask('orders over 500 from Germany, newest first');
} catch (error) {
if (!(error instanceof GridsayError)) throw error;
console.warn(error.code, error.message); // show error.message to your user
}
assistant.undo(); // false when there is nothing to undo, or while a question is pendingOptions
| Option | Meaning |
|---|---|
| url | Required. Where the question is posted: your route. To call Gridsay from the browser with a publishable key, use https://api.gridsay.com/api/v1/datagrid/prompt; the key needs your site's origin and a way to identify end users, both set in the console. |
| headers | Extra request headers, or a function that returns them. |
| publishableKey, getToken | For calling Gridsay from the browser. publishableKey is sent as x-api-key; getToken returns the signed-in user's token, sent as a bearer token. It may return null or undefined, and may be sync or async, so an auth library's getToken can be passed directly. |
| additionalContext | Extra text for the assistant about your table. |
| privateMode | Sent to Gridsay as options.privateMode. |
| referenceId | Your id for the end user. |
| 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. |
Errors
Show error.message to your user. Everything else on a GridsayError is for you: code, status when a response arrived, retryAfter, detail, and cause. Compare codes, never messages: the messages may change. Each helper code is an exported constant, such as CANNOT_APPLY_CODE and RESET_CODE.
What Gridsay answers, with status and code:
| Error | Cause | Fix |
|---|---|---|
| 400 invalid_request | Gridsay could not read the request. detail names the field. | Forward the body unchanged from your route. |
| 401 unauthenticated_user | Not signed in, whoever noticed. Your route turned the caller away (a 401 with no code of its own), getToken gave nothing (null, undefined or an empty string) or threw (then there is no status, and nothing was sent), or Gridsay did not accept the end user's token. | Sign the user in, or return their token from getToken. |
| 413 context_too_large | The question, the columns and the table's state are more than the assistant accepts. detail says which limit. | Send fewer columns, shorter descriptions, fewer examples or fewer singleSelect options. Not charged. |
| 422 query_not_understood | The assistant declined the question, for example a total, a pivot, a chart or something the table does not allow. message is its own sentence, and the table is unchanged. | Show the message; the user rewords. Charged. |
| 429 rate_limited | A limit on your key or your user was reached, or the assistant is busy. | Wait retryAfter seconds when it is set, then ask again. Not charged. |
| 502 or 503 upstream_unavailable | The model service failed or its answer was unusable (502), or the service could not take the question (503). | Ask again; if it persists, detail says what to check. Not charged. |
Gridsay also answers 401 invalid_api_key for a key it does not accept, 402 for a plan that cannot cover the question, and 403 for a site the key does not allow or a publishable key with no sign-in method set up; detail says what to change.
What the helper itself reports, with no request to blame:
| code | When | Fix |
|---|---|---|
| unexpected_error | Something in your page threw: your headers function, or the table while it was being read (an accessor function with no id and no string header, say). cause holds it. A table that throws while taking the answer is cannot_apply instead, with the detail state: the table threw on the answer. | Fix what cause shows. |
| connection_failed | The request did not complete: no network, or the connection broke while the answer was read. | Ask again. |
| 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. |
| invalid_answer | The response was not an answer the helper can read. | Return Gridsay's body and status from your route as they came. |
| 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. |
| reset | reset() was called while the question was waiting. The hook ignores it. | Nothing: no answer is wanted. |
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.
What an answer changes
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:
| Answer | Needs on the table |
|---|---|
| Filters | columnFilteringFeature and filteredRowModel, and not manualFiltering |
| Sorting | rowSortingFeature and sortedRowModel, or manualSorting |
| Grouping | columnGroupingFeature and assistantGroupedRowModel(), or manualGrouping |
| Hidden columns | features: { columnVisibility: true } in the options, columnVisibilityFeature, and a column that can hide |
| Top rows selected | rowSelectionFeature, and enableRowSelection not false |
Whatever is missing is reported to Gridsay as switched off, and a question that needs it gets a sentence back.
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.
- Filtering runs in the browser. A table that filters on its server (
manualFiltering) cannot be filtered by the assistant. WithmanualSortingormanualGroupingthe assistant sets the sorting or grouping state, and fetching the rows in that order is your code. - 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.
- Hidden columns are off unless you switch them on:
features: { columnVisibility: true }in the options ofuseTableAssistantorcreateTableAssistant. WithcolumnVisibilityFeatureregistered 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 withenableHiding: falsestays shown or hidden as it is, and withenableHiding: falseon 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. - Render the visible columns, with
getVisibleLeafColumns()androw.getVisibleCells():getAllLeafColumns()andgetAllCells()show hidden columns too. - 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. - State you own (React state passed as
statewithonSortingChange, say) must show the answer within one second. Otherwise the table is put back andaskrejects withcannot_apply. - Top rows are the first rows of the table in the order shown, inside groups too.
- TanStack's own grouped row model does not group for the assistant; use
assistantGroupedRowModel(). 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.
Columns
The assistant sees the columns that have an accessor. Display columns are not sent, and an answer that names one is not applied.
- An accessor function needs an
id, or a stringheaderthat becomes the id. TanStack itself refuses one with neither. assistantColumnisfilterFn: assistantFilter,sortFn: assistantSortandsortUndefined: false. Set it asdefaultColumnor spread it into a column. If no column has the filter function, the helper warns once in the browser console.- A column with its own
filterFnorsortFnis left to you, and so is one withenableColumnFilter,enableSortingorenableGroupingset tofalse. The assistant is told it cannot filter, sort or group by it. meta.assistantis{ type, description, options, examples }, all optional.typeisstring,number,date,dateTime,booleanorsingleSelect; without one it is read from the first 100 rows, and anything unclear isstring. AsingleSelectneeds itsoptions: values, or{ value, label }.examplesare sent only when you set them: a list, ortruefor up to five values from the rows.- 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 theexamplesyou ask for and the options you list.
Versions
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.
Licence
This package is MIT licensed. TanStack Table is MIT-licensed open source by its own maintainers. Gridsay is an independent product, not affiliated with or endorsed by the TanStack Table project.
A runnable example: examples/tanstack-table.
