@constructive-io/sheets 0.14.1 → 0.15.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.
Files changed (60) hide show
  1. package/README.md +231 -157
  2. package/dist/advanced.cjs +7192 -3840
  3. package/dist/advanced.cjs.map +1 -1
  4. package/dist/advanced.d.cts +2 -2
  5. package/dist/advanced.d.ts +2 -2
  6. package/dist/advanced.js +5 -5
  7. package/dist/auth.cjs.map +1 -1
  8. package/dist/auth.js +3 -3
  9. package/dist/chunk-CJ4PRA64.js +312 -0
  10. package/dist/chunk-CJ4PRA64.js.map +1 -0
  11. package/dist/chunk-II3MSNRO.js +18 -0
  12. package/dist/chunk-II3MSNRO.js.map +1 -0
  13. package/dist/{chunk-BYAYBXVB.js → chunk-J7KK4UWI.js} +6 -6
  14. package/dist/chunk-MBSHDF55.js +839 -0
  15. package/dist/chunk-MBSHDF55.js.map +1 -0
  16. package/dist/chunk-MOFFS5WQ.js +128 -0
  17. package/dist/chunk-MOFFS5WQ.js.map +1 -0
  18. package/dist/chunk-VCBY2AMT.js +8920 -0
  19. package/dist/chunk-VCBY2AMT.js.map +1 -0
  20. package/dist/{chunk-YJZFHL2D.js → chunk-ZOQDSOMO.js} +50 -312
  21. package/dist/chunk-ZOQDSOMO.js.map +1 -0
  22. package/dist/date-editor-ORCB43ZM.js +346 -0
  23. package/dist/date-editor-ORCB43ZM.js.map +1 -0
  24. package/dist/{grid-cell-types-C2-ocDS7.d.cts → grid-cell-types-YNIVK4hN.d.cts} +71 -18
  25. package/dist/{grid-cell-types-C2-ocDS7.d.ts → grid-cell-types-YNIVK4hN.d.ts} +71 -18
  26. package/dist/index.cjs +22733 -12052
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +1432 -266
  29. package/dist/index.d.ts +1432 -266
  30. package/dist/index.js +12688 -6097
  31. package/dist/index.js.map +1 -1
  32. package/dist/sheets-context-Bb7ZoNBg.d.cts +436 -0
  33. package/dist/sheets-context-CPuf31LS.d.ts +436 -0
  34. package/dist/testing.cjs +1170 -589
  35. package/dist/testing.cjs.map +1 -1
  36. package/dist/testing.d.cts +80 -11
  37. package/dist/testing.d.ts +80 -11
  38. package/dist/testing.js +778 -147
  39. package/dist/testing.js.map +1 -1
  40. package/package.json +4 -5
  41. package/dist/chunk-4EZ6A23C.js +0 -44
  42. package/dist/chunk-4EZ6A23C.js.map +0 -1
  43. package/dist/chunk-6Y7CZ5VS.js +0 -168
  44. package/dist/chunk-6Y7CZ5VS.js.map +0 -1
  45. package/dist/chunk-BGL6EBTE.js +0 -446
  46. package/dist/chunk-BGL6EBTE.js.map +0 -1
  47. package/dist/chunk-ER3FIDK7.js +0 -4383
  48. package/dist/chunk-ER3FIDK7.js.map +0 -1
  49. package/dist/chunk-GZM2CSTR.js +0 -279
  50. package/dist/chunk-GZM2CSTR.js.map +0 -1
  51. package/dist/chunk-X7DHTSOX.js +0 -21
  52. package/dist/chunk-X7DHTSOX.js.map +0 -1
  53. package/dist/chunk-YJZFHL2D.js.map +0 -1
  54. package/dist/date-editor-G26WKILO.js +0 -358
  55. package/dist/date-editor-G26WKILO.js.map +0 -1
  56. package/dist/map-picker-ZUGGOIZS.js +0 -290
  57. package/dist/map-picker-ZUGGOIZS.js.map +0 -1
  58. package/dist/sheets-context-CHUVJCff.d.ts +0 -245
  59. package/dist/sheets-context-C_MkTxXm.d.cts +0 -245
  60. /package/dist/{chunk-BYAYBXVB.js.map → chunk-J7KK4UWI.js.map} +0 -0
package/dist/index.d.ts CHANGED
@@ -1,58 +1,99 @@
1
1
  import * as react from 'react';
2
- import react__default, { Component, ReactNode, ErrorInfo } from 'react';
3
- import { b as SheetsConfig, S as SheetsExecuteFn, C as CellProps, c as CellTypeDefinition, d as SheetsCellRenderContext, e as CellTypeMatchInput, f as SheetsScopeKey, g as SheetsFileValue, a as SheetsUploadFn, h as SheetsBackendAdapter } from './sheets-context-CHUVJCff.js';
4
- export { A as AdapterListQuery, i as AdapterListResult, j as AdapterPageInfo, k as AdapterTableContext, l as CellColumnDescriptor, m as CellTypePlugin, n as SheetsAuthEmbedded, o as SheetsAuthStandalone, p as SheetsContext, q as SheetsContextValue, r as SheetsLogger, s as SheetsUploadResult, t as createSheetsExecute, u as createSheetsUpload, v as defineCellType, w as useSheetsContext } from './sheets-context-CHUVJCff.js';
2
+ import react__default, { ReactNode, Component, ErrorInfo } from 'react';
3
+ import { S as SheetsExecuteFn, b as SheetsConfig, C as CellProps, c as CellTypeDefinition, d as SheetsCellRenderContext, e as CellTypeMatchInput, f as SheetsScopeKey, R as ResolvedUploadChoices, g as SheetsBackendAdapter, P as ProcessingPolicy, h as SheetsStorageTransport } from './sheets-context-CPuf31LS.js';
4
+ export { A as AdapterListQuery, i as AdapterListResult, j as AdapterPageInfo, k as AdapterTableContext, l as AdapterTableModelOptions, m as CellColumnDescriptor, n as CellTypePlugin, K as KeyValueStore, o as SheetsAuthEmbedded, p as SheetsAuthStandalone, q as SheetsContext, r as SheetsContextValue, s as SheetsExecuteOptions, t as SheetsFileValue, u as SheetsLogger, v as SheetsMapConfig, w as SheetsMapPlaceSearch, x as SheetsMapTiles, y as SheetsPartialResult, z as SheetsResponseError, B as SheetsStoredView, D as SheetsUploadColumnConfig, E as SheetsUploadConfig, a as SheetsUploadFn, F as SheetsUploadProcessingConfig, G as SheetsUploadResult, H as SheetsViewStorage, I as SheetsViewStorageScope, J as createKeyValueViewStorage, L as createMemoryViewStorage, M as createSheetsExecute, N as createSheetsUpload, O as defineCellType, Q as partialResultOf, T as responseErrorsOf, U as useSheetsContext } from './sheets-context-CPuf31LS.js';
5
5
  import { StoreApi } from 'zustand';
6
- import { R as RelationInfo, d as RelationInfoSlice, E as EditorProps, e as SheetsRowIdentifier, F as FieldMetadata, S as SheetsCell, D as DraftSubmitResult, f as CellRegistryEntry, b as CellType, g as CellRenderer, h as CellPlugin, i as ColumnSchema } from './grid-cell-types-C2-ocDS7.js';
7
- export { B as BaseCellProps, c as CellCategory, j as CellValue, k as FieldMetadata, l as RelationKind, m as RowData, a as SheetsCellKind, n as SheetsRowIdentityResolution, T as TableSchema, o as buildRelationInfoFromMeta, p as canRunSheetsMutation, q as getSheetsWriteCapability, r as isImageField, s as resolveCellType, t as resolveSheetsIdentifier, u as resolveSheetsRowIdentity, v as sheetsIdentifierCacheKey, w as sheetsIdentifierToWhere, x as sheetsRowKey } from './grid-cell-types-C2-ocDS7.js';
6
+ import { R as RelationInfo, d as SheetsRowIdentifier, E as EditorProps, S as SheetsCell, F as FieldMetadata, D as DraftSubmitResult, e as CellRegistryEntry, b as CellType, f as CellRenderer, g as CellPlugin, h as ColumnSchema } from './grid-cell-types-YNIVK4hN.js';
7
+ export { B as BaseCellProps, c as CellCategory, i as CellValue, j as FieldMetadata, k as RelationKind, l as RowData, a as SheetsCellKind, m as SheetsRowIdentityResolution, T as TableSchema, n as canRunSheetsMutation, o as getSheetsWriteCapability, p as isImageField, r as relationInfoFromModel, q as resolveCellType, s as resolveSheetsIdentifier, t as resolveSheetsRowIdentity, u as sheetsIdentifierCacheKey, v as sheetsIdentifierToRowKey, w as sheetsIdentifierToWhere, x as sheetsRowKey } from './grid-cell-types-YNIVK4hN.js';
8
+ import { TableModel, RelationModel, SortSpec, TableKey, ColumnModel, FieldSelection, MutationOptions, PageInfo, ColumnOption, MetaschemaTable, MetaQuery, QueryOptions } from '@constructive-io/data';
9
+ export { ArgumentModel, CELL_ERRORS_KEY, ColumnFileModel, ColumnFilterModel, ColumnModel, ColumnOption, ColumnSemantic, ColumnSortModel, ColumnValueKind, ColumnValueModel, ColumnWriteModel, ConstructiveError, CreateOperationModel, DeleteOperationModel, DisplayFieldOverrides, DisplayFieldsModel, FilterOperatorModel, InputFieldModel, InputValueModel, ListOperationModel, ModelIssue, ModelIssueCode, RELATION_TOTAL_COUNTS_KEY, RelationJunctionModel, RelationKeyPair, RelationModel, RelationModelKind, RelationTargetModel, SortDirection, SortSpec, TableKey, TableModel, TableModelError, TableModelErrorCode, TableOperations, TableSearchModel, TableStorageModel, TableStorageUploadModel, UpdateOperationModel, readCellError, readRelationTotalCount, resolveDisplayFields } from '@constructive-io/data';
8
10
  import * as _tanstack_react_query from '@tanstack/react-query';
9
11
  import { UseQueryResult } from '@tanstack/react-query';
10
- import { FieldSelection, MutationOptions, PageInfo, MetaQuery, QueryOptions, Filter, MetaTable as MetaTable$1 } from '@constructive-io/data';
11
- export { ConstructiveError } from '@constructive-io/data';
12
12
  import { z } from 'zod';
13
13
  export { SheetsAuthGate, SheetsAuthGateProps, useSheetsForgotPassword, useSheetsLogin, useSheetsRegister, useSheetsResetPassword } from './auth.js';
14
14
  import 'graphql';
15
15
 
16
- interface SheetsProviderProps {
17
- config: SheetsConfig;
18
- children: React.ReactNode;
19
- }
20
- declare function SheetsProvider({ config, children }: SheetsProviderProps): react.JSX.Element;
21
-
22
16
  /**
23
- * Presigned-URL upload helpers for the sheets cell-upload seam.
17
+ * The FALLBACK upload path: shape discovery over the full introspection.
24
18
  *
25
- * Replaces the legacy multipart `<endpoint>/upload` POST. The flow is:
26
- * 1. SHA-256 hash the file bytes (Web Crypto, zero new deps)
27
- * 2. Call the presigned upload op (discovered via introspection) to get a
28
- * presigned PUT url + fileId
29
- * 3. PUT the raw bytes to that url (only Content-Type, NO Authorization)
30
- * 4. Return the file projection and try to resolve an optional download URL
19
+ * Used only for a storage service whose `_meta` names no upload mutation (an
20
+ * older server), and by hosts that call `createSheetsUpload` directly. It reads
21
+ * the full introspection once per endpoint and finds root mutations with the
22
+ * upload input and payload shape, and the fields that resolve a download URL by
23
+ * file id. The model-driven path in `uploads/` replaces all of this when the
24
+ * storage `_meta` names the upload mutation.
25
+ */
26
+
27
+ /**
28
+ * Resolve a file's signed `downloadUrl` by id, for callers outside the grid
29
+ * (a storage browser's copy link). Returns null on any failure.
30
+ */
31
+ declare function resolveDownloadUrl(execute: SheetsExecuteFn, endpoint: string, fileId: string): Promise<string | null>;
32
+
33
+ /**
34
+ * The presigned upload protocol, shared by every upload path.
31
35
  *
32
- * The server confirms PUTs and expires rows that never received one.
36
+ * 1. Hash the file (SHA-256, Web Crypto). The server needs the hash before it
37
+ * issues the URL: it names the object and is signed into the PUT.
38
+ * 2. Ask the upload mutation for a presigned PUT URL. A `deduplicated` answer
39
+ * means the bytes are already stored: no PUT.
40
+ * 3. PUT the bytes with the payload's `uploadHeaders`, unchanged (the URL is
41
+ * signed over them: Content-Type, the checksum, the file row id). No
42
+ * Authorization header; the signature is in the URL.
43
+ * 4. An expired URL is requested again once.
33
44
  *
34
- * Runtime introspection finds root mutations with the presigned upload shape
35
- * and prefers `uploadAppFile` when multiple storage planes are exposed.
45
+ * The server confirms the PUT later (a background job) and expires rows that
46
+ * never received one, so a cancelled or failed PUT leaves nothing behind.
36
47
  *
37
- * The downloadUrl-by-id field is likewise shape-discovered. Three read shapes,
38
- * preferred in order: the inflected singular `appFile(id:)`; a filtered
39
- * connection `appFiles(where:{id:{equalTo:$id}}){ nodes { downloadUrl } }`
40
- * (Relay-disabled backends); and the Relay `node(nodeId:)` fallback.
48
+ * The model-driven path (`uploads/`) names the upload mutation from the storage
49
+ * service's `_meta`. The shape discovery in `sheets-upload-discovery.ts` is the
50
+ * FALLBACK for a storage service whose `_meta` names no upload mutation.
41
51
  */
42
-
43
52
  /**
44
- * Resolve a file's signed `downloadUrl` by id — the public entry point for callers
45
- * OUTSIDE the upload flow (e.g. a storage browser fetching the preview/copy link for
46
- * an already-uploaded file).
47
- *
48
- * `downloadUrl` is a Grafast computed field, so it cannot be selected through the
49
- * runtime query builder (`buildSelect` intersects the select against pg columns and
50
- * drops computed fields). This discovers the by-id field using cached introspection
51
- * and reads it through the SAME resolver the upload path uses. Returns null on any
52
- * failure — a missing url is not exceptional for the caller (it just disables
53
- * copy/download), so the throwing internals are swallowed here.
53
+ * The file projection the upload mutation returns: what an image or upload
54
+ * column stores. The server may add keys (image `versions`); they are kept as returned.
54
55
  */
55
- declare function resolveDownloadUrl(execute: SheetsExecuteFn, endpoint: string, fileId: string): Promise<string | null>;
56
+ interface FileProjection {
57
+ id: string;
58
+ key: string;
59
+ bucket_id?: string;
60
+ mime?: string;
61
+ size?: number;
62
+ filename?: string;
63
+ /** Durable public URL; set only for a public bucket. */
64
+ url?: string;
65
+ }
66
+ /**
67
+ * The file row the storage service created for an upload that did not finish
68
+ * (a refused or blocked PUT, a cancel, an answer without an upload URL). Sheets
69
+ * never deletes it: the storage service expires a row that never received its
70
+ * bytes. A host with its own cleanup rule reads it from the error.
71
+ */
72
+ interface UnfinishedUpload {
73
+ /** Id of the files table row. */
74
+ fileId: string;
75
+ /** GraphQL type name of the files table, or null when the upload path does not know it. */
76
+ filesType: string | null;
77
+ /** `TableModel.key` of the files table, or null when the upload path does not know it. */
78
+ filesTableKey: string | null;
79
+ }
80
+ /** The file row an upload error left on the storage service, or null when the server issued none. */
81
+ declare function unfinishedUploadOf(error: unknown): UnfinishedUpload | null;
82
+ interface UploadProgressEvent {
83
+ loaded: number;
84
+ total: number;
85
+ percentage: number;
86
+ }
87
+ interface TransferOptions {
88
+ onProgress?: (progress: UploadProgressEvent) => void;
89
+ signal?: AbortSignal;
90
+ }
91
+
92
+ interface SheetsProviderProps {
93
+ config: SheetsConfig;
94
+ children: React.ReactNode;
95
+ }
96
+ declare function SheetsProvider({ config, children }: SheetsProviderProps): react.JSX.Element;
56
97
 
57
98
  type DraftRowStatus = 'idle' | 'saving' | 'error';
58
99
  interface DraftRow {
@@ -123,10 +164,195 @@ interface SheetsAuthState {
123
164
  setAuthenticated: (token: string, expiresAt: string, identityKey?: string | null) => void;
124
165
  setUnauthenticated: () => void;
125
166
  }
126
- type SheetsStoreState = DraftRowsSlice & RelationInfoSlice & SheetsAuthState;
167
+ type SheetsStoreState = DraftRowsSlice & SheetsAuthState;
127
168
  declare function useSheetsStore<T>(selector: (state: SheetsStoreState) => T): T;
128
169
  declare function useSheetsStoreApi(): StoreApi<SheetsStoreState>;
129
170
 
171
+ /**
172
+ * The filter, sort, search and column layout of one grid, as one serializable
173
+ * value.
174
+ *
175
+ * Columns and relations are named by their field name in the table model, so a
176
+ * host can store the value (a saved view) and load it later. Load a stored value
177
+ * through `validateSheetsViewState`: it drops every part the current model no
178
+ * longer supports and says what it dropped, and it upgrades a version 1 value
179
+ * (no column layout) to the current version.
180
+ */
181
+ /** Version of the state shape. Version 2 added `columns`. */
182
+ declare const SHEETS_VIEW_STATE_VERSION = 2;
183
+ /** How the children of a filter group combine. */
184
+ type SheetsFilterLogic = 'and' | 'or';
185
+ /**
186
+ * A filter value as the user entered it: text (exact decimal text for big
187
+ * numbers, ISO text for dates, times and timestamps), a boolean, a list of
188
+ * values for list operators, field values for an operator that takes an object,
189
+ * or null for an operator without a value.
190
+ */
191
+ type SheetsFilterValue = string | boolean | readonly string[] | Readonly<Record<string, string>> | null;
192
+ /** A condition on one column. */
193
+ interface SheetsColumnCondition {
194
+ kind: 'column';
195
+ /** Stable id within the state. */
196
+ id: string;
197
+ /** Column field name. */
198
+ column: string;
199
+ /** Operator name the column's filter really has, for example `includesInsensitive`. */
200
+ operator: string;
201
+ value: SheetsFilterValue;
202
+ }
203
+ /** What a relation condition tests. */
204
+ type SheetsRelationTest = 'any' | 'none' | 'labelContains';
205
+ /** A condition on one relation. */
206
+ interface SheetsRelationCondition {
207
+ kind: 'relation';
208
+ /** Stable id within the state. */
209
+ id: string;
210
+ /** Relation field name. */
211
+ relation: string;
212
+ /** `any`: has a linked record; `none`: has no linked record; `labelContains`: a linked record's label contains `value`. */
213
+ test: SheetsRelationTest;
214
+ /** Text for `labelContains`, otherwise null. */
215
+ value: string | null;
216
+ }
217
+ type SheetsFilterCondition = SheetsColumnCondition | SheetsRelationCondition;
218
+ /** A group of conditions and groups. */
219
+ interface SheetsFilterGroup {
220
+ kind: 'group';
221
+ /** Stable id within the state. */
222
+ id: string;
223
+ logic: SheetsFilterLogic;
224
+ children: readonly SheetsFilterNode[];
225
+ }
226
+ type SheetsFilterNode = SheetsFilterGroup | SheetsFilterCondition;
227
+ type SheetsSortDirection = 'asc' | 'desc';
228
+ /** One sort key. The first key in a list sorts first. */
229
+ interface SheetsSortKey {
230
+ /** Column field name. */
231
+ column: string;
232
+ direction: SheetsSortDirection;
233
+ }
234
+ /** Row heights the grid offers. */
235
+ type SheetsRowHeight = 'short' | 'medium' | 'tall' | 'extraTall';
236
+ /** Which columns show, in what order, how wide, how many stay in place, and how tall rows are. */
237
+ interface SheetsColumnLayout {
238
+ /**
239
+ * Grid column keys (column and relation field names) in display order. Keys
240
+ * the table has but this list does not name follow, in the table's order, so a
241
+ * new column shows up at the end.
242
+ */
243
+ order: readonly string[];
244
+ /** Grid column keys that are hidden. */
245
+ hidden: readonly string[];
246
+ /** How many leading visible columns stay in place while the grid scrolls sideways. */
247
+ frozenCount: number;
248
+ /** Column widths in pixels, by grid column key. A column without an entry keeps its default width. */
249
+ widths: Readonly<Record<string, number>>;
250
+ rowHeight: SheetsRowHeight;
251
+ }
252
+ /** Filter, sort, search and column layout of one grid. */
253
+ interface SheetsViewState {
254
+ version: typeof SHEETS_VIEW_STATE_VERSION;
255
+ filters: SheetsFilterGroup;
256
+ sort: readonly SheetsSortKey[];
257
+ /** Search text; empty for no search. */
258
+ search: string;
259
+ columns: SheetsColumnLayout;
260
+ }
261
+ /** Why the validator dropped part of a state. */
262
+ type SheetsViewStateDropReason = 'invalid-shape' | 'unknown-column' | 'column-not-filterable' | 'unknown-operator' | 'unknown-option' | 'unknown-relation' | 'relation-test-unavailable' | 'column-not-sortable' | 'duplicate-sort' | 'search-unavailable';
263
+ /** One part of a state that the current model does not support. */
264
+ interface SheetsViewStateDrop {
265
+ /** Which part of the state. */
266
+ part: 'filters' | 'sort' | 'search' | 'columns';
267
+ /** Column or relation the dropped part named, or null. */
268
+ target: string | null;
269
+ reason: SheetsViewStateDropReason;
270
+ /** Human-readable explanation, safe to show to the user. */
271
+ message: string;
272
+ }
273
+ /** A state the model supports, and what was dropped to get it. */
274
+ interface SheetsViewStateValidation {
275
+ state: SheetsViewState;
276
+ dropped: readonly SheetsViewStateDrop[];
277
+ }
278
+
279
+ interface SheetsOpenTableRequest {
280
+ /** `TableModel.key` of the table to open. */
281
+ tableKey: string;
282
+ /** GraphQL type name of that table. */
283
+ tableName: string;
284
+ /**
285
+ * The rows the user was looking at (the junction rows of this record), as a filter
286
+ * group a host passes straight to `<Sheets filters>`; null when no exact filter can be
287
+ * built, in which case the host opens the table unfiltered.
288
+ */
289
+ filters: SheetsFilterGroup | null;
290
+ /** Why the editor asks: the links live in a table with more fields than the editor can fill. */
291
+ reason: 'linked-records';
292
+ }
293
+ type SheetsOpenTableHandler = (request: SheetsOpenTableRequest) => void;
294
+ declare const SheetsOpenTableContext: react.Context<SheetsOpenTableHandler | null>;
295
+ /** A request to show one linked record, for example in the record panel's navigation stack. */
296
+ interface SheetsOpenRecordRequest {
297
+ /** `TableModel.key` of the record's table. */
298
+ tableKey: string;
299
+ /** GraphQL type name of that table. */
300
+ tableName: string;
301
+ /** Primary-key values of the record, by field name. */
302
+ key: Readonly<Record<string, unknown>>;
303
+ /** The record's label, for a title while it loads. */
304
+ label: string;
305
+ }
306
+ type SheetsOpenRecordHandler = (request: SheetsOpenRecordRequest) => void;
307
+ declare const SheetsOpenRecordContext: react.Context<SheetsOpenRecordHandler | null>;
308
+ /** The host's handler for opening a linked record, or null when the host has none. */
309
+ declare function useOpenRecordHandler(): SheetsOpenRecordHandler | null;
310
+
311
+ interface RelationSectionProps {
312
+ /** The record's table model. */
313
+ table: TableModel;
314
+ /** One relation of that table (the grid's rule for which to show: `gridRelations(table)`). */
315
+ relation: RelationModel;
316
+ /** The saved record (scalar fields and relation fields as read) or the new record's values; null while it loads. */
317
+ row: Readonly<Record<string, unknown>> | null;
318
+ /** The saved record's primary key; null for a record that is not created yet. */
319
+ rowIdentifier: SheetsRowIdentifier | null;
320
+ /** True for a record that is not created yet. */
321
+ isDraft: boolean;
322
+ /** A new record needs this link: the heading is marked like a required field. */
323
+ required?: boolean;
324
+ /** A reason the host already holds for keeping the relation read-only; it wins over the model's rules. */
325
+ readOnlyReason?: string | null;
326
+ /**
327
+ * belongsTo: the local key fields plus the chosen record under `relation.fieldName`
328
+ * (the grid editor's shape). On a new record this is the change itself; on a saved
329
+ * record it follows the write, for an immediate update of the shown record.
330
+ */
331
+ onCommitPatch?: (patch: Record<string, unknown>) => void;
332
+ /** Called after any write (the affected tables are already refetching). */
333
+ onInvalidateData?: () => void;
334
+ /** Open a linked record; defaults to the nearest `SheetsOpenRecordContext` handler. Without either, no open control is shown. */
335
+ onOpenRecord?: SheetsOpenRecordHandler;
336
+ /** Heading level of the section title. Default 3. */
337
+ headingLevel?: 2 | 3 | 4;
338
+ }
339
+ declare function RelationSection({ table, relation, row, rowIdentifier, isDraft, required, readOnlyReason, onCommitPatch, onInvalidateData, onOpenRecord, headingLevel, }: RelationSectionProps): react.JSX.Element;
340
+
341
+ /**
342
+ * Which relation and foreign-key columns the grid shows, and in what order,
343
+ * from the table model alone (never from the keys of a loaded row).
344
+ *
345
+ * - Every readable relation is a column, except a hasMany to a junction
346
+ * table that a pure manyToMany relation already shows.
347
+ * - A foreign-key column is hidden only when its belongsTo relation is shown;
348
+ * the relation column takes the place of its first key column.
349
+ * - Primary-key columns come first, then the other columns in model order,
350
+ * then hasOne, hasMany and manyToMany relations in model order.
351
+ */
352
+
353
+ /** The relations the grid shows as columns, in model order. */
354
+ declare function gridRelations(model: TableModel): RelationModel[];
355
+
130
356
  /** A grid row: arbitrary column values keyed by field name, plus an optional id. */
131
357
  type SheetsRow = Record<string, unknown> & {
132
358
  id?: string | number;
@@ -319,11 +545,24 @@ declare function extendRangeToCell(sel: SheetsSelection, col: number, row: numbe
319
545
  */
320
546
  declare function moveActive(sel: SheetsSelection, dCol: number, dRow: number, colCount: number, rowCount: number): SheetsSelection;
321
547
 
548
+ /** One cell write the grid refused before sending it. */
549
+ interface RejectedWrite {
550
+ rowIndex: number;
551
+ colKey: string;
552
+ reason: string;
553
+ }
554
+
322
555
  /** A single cell write request. */
323
556
  interface CellWrite {
324
557
  rowIndex: number;
325
558
  colKey: string;
326
559
  value: unknown;
560
+ /**
561
+ * The value is text the user typed or pasted (JSON and lists are read from it).
562
+ * Defaults to true for a string value, false otherwise; an editor or a fill that
563
+ * hands over a stored value sets it to false.
564
+ */
565
+ fromText?: boolean;
327
566
  }
328
567
  interface CommitCellsOptions {
329
568
  /** When false, the commit is NOT pushed to history (used by undo/redo replays). Default true. */
@@ -332,6 +571,8 @@ interface CommitCellsOptions {
332
571
  interface CommitCellsResult {
333
572
  /** Number of server cells actually written (post readonly/null/no-op filtering). */
334
573
  applied: number;
574
+ /** Writes refused before sending (the value did not fit, or the cell is read-only), when there are any. */
575
+ rejected?: readonly RejectedWrite[];
335
576
  }
336
577
 
337
578
  /**
@@ -345,7 +586,7 @@ interface CommitCellsResult {
345
586
  * will not bust the per-cell memo.
346
587
  *
347
588
  * Getters (live reads off the existing refs):
348
- * rowCount / colCount / activeCell / selection / combinedRows / columnKeys
589
+ * rowCount / colCount / activeCell / resumeCell / selection / combinedRows / columnKeys
349
590
  *
350
591
  * Anchor access wraps the existing `anchorRef` (the FIXED corner a range extends FROM):
351
592
  * getAnchor / setAnchor
@@ -354,8 +595,92 @@ interface CommitCellsResult {
354
595
  * setActiveCell, moveActiveCell, extendToCell, setSelection, commitCells,
355
596
  * openEditorAtActive, openEditorAt, undo, redo, scrollToCell, sortToggle,
356
597
  * getCellsInRange, toTSV, emit
598
+ *
599
+ * View (filter, sort and search): `view`, see {@link GridViewCommandTarget}.
357
600
  */
358
601
 
602
+ /**
603
+ * The filter, sort, search, column layout and saved-view actions the view
604
+ * commands run. Each `can*` / `has*` reads the table model and the view, so a
605
+ * command is only runnable when it would do something.
606
+ */
607
+ interface GridViewCommandTarget {
608
+ /** The table can be searched and the search box is on screen. */
609
+ readonly canSearch: boolean;
610
+ /** A search is active. */
611
+ readonly hasSearch: boolean;
612
+ /** The filter builder can open: the built-in toolbar is shown and the table has a filterable field. */
613
+ readonly canFilter: boolean;
614
+ /** At least one filter condition exists. */
615
+ readonly hasFilters: boolean;
616
+ /** The sort control can open: the built-in toolbar is shown and the table has a sortable column. */
617
+ readonly canSortAny: boolean;
618
+ /** At least one sort key exists. */
619
+ readonly hasSort: boolean;
620
+ /** The grid column can be sorted. */
621
+ canSort(colKey: string): boolean;
622
+ /** Focus the toolbar search box; false when it is not there. */
623
+ focusSearch(): boolean;
624
+ clearSearch(): void;
625
+ openFilters(): void;
626
+ clearFilters(): void;
627
+ openSort(): void;
628
+ clearSort(): void;
629
+ /** Sort by this column alone. */
630
+ sortBy(colKey: string, direction: 'asc' | 'desc'): void;
631
+ /** The column can be filtered (the built-in toolbar is shown). */
632
+ canFilterBy(colKey: string): boolean;
633
+ /** Add a condition on the column and open the filters. */
634
+ filterBy(colKey: string): void;
635
+ /** The column can be hidden (it is not the last one shown). */
636
+ canHide(colKey: string): boolean;
637
+ hide(colKey: string): void;
638
+ /** The column can move one place left (-1) or right (1) among the shown columns. */
639
+ canMove(colKey: string, step: -1 | 1): boolean;
640
+ move(colKey: string, step: -1 | 1): void;
641
+ /** How many leading columns stay in place. */
642
+ readonly frozenCount: number;
643
+ /** Freeze the shown columns up to and including this one. */
644
+ freezeUpTo(colKey: string): void;
645
+ unfreeze(): void;
646
+ /** Open the header menu of a column. */
647
+ openColumnMenu(colKey: string): void;
648
+ /** The Fields control can open (the built-in toolbar is shown). */
649
+ readonly canOpenFields: boolean;
650
+ openFields(): void;
651
+ /** The view switcher can open (the built-in toolbar is shown). */
652
+ readonly canOpenViews: boolean;
653
+ openViews(): void;
654
+ /** The active saved view has unsaved changes. */
655
+ readonly canSaveView: boolean;
656
+ saveView(): void;
657
+ }
658
+ /** The record panel, when the grid has one: open one row as a record. */
659
+ interface GridRecordCommandTarget {
660
+ /** The row can be opened (it is loaded and is a record). */
661
+ canOpen(rowIndex: number): boolean;
662
+ open(rowIndex: number): void;
663
+ /** The panel is open. Escape in the grid closes it only then. */
664
+ isOpen?(): boolean;
665
+ close?(): void;
666
+ }
667
+ /** The record panel's new-record form, when the grid has one. */
668
+ interface GridNewRecordCommandTarget {
669
+ /** The table allows new records. */
670
+ canCreate(): boolean;
671
+ open(): void;
672
+ }
673
+ /** Links in cells (an email or web address): find the one a cell holds, and open it. */
674
+ interface GridLinkCommandTarget {
675
+ /** The address the cell's link opens, or null when the cell holds no link. */
676
+ hrefAt(col: number, row: number): string | null;
677
+ /** Open an address: a web address in a new tab, an email in the mail app. */
678
+ open(href: string): void;
679
+ }
680
+ /** The grid's context menu, opened from the keyboard at a cell. */
681
+ interface GridContextMenuCommandTarget {
682
+ open(col: number, row: number): void;
683
+ }
359
684
  /** Extracted cell matrix — mirrors `getCellsInRange`'s return shape. */
360
685
  interface CellMatrix {
361
686
  cols: string[];
@@ -369,6 +694,11 @@ interface GridCommandContext {
369
694
  readonly colCount: number;
370
695
  /** The active (keyboard cursor) cell `[col, row]`, or undefined. */
371
696
  readonly activeCell: [number, number] | undefined;
697
+ /**
698
+ * Where the cursor comes back after the active cell was cleared: the last active cell while
699
+ * it is still inside the grid. Absent means the first cell.
700
+ */
701
+ readonly resumeCell?: [number, number];
372
702
  /** The LATEST canonical selection (post-sort/filter-clear safe). */
373
703
  readonly selection: SheetsSelection | undefined;
374
704
  /** The current combined (server + draft) row window. */
@@ -399,8 +729,11 @@ interface GridCommandContext {
399
729
  redo(): void | Promise<void>;
400
730
  /** Scroll a cell into view. */
401
731
  scrollToCell(col: number, row: number): void;
402
- /** Toggle the sort for a column key (the existing header-click sort toggle). */
403
- sortToggle(colKey: string): void;
732
+ /**
733
+ * Header sort click for a column key: cycle that column alone, or with `additive`
734
+ * (Shift+click) add it to the sort, flip it, or remove it.
735
+ */
736
+ sortToggle(colKey: string, additive?: boolean): void;
404
737
  /** Toggle a single row in the checkbox selection (the existing rowMarker.onToggleRow). */
405
738
  toggleRow(rowIndex: number, shift: boolean): void;
406
739
  /** Toggle select-all in the checkbox selection (the existing rowMarker.onToggleAll). */
@@ -411,6 +744,11 @@ interface GridCommandContext {
411
744
  toTSV(values: (readonly unknown[])[]): string;
412
745
  /** Emit an observational event (analytics/telemetry; never changes behavior). */
413
746
  emit(type: SheetsEvent['type'], meta?: Record<string, unknown>): void;
747
+ readonly view: GridViewCommandTarget;
748
+ readonly record?: GridRecordCommandTarget;
749
+ readonly newRecord?: GridNewRecordCommandTarget;
750
+ readonly link?: GridLinkCommandTarget;
751
+ readonly contextMenu?: GridContextMenuCommandTarget;
414
752
  }
415
753
 
416
754
  /**
@@ -460,8 +798,10 @@ declare function kbd(key: string, ...modifiers: KeyModifier[]): KeyBinding;
460
798
  * DEFAULT_KEYMAP + resolveKeyCommand (P4 Phase 1).
461
799
  *
462
800
  * A keymap is an ordered Binding[]; `resolveKeyCommand` returns the FIRST matching
463
- * binding's command id (first-match-wins) or `null` when nothing matches — including
464
- * for an unbound PRINTABLE key, so the dispatch funnel can fall to the `editor.typeToEdit`
801
+ * binding's command id (first-match-wins) or `null` when nothing matches. The grid tries
802
+ * every binding of a chord in order (`resolveKeyBindings`) and runs the first whose command
803
+ * can run, so one key can mean "close the panel, else clear the selection". Nothing matches
804
+ * an unbound PRINTABLE key either, so the dispatch funnel can fall to the `editor.typeToEdit`
465
805
  * sentinel (the printable-key path is NOT in the keymap; the funnel routes it explicitly).
466
806
  *
467
807
  * Triggers come in three kinds — `key` (matched here via the copied matchKeyBinding),
@@ -474,7 +814,7 @@ declare function kbd(key: string, ...modifiers: KeyModifier[]): KeyBinding;
474
814
  */
475
815
 
476
816
  /** A pointer gesture name (resolved by the pointer handlers, not the key funnel). */
477
- type PointerGesture = 'click' | 'shiftClick' | 'dblclick' | 'headerClick' | 'rowToggle' | 'rowToggleAll';
817
+ type PointerGesture = 'click' | 'shiftClick' | 'dblclick' | 'headerClick' | 'headerShiftClick' | 'rowToggle' | 'rowToggleAll';
478
818
  /** What fires a command. */
479
819
  type Trigger = {
480
820
  kind: 'key';
@@ -490,6 +830,11 @@ type Trigger = {
490
830
  interface Binding {
491
831
  trigger: Trigger;
492
832
  command: string;
833
+ /**
834
+ * Keep the key from the browser while the grid has focus even when the command
835
+ * does not run. For chords whose browser action loses work (Mod+R reloads the page).
836
+ */
837
+ claim?: boolean;
493
838
  }
494
839
 
495
840
  /**
@@ -537,13 +882,160 @@ interface CommandResult {
537
882
  */
538
883
  type Interceptor = (ev: DispatchEvent, next: () => CommandResult) => CommandResult;
539
884
 
885
+ interface ColumnLayoutBindings {
886
+ layout: SheetsColumnLayout;
887
+ /** Every grid column key of the table, in display order (shown and hidden). */
888
+ orderedKeys: readonly string[];
889
+ /** The keys that show, in display order. */
890
+ visibleKeys: readonly string[];
891
+ /** How many leading visible columns stay in place. */
892
+ frozenCount: number;
893
+ /** Row height in pixels. */
894
+ rowHeightPx: number;
895
+ isHidden: (key: string) => boolean;
896
+ /** Why a column cannot be hidden (it is the last one shown), or null. */
897
+ hideReason: (key: string) => string | null;
898
+ setHidden: (key: string, hidden: boolean) => void;
899
+ showAll: () => void;
900
+ hideAll: () => void;
901
+ /** Move to a position of the full display order (Fields list). */
902
+ moveTo: (key: string, index: number) => void;
903
+ /** Move beside another column (drag and drop). */
904
+ moveBeside: (key: string, target: string, side: 'before' | 'after') => void;
905
+ /** Move one place among the visible columns; false when it is already at that end. */
906
+ moveStep: (key: string, step: -1 | 1) => boolean;
907
+ freezeUpTo: (key: string) => void;
908
+ unfreeze: () => void;
909
+ setWidth: (key: string, width: number) => void;
910
+ setRowHeight: (rowHeight: SheetsRowHeight) => void;
911
+ fieldsOpen: boolean;
912
+ setFieldsOpen: (open: boolean) => void;
913
+ /** The column whose header menu is open, or null. */
914
+ menuColumn: string | null;
915
+ setMenuColumn: (key: string | null) => void;
916
+ }
917
+
918
+ /**
919
+ * The list variables for a view state: the filter (conditions and search,
920
+ * combined with `and`) and the sort, built only from the table model.
921
+ */
922
+
923
+ type Where = Record<string, unknown>;
924
+ /** Whether a condition is part of the filter, and why not. */
925
+ type ConditionStatus = {
926
+ status: 'applied';
927
+ } | {
928
+ status: 'incomplete';
929
+ } | {
930
+ status: 'invalid';
931
+ message: string;
932
+ };
933
+ interface ViewQuery {
934
+ /** The filter input value, or undefined for no filter. */
935
+ where: Where | undefined;
936
+ /** The sort, first key first, or undefined for none. */
937
+ orderBy: SortSpec[] | undefined;
938
+ /** Status of every condition, by condition id. */
939
+ conditions: ReadonlyMap<string, ConditionStatus>;
940
+ /** Number of conditions in the filter. */
941
+ appliedCount: number;
942
+ /** Related tables whose models some condition still needs. */
943
+ waitingFor: readonly TableKey[];
944
+ }
945
+ type RelatedModelLookup = (key: TableKey) => TableModel | null;
946
+ /**
947
+ * The list variables for a state the model supports (see
948
+ * `validateSheetsViewState`). Conditions that are incomplete or invalid, or
949
+ * that the filter input cannot combine, are left out of the filter and
950
+ * reported in `conditions`, so `appliedCount` counts only what filters.
951
+ */
952
+ declare function buildViewQuery(state: SheetsViewState, model: TableModel, related?: RelatedModelLookup): ViewQuery;
953
+
954
+ /**
955
+ * What the toolbar search box searches, from the table model.
956
+ *
957
+ * A table with a combined search field searches through it. Otherwise the
958
+ * search matches every text column that really has a case-insensitive contains
959
+ * operator, combined with `or`; without `or` it matches the first such column.
960
+ */
961
+
962
+ type SearchPlan = {
963
+ mode: 'unified';
964
+ /** Filter input field that takes the search text. */
965
+ field: string;
966
+ /** Columns the table's search covers, when the server names them. */
967
+ columns: readonly string[];
968
+ } | {
969
+ mode: 'columns';
970
+ /** Columns matched with a case-insensitive contains, in table order. */
971
+ columns: readonly {
972
+ name: string;
973
+ field: string;
974
+ }[];
975
+ };
976
+
977
+ interface SheetsViewProps {
978
+ /** Controlled filters. Omit to let the grid own them. */
979
+ filters?: SheetsFilterGroup;
980
+ onFiltersChange?: (filters: SheetsFilterGroup) => void;
981
+ /** Controlled sort, first key first. Omit to let the grid own it. */
982
+ sort?: readonly SheetsSortKey[];
983
+ onSortChange?: (sort: readonly SheetsSortKey[]) => void;
984
+ /** Controlled search text. Omit to let the grid own it. */
985
+ search?: string;
986
+ onSearchChange?: (search: string) => void;
987
+ /** Controlled column layout (order, hidden, frozen count, widths, row height). Omit to let the grid own it. */
988
+ columns?: SheetsColumnLayout;
989
+ onColumnsChange?: (columns: SheetsColumnLayout) => void;
990
+ }
991
+ /** The view bindings the toolbar, the header and the commands use. */
992
+ interface SheetsViewBindings {
993
+ /** The state in use, valid for the current model. */
994
+ state: SheetsViewState;
995
+ model: TableModel | null;
996
+ /** Parts of the given state the model does not support. */
997
+ dropped: readonly SheetsViewStateDrop[];
998
+ /** Status of every condition, by condition id. */
999
+ conditions: ReadonlyMap<string, ConditionStatus>;
1000
+ /** Conditions that are part of the filter. */
1001
+ appliedCount: number;
1002
+ /** What the search box searches, or null when the table cannot be searched. */
1003
+ searchPlan: SearchPlan | null;
1004
+ columnLabel: (name: string) => string;
1005
+ /** A related table's model, once loaded. */
1006
+ relatedModel: (key: TableKey) => TableModel | null;
1007
+ setFilters: (filters: SheetsFilterGroup) => void;
1008
+ clearFilters: () => void;
1009
+ setSort: (sort: readonly SheetsSortKey[]) => void;
1010
+ /** Header click: cycle one column, or with `additive` add it to the sort. */
1011
+ toggleSort: (column: string, additive: boolean) => void;
1012
+ setSearch: (search: string) => void;
1013
+ setColumns: (columns: SheetsColumnLayout) => void;
1014
+ /** Replace filters, sort, search and layout at once (a saved view). */
1015
+ applyState: (state: SheetsViewState) => void;
1016
+ /** Open the filters with a new condition on a column or relation; false when no condition could be added. */
1017
+ filterBy: (column: string) => boolean;
1018
+ /** Column layout and its actions. */
1019
+ layout: ColumnLayoutBindings;
1020
+ /** Why a grid column cannot be sorted, or null when it can. Empty text for a column the grid adds itself. */
1021
+ unsortableReason: (column: string) => string | null;
1022
+ filtersOpen: boolean;
1023
+ setFiltersOpen: (open: boolean) => void;
1024
+ sortOpen: boolean;
1025
+ setSortOpen: (open: boolean) => void;
1026
+ /** Attach to the search input so `focusSearch` can reach it. */
1027
+ searchInputRef: React.MutableRefObject<HTMLInputElement | null>;
1028
+ /** Focus the search box; false when there is none. */
1029
+ focusSearch: () => boolean;
1030
+ }
1031
+
540
1032
  /**
541
1033
  * Lifecycle/interaction event emitted by {@link Sheets} via the optional
542
1034
  * `onEvent` prop. Purely observational: firing an event never changes grid
543
1035
  * behavior, so consumers can wire analytics/telemetry without side effects.
544
1036
  */
545
1037
  interface SheetsEvent {
546
- type: 'load:success' | 'load:error' | 'cell:edit' | 'row:create' | 'row:delete' | 'filter:apply' | 'sort:change' | 'page:change';
1038
+ type: 'load:success' | 'load:error' | 'cell:edit' | 'row:create' | 'row:delete' | 'filter:apply' | 'sort:change' | 'search:change' | 'page:change';
547
1039
  /** The table the event originated from. */
548
1040
  tableName: string;
549
1041
  /** Epoch ms (`Date.now()`) when the event fired. */
@@ -567,7 +1059,10 @@ interface SheetsSlots {
567
1059
  empty?: React.ReactNode | ((ctx: {
568
1060
  tableName: string;
569
1061
  }) => React.ReactNode);
570
- /** Replaces the default full-screen error state. */
1062
+ /**
1063
+ * Replaces the default error panel: full-screen while the table's model is missing, and over
1064
+ * the grid body (toolbar kept) when only the rows failed to load.
1065
+ */
571
1066
  error?: (ctx: {
572
1067
  error: unknown;
573
1068
  retry: () => void;
@@ -595,14 +1090,37 @@ interface SheetsHandle {
595
1090
  refetch(): void;
596
1091
  /** Return the currently selected rows (empty array when nothing selected). */
597
1092
  getSelectedRows(): Record<string, unknown>[];
598
- /** Download the selected rows (or all rows when none selected) as CSV. */
1093
+ /**
1094
+ * Download the selected rows (or all rows when none selected) as CSV.
1095
+ * `protectFormulas` overrides the grid's `csvExport.protectFormulas` for this download.
1096
+ */
599
1097
  exportCsv(opts?: {
600
1098
  columns?: string[];
601
1099
  filename?: string;
1100
+ protectFormulas?: boolean;
602
1101
  }): void;
1102
+ /** Open a record of this table in the record panel. False when the identifier does not name a record. */
1103
+ openRecord(recordId: SheetsRowIdentifier): boolean;
1104
+ /** Open the record panel on a new record. False when the table does not allow new records. */
1105
+ openNewRecord(): boolean;
1106
+ /** Close the record panel. */
1107
+ closeRecord(): void;
603
1108
  }
604
- interface DataGridProps<TRow extends SheetsRow = SheetsRow> {
1109
+ /**
1110
+ * `filters` / `sort` / `search` (each with its change callback) let a host own
1111
+ * the view state, for example to persist it as a saved view. Each one omitted is
1112
+ * owned by the grid. The grid checks every given state against the table model
1113
+ * and leaves out what the model no longer supports (see `validateSheetsViewState`).
1114
+ */
1115
+ interface DataGridProps<TRow extends SheetsRow = SheetsRow> extends SheetsViewProps {
605
1116
  tableName: string;
1117
+ /**
1118
+ * Make the grid read-only for this host: `true`, or the reason to show. Every cell,
1119
+ * paste and fill, Add row, New record, Import, Delete, every link and the record panel's
1120
+ * fields refuse writes and show the reason; viewing, sorting, filtering, search and
1121
+ * export stay. `true` shows "This table is read-only here."
1122
+ */
1123
+ readOnly?: boolean | string;
606
1124
  className?: string;
607
1125
  pageSize?: number;
608
1126
  showSelection?: boolean;
@@ -630,6 +1148,29 @@ interface DataGridProps<TRow extends SheetsRow = SheetsRow> {
630
1148
  * Omitting it leaves behavior unchanged.
631
1149
  */
632
1150
  onEvent?: (e: SheetsEvent) => void;
1151
+ /**
1152
+ * Called when the user asks to see another table, for example the table that
1153
+ * stores links needing more fields than the link editor can fill. The grid
1154
+ * does not navigate; omit it and the editor offers no such action.
1155
+ */
1156
+ onOpenTable?: SheetsOpenTableHandler;
1157
+ /**
1158
+ * CSV export settings. `protectFormulas`: text that starts with =, +, -, @, a tab or
1159
+ * a carriage return is written with a leading apostrophe, so a spreadsheet app does not
1160
+ * run it as a formula (numbers are not changed). Off by default. It applies to
1161
+ * "Export selected" and `SheetsHandle.exportCsv`, and is the starting choice of the
1162
+ * checkbox in the "Export view" dialog.
1163
+ */
1164
+ csvExport?: {
1165
+ protectFormulas?: boolean;
1166
+ };
1167
+ /**
1168
+ * The record open in the record panel, for deep links: an identifier of a record of
1169
+ * this table, or null for closed. Omit it to let the grid own the panel state.
1170
+ */
1171
+ recordId?: SheetsRowIdentifier | null;
1172
+ /** Called whenever the user opens, moves to or closes a record of this table in the record panel. */
1173
+ onRecordOpenChange?: (recordId: SheetsRowIdentifier | null) => void;
633
1174
  /**
634
1175
  * Optional render-slot overrides for the toolbar / empty / error / loading
635
1176
  * regions. Any omitted slot falls back to the built-in default.
@@ -641,8 +1182,9 @@ interface DataGridProps<TRow extends SheetsRow = SheetsRow> {
641
1182
  */
642
1183
  commands?: GridCommand[];
643
1184
  /**
644
- * Extra / override key bindings, scanned BEFORE the defaults (first-match-wins),
645
- * so a rebind of a built-in chord wins. Omitting it = the default keymap.
1185
+ * Extra / override key bindings, scanned BEFORE the defaults, so a rebind of a
1186
+ * built-in chord wins. When several bindings match a key, they are tried in order
1187
+ * and the first whose command can run wins. Omitting it = the default keymap.
646
1188
  */
647
1189
  keymap?: Binding[];
648
1190
  /**
@@ -672,6 +1214,56 @@ declare const Sheets: <TRow extends SheetsRow = SheetsRow>(props: DataGridProps<
672
1214
  }) => react__default.ReactElement;
673
1215
  type SheetsProps<TRow extends SheetsRow = SheetsRow> = DataGridProps<TRow>;
674
1216
 
1217
+ /** The built-in engine the registry falls back to (injected to avoid a cycle). */
1218
+ interface CellTypeBuiltins {
1219
+ toSheetsCell: (value: unknown, ctx: SheetsCellRenderContext) => SheetsCell;
1220
+ }
1221
+ interface CellTypeRegistry {
1222
+ /** Detection: consumer `match()` chain first (later defs win), else the built-in resolver. */
1223
+ resolveTypeKey(meta: CellTypeMatchInput, builtinFallback: () => string): string;
1224
+ /** Native display: consumer `def.toSheetsCell` for this typeKey, else the built-in renderer. */
1225
+ toSheetsCell(typeKey: string, value: unknown, ctx: SheetsCellRenderContext): SheetsCell;
1226
+ /** The registered definition for a typeKey, if any (consumer defs only). */
1227
+ get(typeKey: string): CellTypeDefinition<any> | undefined;
1228
+ /** The native cell COMPONENT override for a typeKey, if any (consumer `def.cell`). */
1229
+ getCellComponent(typeKey: string): React.ComponentType<CellProps> | undefined;
1230
+ /** The native EDITOR override for a typeKey, if any (consumer `def.editorComponent`). */
1231
+ getEditorComponent(typeKey: string): React.ComponentType<EditorProps> | undefined;
1232
+ }
1233
+ /**
1234
+ * Build a registry. `cellTypes` are consumer definitions in precedence order
1235
+ * (provider `plugins` first, then per-instance `cellTypes`); later entries win,
1236
+ * so an instance-level def overrides a provider-level one with the same typeKey.
1237
+ */
1238
+ declare function createCellTypeRegistry(cellTypes: CellTypeDefinition<any>[], builtins: CellTypeBuiltins): CellTypeRegistry;
1239
+
1240
+ /** Resolved DOM cell payload: the neutral cell plus its (optional) view component. */
1241
+ interface SheetsCellResolution {
1242
+ cell: SheetsCell;
1243
+ component?: React.ComponentType<CellProps>;
1244
+ colKey: string;
1245
+ /**
1246
+ * The resolved cell-type key (post detection-override) — the SINGLE source of
1247
+ * truth the host feeds to `resolveEditIntent` to route activation. Always set;
1248
+ * `'text'` for the loading/empty fallthrough cells that carry no type. (Mirror
1249
+ * of the `meta.cellType` the cell itself now self-describes.)
1250
+ */
1251
+ typeKey: string;
1252
+ /** Typed server row locator, separate from the grid's string key. */
1253
+ rowIdentifier?: SheetsRowIdentifier | null;
1254
+ readOnlyReason?: string;
1255
+ /** Field metadata for the column — fed to a native overlay editor's EditorProps.fieldMeta. */
1256
+ fieldMeta?: FieldMetadata;
1257
+ /** Relation info for the column (when relational) — fed to a native overlay editor's EditorProps.relationInfo. */
1258
+ relationInfo?: RelationInfo;
1259
+ /** The table-model column behind this cell, or null when the cell is not a column. */
1260
+ column?: ColumnModel | null;
1261
+ /** The table-model relation behind this cell, or null when the cell is not a relation. */
1262
+ relation?: RelationModel | null;
1263
+ /** A problem with this draft cell's value (for example a missing required value), shown on the cell. */
1264
+ errorMessage?: string;
1265
+ }
1266
+
675
1267
  type RelationMetadataSource = 'relation' | 'foreignKey';
676
1268
  interface RelationMetadata {
677
1269
  tableName: string;
@@ -715,9 +1307,12 @@ interface RelationColumnInfo {
715
1307
  relationTypeByField: Map<string, RelationKind>;
716
1308
  }
717
1309
  /**
718
- * Create data grid columns with relation metadata baked in
1310
+ * Create data grid columns with relation metadata baked in.
1311
+ *
1312
+ * @param tableName - table name or `TableModel.key`.
1313
+ * @param _rows - ignored; columns come from the table model, not from loaded rows.
719
1314
  */
720
- declare function useRelationColumns(tableName?: string, rows?: unknown[]): RelationColumnInfo;
1315
+ declare function useRelationColumns(tableName?: string, _rows?: unknown[]): RelationColumnInfo;
721
1316
  /**
722
1317
  * Drop-in replacement for the original useDataGridColumns hook
723
1318
  * Maintains complete backward compatibility while providing improvements
@@ -737,114 +1332,15 @@ declare function useDataGridColumns(tableName?: string, rows?: unknown[]): {
737
1332
  invalidateRelationCache: () => Promise<void>;
738
1333
  };
739
1334
 
740
- /** The built-in engine the registry falls back to (injected to avoid a cycle). */
741
- interface CellTypeBuiltins {
742
- toSheetsCell: (value: unknown, ctx: SheetsCellRenderContext) => SheetsCell;
743
- }
744
- interface CellTypeRegistry {
745
- /** Detection: consumer `match()` chain first (later defs win), else the built-in resolver. */
746
- resolveTypeKey(meta: CellTypeMatchInput, builtinFallback: () => string): string;
747
- /** Native display: consumer `def.toSheetsCell` for this typeKey, else the built-in renderer. */
748
- toSheetsCell(typeKey: string, value: unknown, ctx: SheetsCellRenderContext): SheetsCell;
749
- /** The registered definition for a typeKey, if any (consumer defs only). */
750
- get(typeKey: string): CellTypeDefinition<any> | undefined;
751
- /** The native cell COMPONENT override for a typeKey, if any (consumer `def.cell`). */
752
- getCellComponent(typeKey: string): React.ComponentType<CellProps> | undefined;
753
- /** The native EDITOR override for a typeKey, if any (consumer `def.editorComponent`). */
754
- getEditorComponent(typeKey: string): React.ComponentType<EditorProps> | undefined;
755
- }
756
- /**
757
- * Build a registry. `cellTypes` are consumer definitions in precedence order
758
- * (provider `plugins` first, then per-instance `cellTypes`); later entries win,
759
- * so an instance-level def overrides a provider-level one with the same typeKey.
760
- */
761
- declare function createCellTypeRegistry(cellTypes: CellTypeDefinition<any>[], builtins: CellTypeBuiltins): CellTypeRegistry;
762
-
763
- /** Resolved DOM cell payload: the neutral cell plus its (optional) view component. */
764
- interface SheetsCellResolution {
765
- cell: SheetsCell;
766
- component?: React.ComponentType<CellProps>;
767
- colKey: string;
768
- /**
769
- * The resolved cell-type key (post detection-override) — the SINGLE source of
770
- * truth the host feeds to `resolveEditIntent` to route activation. Always set;
771
- * `'text'` for the loading/empty fallthrough cells that carry no type. (Mirror
772
- * of the `meta.cellType` the cell itself now self-describes.)
773
- */
774
- typeKey: string;
775
- /** Typed server row locator, separate from the grid's string key. */
776
- rowIdentifier?: SheetsRowIdentifier | null;
777
- readOnlyReason?: string;
778
- /** Field metadata for the column — fed to a native overlay editor's EditorProps.fieldMeta. */
779
- fieldMeta?: FieldMetadata;
780
- /** Relation info for the column (when relational) — fed to a native overlay editor's EditorProps.relationInfo. */
781
- relationInfo?: RelationInfo;
782
- }
783
-
784
- type FilterValue = string | number | boolean | null | undefined;
785
- type FilterNode = FilterCondition | FilterGroup;
786
- interface FilterCondition {
787
- type: "condition";
788
- id: string;
789
- field: string;
790
- operator: string;
791
- value: FilterValue;
792
- }
793
- interface FilterGroup {
794
- type: "group";
795
- id: string;
796
- conjunction: "and" | "or";
797
- children: FilterNode[];
798
- }
799
- declare const MAX_FILTER_DEPTH = 3;
800
- type FieldTypeMap = Record<string, {
801
- gqlType: string;
802
- isArray: boolean;
803
- }>;
804
- declare function createEmptyGroup(conjunction?: "and" | "or"): FilterGroup;
805
- declare function countConditions(node: FilterNode): number;
806
- interface SheetsControlsProps {
807
- openSearch?: () => void;
808
- filterTree: FilterGroup;
809
- setFilterTree: (tree: FilterGroup) => void;
810
- filtersOpen: boolean;
811
- setFiltersOpen: (open: boolean) => void;
812
- clearAllFilters: () => void;
813
- applyFilters: () => void;
814
- columnKeys: string[];
815
- fieldTypeMap: FieldTypeMap;
816
- showSelection: boolean;
817
- gridSelection: SheetsSelection | null;
818
- setGridSelection: (selection: SheetsSelection | null) => void;
819
- deleteSelected: () => void;
820
- onAddRow?: () => void;
821
- onExport?: () => void;
822
- canDelete?: boolean;
823
- readOnlyReason?: string | null;
824
- }
825
- declare function SheetsControls(props: SheetsControlsProps): react.JSX.Element;
826
-
827
1335
  interface GridState {
828
- sorting: {
829
- id: string | null;
830
- desc: boolean;
831
- };
832
1336
  pageIndex: number;
833
- filterTree: FilterGroup;
834
- filtersOpen: boolean;
835
1337
  columnWidths: Map<string, number>;
836
1338
  gridSelection: SheetsSelection | undefined;
837
1339
  }
838
1340
  declare function useGridState(): {
839
1341
  state: GridState;
840
1342
  actions: {
841
- setSorting: (sorting: GridState["sorting"]) => void;
842
- toggleSorting: (colId: string) => void;
843
1343
  setPageIndex: (pageIndex: number) => void;
844
- setFilterTree: (tree: FilterGroup) => void;
845
- clearAllFilters: () => void;
846
- toggleFiltersPanel: () => void;
847
- setFiltersOpen: (open: boolean) => void;
848
1344
  resizeColumn: (id: string, width: number) => void;
849
1345
  setGridSelection: (selection: SheetsSelection | undefined) => void;
850
1346
  setActiveCell: (col: number, row: number) => void;
@@ -853,6 +1349,13 @@ declare function useGridState(): {
853
1349
  };
854
1350
  };
855
1351
 
1352
+ /** One reversible step: a label plus its undo / redo thunks (throw when nothing changed). */
1353
+ interface HistoryEntry {
1354
+ label: string;
1355
+ undo: () => Promise<void> | void;
1356
+ redo: () => Promise<void> | void;
1357
+ }
1358
+
856
1359
  type RowRecord$2 = Record<string, unknown>;
857
1360
  /** Data for a single loaded page */
858
1361
  interface PageData<T = RowRecord$2> {
@@ -870,8 +1373,10 @@ interface UseInfiniteTableOptions {
870
1373
  field: string;
871
1374
  direction: 'asc' | 'desc';
872
1375
  }>;
873
- /** Filter conditions */
874
- where?: Record<string, unknown>;
1376
+ /** A filter in the server's filter input shape (any operator the model reports, relation and search fields included). */
1377
+ where?: Readonly<Record<string, unknown>>;
1378
+ /** Columns to fetch (the primary key and relation keys are always added). Omitted: every readable column. */
1379
+ columns?: readonly string[];
875
1380
  /** Field selection preset or custom selection */
876
1381
  select?: FieldSelection;
877
1382
  /** Enable/disable the hook */
@@ -897,10 +1402,14 @@ interface UseInfiniteTableResult<T = RowRecord$2> {
897
1402
  pageSize: number;
898
1403
  /** Overall loading state (true if any page is loading) */
899
1404
  isLoading: boolean;
1405
+ /** True while a page request for the current options is in flight, also while placeholder rows from the previous options show */
1406
+ isFetching: boolean;
900
1407
  /** Whether initial data has been loaded */
901
1408
  hasInitialData: boolean;
902
- /** Error from the most recent failed fetch */
1409
+ /** Error from the most recent failed fetch, or why the table model is unavailable */
903
1410
  error: Error | null;
1411
+ /** The table model, or null while it loads or when it failed */
1412
+ model: TableModel | null;
904
1413
  /** Invalidate all pages and refetch */
905
1414
  invalidate: () => void;
906
1415
  /** Reset to initial state (clears all pages, refetches page 0) */
@@ -925,6 +1434,50 @@ interface VisibleRowRange {
925
1434
  endIndex: number;
926
1435
  }
927
1436
 
1437
+ /** A saved view, checked against the current model. */
1438
+ interface SavedView {
1439
+ id: string;
1440
+ name: string;
1441
+ /** The stored state as the current model supports it. */
1442
+ state: SheetsViewState;
1443
+ /** What the model no longer supports, as messages for the user. */
1444
+ dropped: readonly SheetsViewStateDrop[];
1445
+ updatedAt: string;
1446
+ }
1447
+ interface SavedViewsBindings {
1448
+ /** 'loading' until the stored views and the table model are both there. */
1449
+ status: 'loading' | 'ready' | 'error';
1450
+ /** Why the views could not be loaded or the last change failed, or null. */
1451
+ error: string | null;
1452
+ views: readonly SavedView[];
1453
+ /** The view in use, or null for the default view (nothing saved). */
1454
+ activeView: SavedView | null;
1455
+ /** The grid differs from the active view as saved. Always false for the default view. */
1456
+ dirty: boolean;
1457
+ /** True while a change is being written. */
1458
+ busy: boolean;
1459
+ /** Messages about parts of the active view the model dropped when it loaded. */
1460
+ activeDropped: readonly SheetsViewStateDrop[];
1461
+ /** Switch to a view, or with null to the default view (no filter, sort or search, every field shown). Unsaved changes are discarded. */
1462
+ select: (viewId: string | null) => Promise<boolean>;
1463
+ /** Save the grid as a new view and switch to it. */
1464
+ create: (name: string) => Promise<boolean>;
1465
+ /** Save the grid into the active view. */
1466
+ save: () => Promise<boolean>;
1467
+ /** Go back to the active view as saved. */
1468
+ discard: () => void;
1469
+ rename: (viewId: string, name: string) => Promise<boolean>;
1470
+ /** Copy a view under a new name and switch to the copy. */
1471
+ duplicate: (viewId: string) => Promise<boolean>;
1472
+ remove: (viewId: string) => Promise<boolean>;
1473
+ /** Load the views again after an error. */
1474
+ retry: () => void;
1475
+ /** Why a name cannot be used, or null. */
1476
+ nameProblem: (name: string, exceptViewId?: string) => string | null;
1477
+ open: boolean;
1478
+ setOpen: (open: boolean) => void;
1479
+ }
1480
+
928
1481
  /** Draft-row bindings for a headless shell. */
929
1482
  interface SheetsDraftBindings {
930
1483
  /** Whether any client-side draft rows exist. */
@@ -935,6 +1488,8 @@ interface SheetsDraftBindings {
935
1488
  submitDrafts: () => Promise<void>;
936
1489
  /** Delete the currently selected rows (draft + server). */
937
1490
  deleteSelected: () => Promise<void>;
1491
+ /** Delete these rows by index: a saved row is deleted, a new row is discarded. */
1492
+ deleteRows: (rows: readonly number[]) => Promise<void>;
938
1493
  }
939
1494
  /**
940
1495
  * Selection bindings for a headless shell.
@@ -986,6 +1541,8 @@ interface UseSheetsResult {
986
1541
  isEmpty: boolean;
987
1542
  /** Refetch the underlying data (mode-aware: infinite vs paginated). */
988
1543
  refetch: () => void;
1544
+ /** Read the table's shape (`_meta`) and its rows again. */
1545
+ refreshFromServer: () => void;
989
1546
  }
990
1547
  /**
991
1548
  * Internal bindings consumed only by the built-in {@link Sheets} chrome
@@ -998,34 +1555,40 @@ interface SheetsShellBindings {
998
1555
  serverRowCount: number;
999
1556
  draftRowCount: number;
1000
1557
  infiniteScroll: boolean;
1001
- filterTree: ReturnType<typeof useGridState>['state']['filterTree'];
1002
- filtersOpen: boolean;
1003
- setFilterTree: ReturnType<typeof useGridState>['actions']['setFilterTree'];
1004
- setFiltersOpen: ReturnType<typeof useGridState>['actions']['setFiltersOpen'];
1005
- clearAllFilters: ReturnType<typeof useGridState>['actions']['clearAllFilters'];
1006
- applyFilters: () => void;
1007
- fieldTypeMap: Record<string, {
1008
- gqlType: string;
1009
- isArray: boolean;
1010
- }>;
1558
+ /** @internal Filter, sort and search state and actions (toolbar, header, view commands). NOT a stable API. */
1559
+ view: SheetsViewBindings;
1560
+ /** @internal Saved views of the table (switcher, save, discard). NOT a stable API. */
1561
+ savedViews: SavedViewsBindings;
1562
+ /** Number of filter conditions in the state, applied or not. */
1563
+ filterConditionCount: number;
1564
+ /** The list filter and sort of the view, as the data hooks get them (full-result export). */
1565
+ viewQuery: {
1566
+ where: Readonly<Record<string, unknown>> | undefined;
1567
+ orderBy: readonly SortSpec[] | undefined;
1568
+ };
1569
+ /** True while rows for the current filter, sort or search are being fetched (the previous rows may still show). */
1570
+ isFetchingRows: boolean;
1011
1571
  setGridSelectionForControls: (selection: SheetsSelection | null) => void;
1012
- /** Header sort toggle (colIndex → toggleSorting on the sortable column). */
1013
- onHeaderClicked: (colIndex: number) => void;
1014
1572
  /** Prefetch the rows in an inclusive visible window (native range, infinite mode). */
1015
1573
  onVisibleRegionChanged: (range: VisibleRowRange) => void;
1016
- /** @internal Sort state mirror ({ id, desc }) — the DOM header reads this for its caret. NOT a stable API. */
1017
- sorting: ReturnType<typeof useGridState>['state']['sorting'];
1574
+ /** Changes exactly when sort, filters or search change the rows (selection resets on it). */
1575
+ viewSignature: string;
1018
1576
  /** @internal Committed column widths (id → px) — the DOM grid maps these to v9 columnSizing. NOT a stable API. */
1019
1577
  columnWidths: ReturnType<typeof useGridState>['state']['columnWidths'];
1020
1578
  /** @internal Commit a column width (id, px) — the DOM resize handle drives this directly. NOT a stable API. */
1021
1579
  resizeColumn: ReturnType<typeof useGridState>['actions']['resizeColumn'];
1580
+ /** Leading columns that stay in place under horizontal scroll (the view's layout). */
1022
1581
  frozenCount: number;
1582
+ /** Row height in pixels (the view's layout). */
1583
+ rowHeightPx: number;
1023
1584
  selectedRowCount: number;
1024
1585
  canCreate: boolean;
1025
1586
  canUpdate: boolean;
1026
1587
  canDelete: boolean;
1027
- /** Human-readable reason shown when `_meta` proves the whole table is read-only. */
1588
+ /** Human-readable reason shown when the table model proves rows cannot be changed. */
1028
1589
  readOnlyReason: string | null;
1590
+ /** @internal The table model (kinds, options, write flags, relations, sort and filter names), or null while it loads. NOT a stable API. */
1591
+ tableModel: TableModel | null;
1029
1592
  /** Stable identity for selection, TanStack rows, and editor instances. */
1030
1593
  getRowId: (row: SheetsRow | null | undefined, index: number) => string;
1031
1594
  isSubmittingDrafts: boolean;
@@ -1053,6 +1616,8 @@ interface SheetsShellBindings {
1053
1616
  canUndo: boolean;
1054
1617
  /** @internal Whether a redo is available. NOT a stable API. */
1055
1618
  canRedo: boolean;
1619
+ /** @internal Add a step to the undo history (a link editor's saved change). NOT a stable API. */
1620
+ recordHistory: (entry: HistoryEntry) => void;
1056
1621
  /** @internal Observational event emitter (analytics/telemetry) — threaded into the command context. NOT a stable API. */
1057
1622
  emit: (type: SheetsEvent['type'], meta?: Record<string, unknown>) => void;
1058
1623
  }
@@ -1060,6 +1625,7 @@ type UseSheetsInternalResult<TRow extends SheetsRow = SheetsRow> = UseSheetsResu
1060
1625
  /** @internal Bindings for the built-in <Sheets> chrome — not a stable API. */
1061
1626
  _shell: SheetsShellBindings;
1062
1627
  };
1628
+
1063
1629
  /**
1064
1630
  * Headless grid hook — returns the data/state bindings the built-in {@link Sheets}
1065
1631
  * component renders with the native DOM grid.
@@ -1074,6 +1640,229 @@ type UseSheetsInternalResult<TRow extends SheetsRow = SheetsRow> = UseSheetsResu
1074
1640
  */
1075
1641
  declare function useSheets<TRow extends SheetsRow = SheetsRow>(props: DataGridProps<TRow>): UseSheetsInternalResult<TRow>;
1076
1642
 
1643
+ /** The reason a grid shows for `readOnly={true}`. */
1644
+ declare const DEFAULT_READ_ONLY_REASON = "This table is read-only here.";
1645
+ interface SheetsReadOnlyProviderProps {
1646
+ /** `true`, or the reason to show; false or omitted leaves writes to the table model. */
1647
+ readOnly?: boolean | string | null;
1648
+ children: ReactNode;
1649
+ }
1650
+ /**
1651
+ * Make everything inside read-only with a reason. `<Sheets readOnly>` renders it;
1652
+ * a host driving `useSheets` itself wraps its grid in it.
1653
+ */
1654
+ declare function SheetsReadOnlyProvider({ readOnly, children }: SheetsReadOnlyProviderProps): react.JSX.Element;
1655
+
1656
+ interface RowRemoval {
1657
+ /** The row indexes to remove. */
1658
+ rows: readonly number[];
1659
+ /** Saved rows among them: deleted on the server. */
1660
+ saved: number;
1661
+ /** New rows among them: discarded. */
1662
+ unsaved: number;
1663
+ /** Why these rows cannot be removed, or null. */
1664
+ blockedReason: string | null;
1665
+ }
1666
+
1667
+ interface SheetsControlsProps {
1668
+ /** Filter, sort and search bindings. */
1669
+ view: SheetsViewBindings;
1670
+ /** Grid columns, in display order. */
1671
+ columnKeys: readonly string[];
1672
+ showSelection: boolean;
1673
+ gridSelection: SheetsSelection | null;
1674
+ setGridSelection: (selection: SheetsSelection | null) => void;
1675
+ deleteSelected: () => void;
1676
+ onAddRow?: () => void;
1677
+ /** Download the selected rows as CSV; offered only while rows are selected. */
1678
+ onExport?: () => void;
1679
+ canDelete?: boolean;
1680
+ /** What deleting the selected rows does (saved rows deleted, new rows discarded); refines `canDelete`. */
1681
+ selectionRemoval?: RowRemoval;
1682
+ readOnlyReason?: string | null;
1683
+ /** Saved views of the table. Omit to hide the view switcher. */
1684
+ savedViews?: SavedViewsBindings;
1685
+ /** More toolbar actions (import, export of the whole view), placed before New record. */
1686
+ tools?: React.ReactNode;
1687
+ /** Open the record panel's new-record form; `disabledReason` says why it cannot open. Omit to hide. */
1688
+ newRecord?: {
1689
+ open: () => void;
1690
+ disabledReason: string | null;
1691
+ };
1692
+ }
1693
+ declare function SheetsControls(props: SheetsControlsProps): react.JSX.Element;
1694
+
1695
+ interface ImportRecordsControlProps {
1696
+ /** The table to add records to, or null while it loads. */
1697
+ model: TableModel | null;
1698
+ /** Name used in the dialog title and the error report's file name. Default: the table name. */
1699
+ tableLabel?: string;
1700
+ }
1701
+ declare function ImportRecordsControl({ model, tableLabel }: ImportRecordsControlProps): react.JSX.Element;
1702
+
1703
+ interface ExportViewControlProps {
1704
+ /** The table, or null while it loads. */
1705
+ model: TableModel | null;
1706
+ /** The view's filter, search included. */
1707
+ where?: Readonly<Record<string, unknown>>;
1708
+ orderBy?: readonly SortSpec[];
1709
+ /** The view's column keys in order (column names and relation field names). Default: every grid column. */
1710
+ columns?: readonly string[];
1711
+ /** Download file name. Default: the table name with `.csv`. */
1712
+ filename?: string;
1713
+ /** Prefix text that starts like a spreadsheet formula with an apostrophe (see `formula-protection.ts`). Default false. */
1714
+ protectFormulas?: boolean;
1715
+ }
1716
+ declare function ExportViewControl({ model, where, orderBy, columns, filename, protectFormulas }: ExportViewControlProps): react.JSX.Element;
1717
+
1718
+ /**
1719
+ * Check a stored view state against the current table model.
1720
+ *
1721
+ * Pure: returns a state that only names columns, operators, options and
1722
+ * relations the model has, and a list of what it dropped and why. Use it to load
1723
+ * a saved view; the grid also runs it on every state it receives, so a stale
1724
+ * state never reaches the server. A version 1 state (before the column layout)
1725
+ * loads with the default layout.
1726
+ */
1727
+
1728
+ interface ValidateSheetsViewStateOptions {
1729
+ /** Column or relation title for messages; defaults to the field name. */
1730
+ label?: (name: string) => string;
1731
+ }
1732
+ /**
1733
+ * A state the model supports, from any stored value. Unknown columns,
1734
+ * operators, options and relations are dropped and reported; an unreadable
1735
+ * value becomes the empty state.
1736
+ */
1737
+ declare function validateSheetsViewState(input: unknown, model: TableModel, options?: ValidateSheetsViewStateOptions): SheetsViewStateValidation;
1738
+
1739
+ /** Deepest nesting the filter builder offers (the root group is depth 0). */
1740
+ declare const MAX_FILTER_DEPTH = 3;
1741
+ declare function createFilterGroup(logic?: SheetsFilterLogic, children?: readonly SheetsFilterNode[]): SheetsFilterGroup;
1742
+ /** The state with no filter, no sort, no search, and every column shown in the table's order. */
1743
+ declare function createSheetsViewState(): SheetsViewState;
1744
+ /** Every condition in a group, depth first. */
1745
+ declare function filterConditionsOf(node: SheetsFilterNode): SheetsFilterCondition[];
1746
+ /**
1747
+ * The sort after a header click. A plain click cycles that column alone
1748
+ * (ascending, descending, none) and replaces any other key. An additive click
1749
+ * (Shift) adds the column as the last key, flips it, or removes it, and keeps
1750
+ * the other keys.
1751
+ */
1752
+ declare function cycleSort(sort: readonly SheetsSortKey[], column: string, additive: boolean): SheetsSortKey[];
1753
+
1754
+ /**
1755
+ * Column layout: pure helpers over `SheetsColumnLayout`.
1756
+ *
1757
+ * `available` is always the table's grid column keys in the table's order
1758
+ * (`gridColumnKeys(model)`). A layout names keys by field name, so it survives
1759
+ * a schema change: keys it names that the table lost are ignored here (and
1760
+ * reported by the validator), keys the table gained follow at the end.
1761
+ */
1762
+
1763
+ /** Row height of each setting, in pixels. */
1764
+ declare const ROW_HEIGHT_PX: Readonly<Record<SheetsRowHeight, number>>;
1765
+ /** The layout with every column shown in the table's order and the first column frozen. */
1766
+ declare function createColumnLayout(): SheetsColumnLayout;
1767
+ /** Every available key in display order: the layout's order first, then the rest in the table's order. */
1768
+ declare function orderedColumnKeys(available: readonly string[], layout: SheetsColumnLayout): string[];
1769
+ /** The keys that show, in display order. */
1770
+ declare function visibleColumnKeys(available: readonly string[], layout: SheetsColumnLayout): string[];
1771
+
1772
+ /**
1773
+ * Filter operators from the table model.
1774
+ *
1775
+ * A column offers exactly the operators its filter input really has
1776
+ * (`ColumnModel.filter.operators`). Each operator gets a plain label, a group,
1777
+ * and the value control its input shape and the column's kind call for. An
1778
+ * operator this file does not know still appears, named from its field name.
1779
+ */
1780
+
1781
+ type FilterOperatorGroup = 'match' | 'text' | 'compare' | 'items' | 'empty' | 'other';
1782
+ /** A control for one value. */
1783
+ type ScalarValueControl = {
1784
+ kind: 'text';
1785
+ }
1786
+ /** A whole number that fits a JavaScript number; sent as a number. */
1787
+ | {
1788
+ kind: 'integer';
1789
+ }
1790
+ /** A floating-point number; sent as a number. */
1791
+ | {
1792
+ kind: 'number';
1793
+ }
1794
+ /** A whole number of any size; sent as exact text. */
1795
+ | {
1796
+ kind: 'exact-integer';
1797
+ }
1798
+ /** A decimal number of any size; sent as exact text. */
1799
+ | {
1800
+ kind: 'exact-decimal';
1801
+ } | {
1802
+ kind: 'date';
1803
+ } | {
1804
+ kind: 'datetime';
1805
+ } | {
1806
+ kind: 'time';
1807
+ } | {
1808
+ kind: 'boolean';
1809
+ }
1810
+ /** One of a fixed list. `value` is the wire value. */
1811
+ | {
1812
+ kind: 'choice';
1813
+ options: readonly ColumnOption[];
1814
+ } | {
1815
+ kind: 'json';
1816
+ };
1817
+ interface FilterValueField {
1818
+ name: string;
1819
+ label: string;
1820
+ required: boolean;
1821
+ control: ScalarValueControl;
1822
+ }
1823
+ /** The control a condition shows for its operator. */
1824
+ type FilterValueControl = ScalarValueControl
1825
+ /** The operator takes no value from the user. */
1826
+ | {
1827
+ kind: 'none';
1828
+ }
1829
+ /** The operator takes a list of values. */
1830
+ | {
1831
+ kind: 'multi';
1832
+ item: ScalarValueControl;
1833
+ }
1834
+ /** The operator takes an object: one control per field. */
1835
+ | {
1836
+ kind: 'fields';
1837
+ fields: readonly FilterValueField[];
1838
+ }
1839
+ /** The editor cannot enter this operator's value. */
1840
+ | {
1841
+ kind: 'unsupported';
1842
+ reason: string;
1843
+ };
1844
+ interface FilterOperatorOption {
1845
+ /** Unique within a column: the operator name, or `isNull:true` / `isNull:false`. */
1846
+ id: string;
1847
+ /** Operator field name. */
1848
+ operator: string;
1849
+ label: string;
1850
+ group: FilterOperatorGroup;
1851
+ control: FilterValueControl;
1852
+ /** The operand of an operator that takes no value from the user (`isNull`). */
1853
+ fixedValue?: boolean;
1854
+ }
1855
+ /** The label of one operator on one column. */
1856
+ declare function filterOperatorLabel(column: ColumnModel, operator: string): string;
1857
+ /**
1858
+ * Every operator a column's filter has, as the builder offers them: grouped,
1859
+ * labelled, each with its value control. `isNull` becomes two choices, "is
1860
+ * empty" and "is not empty". Empty when the column cannot be filtered.
1861
+ */
1862
+ declare function filterOperatorOptions(column: ColumnModel): FilterOperatorOption[];
1863
+ /** The operator a new condition on this column starts with. */
1864
+ declare function defaultOperatorOption(column: ColumnModel): FilterOperatorOption | null;
1865
+
1077
1866
  interface SheetsPaginationProps {
1078
1867
  pageIndex: number;
1079
1868
  pageSize: number;
@@ -1083,9 +1872,29 @@ interface SheetsPaginationProps {
1083
1872
  }
1084
1873
  declare function SheetsPagination(props: SheetsPaginationProps): react.JSX.Element;
1085
1874
 
1875
+ interface SheetsStatusBarProps {
1876
+ /** Rows the server reports for the current filter and search; null until the first count for this view arrives. */
1877
+ total: number | null;
1878
+ /** A filter or a search narrows the rows ("12 matching rows"). */
1879
+ filtered: boolean;
1880
+ /** The rows are being fetched again; the count may change. */
1881
+ updating?: boolean;
1882
+ /** More status after the count (the grid passes its save status). */
1883
+ children?: ReactNode;
1884
+ }
1885
+ declare function SheetsStatusBar({ total, filtered, updating, children }: SheetsStatusBarProps): react.JSX.Element;
1886
+
1086
1887
  type TableWithCategory = {
1888
+ /** The value `onTableChange` receives and `activeTable` matches, for example a `TableModel.key`. */
1087
1889
  name: string;
1890
+ /** What the list shows. Default: `name`. The search matches both. */
1891
+ label?: string;
1088
1892
  category?: string;
1893
+ /**
1894
+ * A table a platform module made (see `isSystemTable` in `@constructive-io/data`). System tables
1895
+ * show in their own section, and only while "Show system tables" is on (off by default).
1896
+ */
1897
+ system?: boolean;
1089
1898
  };
1090
1899
  interface TableSelectorProps {
1091
1900
  tables: string[] | TableWithCategory[];
@@ -1099,6 +1908,48 @@ interface TableSelectorProps {
1099
1908
  }
1100
1909
  declare const SheetsTableSelector: react__default.NamedExoticComponent<TableSelectorProps>;
1101
1910
 
1911
+ /** Whether system tables show in table lists, and the setter every list on the page follows. */
1912
+ declare function useShowSystemTables(): [boolean, (show: boolean) => void];
1913
+ /**
1914
+ * The tables a list shows: the owner's, and the system tables only while they are shown. The open
1915
+ * table always stays, so a system table opened by a link or an address is never missing from the list.
1916
+ */
1917
+ declare function visibleTables<T extends {
1918
+ system?: boolean;
1919
+ }>(tables: readonly T[], showSystem: boolean, isOpen: (table: T) => boolean): T[];
1920
+
1921
+ interface UseTableModelOptions {
1922
+ /** Resolve the model. Default true. */
1923
+ enabled?: boolean;
1924
+ }
1925
+ interface UseTableModelResult {
1926
+ /** The model, or null while it loads or when it failed. */
1927
+ model: TableModel | null;
1928
+ /** `TableModel.key` of the requested table, or null until `_meta` has loaded or when the name is unknown. */
1929
+ tableKey: TableKey | null;
1930
+ /** The `_meta` entry of the table, or null. */
1931
+ metaTable: MetaschemaTable | null;
1932
+ /** True until the model is ready (or failed). */
1933
+ isLoading: boolean;
1934
+ /** Why the model is unavailable: `_meta` failed, the name is unknown or ambiguous, or this table failed. */
1935
+ error: Error | null;
1936
+ /** Load again what failed: `_meta` when it failed (the model follows), otherwise this table's model. */
1937
+ refetch: () => Promise<void>;
1938
+ }
1939
+ declare function useTableModel(tableRef: string | null | undefined, options?: UseTableModelOptions): UseTableModelResult;
1940
+ interface UseTableModelsResult {
1941
+ /** The models that have loaded, by `TableModel.key`. A table that failed or is unknown is absent. */
1942
+ models: ReadonlyMap<TableKey, TableModel>;
1943
+ /** True while `_meta` or any of the models still loads. */
1944
+ isLoading: boolean;
1945
+ }
1946
+ /**
1947
+ * The models of a variable set of tables (names or keys), with the same cache
1948
+ * entries as `useTableModel`. Unknown or ambiguous names are skipped; use
1949
+ * `useTableModel` for one table's error.
1950
+ */
1951
+ declare function useTableModels(refs: readonly string[], options?: UseTableModelOptions): UseTableModelsResult;
1952
+
1102
1953
  interface UseMetaOptions {
1103
1954
  enabled?: boolean;
1104
1955
  }
@@ -1109,10 +1960,14 @@ type DeleteIdentifier = SheetsRowIdentifier;
1109
1960
  /**
1110
1961
  * Unified table hook options
1111
1962
  */
1112
- interface UseTableOptions extends QueryOptions {
1963
+ interface UseTableOptions extends Omit<QueryOptions, 'where'> {
1964
+ /** A filter in the server's filter input shape (any operator the model reports, relation and search fields included). */
1965
+ where?: Readonly<Record<string, unknown>>;
1966
+ /** Columns to fetch (the primary key and relation keys are always added). Omitted: every readable column. */
1967
+ columns?: readonly string[];
1113
1968
  /** Enable/disable automatic data fetching */
1114
1969
  enabled?: boolean;
1115
- /** Field selection for queries */
1970
+ /** Field selection for queries: `includeRelations` (or the `full` preset) chooses the relations to select. */
1116
1971
  select?: FieldSelection;
1117
1972
  /** Mutation options */
1118
1973
  mutationOptions?: MutationOptions;
@@ -1124,7 +1979,11 @@ interface UseTableResult<TData extends RowRecord$1 = RowRecord$1> {
1124
1979
  data: TData[];
1125
1980
  totalCount: number;
1126
1981
  isLoading: boolean;
1982
+ /** True while a request for the current options is in flight, also while the previous rows are still shown. */
1983
+ isFetching: boolean;
1127
1984
  error: Error | null;
1985
+ /** The table model, or null while it loads or when it failed. */
1986
+ model: TableModel | null;
1128
1987
  findOne: (id: SheetsRowIdentifier) => Promise<TData | null>;
1129
1988
  create: (data: RowRecord$1) => Promise<{
1130
1989
  createdRow: TData | null;
@@ -1145,14 +2004,15 @@ interface UseTableResult<TData extends RowRecord$1 = RowRecord$1> {
1145
2004
  invalidate: () => void;
1146
2005
  }
1147
2006
  /**
1148
- * Generate query keys for consistent cache management
2007
+ * Generate query keys for consistent cache management. `tableRef` is a
2008
+ * `TableModel.key` or a table name.
1149
2009
  */
1150
2010
  declare const sheetsTableQueryKeys: {
1151
2011
  scope: (scope: SheetsScopeKey) => readonly ["sheets", SheetsScopeKey];
1152
- table: (scope: SheetsScopeKey, tableName: string) => readonly ["sheets", SheetsScopeKey, "table", string];
1153
- tableRows: (scope: SheetsScopeKey, tableName: string, options?: QueryOptions) => readonly ["sheets", SheetsScopeKey, "table", string, "rows", unknown];
1154
- tableRow: (scope: SheetsScopeKey, tableName: string, id: unknown) => readonly ["sheets", SheetsScopeKey, "table", string, "row", unknown];
1155
- tableCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown>) => readonly ["sheets", SheetsScopeKey, "table", string, "count", Record<string, unknown> | null | undefined];
2012
+ table: (scope: SheetsScopeKey, tableRef: string) => readonly ["sheets", SheetsScopeKey, "table", ...string[]];
2013
+ tableRows: (scope: SheetsScopeKey, tableRef: string, options?: unknown) => readonly ["sheets", SheetsScopeKey, "table", ...string[], "rows", unknown];
2014
+ tableRow: (scope: SheetsScopeKey, tableRef: string, id: unknown) => readonly ["sheets", SheetsScopeKey, "table", ...string[], "row", unknown];
2015
+ tableCount: (scope: SheetsScopeKey, tableRef: string, where?: Readonly<Record<string, unknown>>) => readonly ["sheets", SheetsScopeKey, "table", ...string[], "count", Readonly<Record<string, unknown>> | null | undefined];
1156
2016
  };
1157
2017
  /**
1158
2018
  * Main unified table hook
@@ -1165,7 +2025,10 @@ interface UseSheetsTableCursorOptions {
1165
2025
  enabled?: boolean;
1166
2026
  select?: FieldSelection;
1167
2027
  pageSize?: number;
1168
- where?: Filter;
2028
+ /** A filter in the server's filter input shape. */
2029
+ where?: Readonly<Record<string, unknown>>;
2030
+ /** Columns to fetch (the primary key and relation keys are always added). Omitted: every readable column. */
2031
+ columns?: readonly string[];
1169
2032
  orderBy?: Array<{
1170
2033
  field: string;
1171
2034
  direction: 'asc' | 'desc';
@@ -1182,35 +2045,107 @@ interface UseSheetsTableCursorResult<TData extends RowRecord = RowRecord> {
1182
2045
  }
1183
2046
  declare function useSheetsTableCursor<TData extends RowRecord = RowRecord>(tableName: string, options?: UseSheetsTableCursorOptions): UseSheetsTableCursorResult<TData>;
1184
2047
 
1185
- interface UploadProgress {
1186
- loaded: number;
1187
- total: number;
1188
- percentage: number;
2048
+ interface SendFileOptions extends TransferOptions {
2049
+ /** The row the file is for, passed to a host-injected uploader. */
2050
+ recordId?: string | number;
2051
+ }
2052
+ /** Sends one file to storage and resolves to its projection. */
2053
+ type SendFile = (file: File, options?: SendFileOptions) => Promise<FileProjection>;
2054
+ type ColumnUploadState = {
2055
+ status: 'ready';
2056
+ send: SendFile;
2057
+ } | {
2058
+ status: 'unavailable';
2059
+ reason: string;
2060
+ };
2061
+ interface ColumnStorage {
2062
+ choices: ResolvedUploadChoices;
2063
+ upload: ColumnUploadState;
2064
+ /** Resolves download URLs by file id, or null when this column's previews cannot be signed. */
2065
+ resolveUrls: ((ids: readonly string[]) => Promise<Map<string, string>>) | null;
2066
+ /** Identity of the URL resolver, for batching and caching. */
2067
+ previewKey: string | null;
1189
2068
  }
1190
- /** The value confirmed by the row update. Attachments store a public URL as text. */
1191
- type UploadResponse = SheetsFileValue | string | null;
1192
- interface UseFieldUploadOptions {
1193
- onProgress?: (progress: UploadProgress) => void;
1194
- onSuccess?: (data: UploadResponse) => void;
1195
- onError?: (error: Error) => void;
1196
- showToast?: boolean;
1197
- successMessage?: string;
1198
- successToastDelayMs?: number;
2069
+
2070
+ type UploadProgress = UploadProgressEvent;
2071
+ /** The value a file cell stores after a write: a projection, a link, a list, or null. */
2072
+ type UploadResponse = unknown;
2073
+ interface UseColumnStorageResult {
2074
+ storage: ColumnStorage | null;
2075
+ isLoading: boolean;
2076
+ error: Error | null;
2077
+ }
2078
+ /** Where a file column uploads to and how its previews are signed. Resolved once per column. */
2079
+ declare function useColumnStorage(table: TableModel | null | undefined, column: ColumnModel | null | undefined): UseColumnStorageResult;
2080
+ type FileUploadState = {
2081
+ status: 'loading';
2082
+ } | {
2083
+ status: 'ready';
2084
+ send: SendFile;
2085
+ } | {
2086
+ status: 'unavailable';
2087
+ reason: string;
2088
+ };
2089
+ /** Whether the column can take a new file now, and the uploader when it can. */
2090
+ declare function useFileUploadState(table: TableModel | null | undefined, column: ColumnModel | null | undefined, readOnlyReason?: string | null): FileUploadState;
2091
+ interface FileCellWriteJob {
2092
+ table: TableModel;
2093
+ column: ColumnModel;
2094
+ /** Primary-key identity of the row. */
2095
+ rowKey: SheetsRowIdentifier;
2096
+ /** Grid row id, which keys the cell's pending state. */
2097
+ rowId: string;
2098
+ value: unknown;
2099
+ /** Called when the server first answers that the file is still processing. */
2100
+ onProcessing?: () => void;
2101
+ signal?: AbortSignal;
1199
2102
  }
2103
+ /**
2104
+ * Write a file cell. While the server confirms the file the cell shows
2105
+ * "Processing file…"; a failure stays on the cell with a retry, even when the
2106
+ * editor has closed, so an uploaded file is never dropped silently.
2107
+ */
2108
+ declare function useFileCellWriter(): (job: FileCellWriteJob) => Promise<unknown>;
1200
2109
  interface FieldUploadTarget {
1201
- table: MetaTable$1;
1202
- allTables?: readonly MetaTable$1[];
1203
- fieldName: string;
1204
- recordId: SheetsRowIdentifier;
2110
+ table: TableModel;
2111
+ /** Column name. */
2112
+ column: string;
2113
+ rowKey: SheetsRowIdentifier;
1205
2114
  }
1206
2115
  interface FieldUploadTransport {
2116
+ /** Data executor for the cell write. */
1207
2117
  execute: SheetsExecuteFn;
1208
- executeUpload: SheetsUploadFn;
1209
2118
  adapter: Pick<SheetsBackendAdapter, 'updateRow'>;
2119
+ /** Sends the file to storage (from `useColumnStorage(...).storage.upload`). */
2120
+ send: SendFile;
2121
+ policy?: ProcessingPolicy;
1210
2122
  onProgress?: (progress: UploadProgress) => void;
2123
+ onProcessing?: () => void;
2124
+ signal?: AbortSignal;
1211
2125
  }
1212
- /** Upload and persist a media value, or pass null to clear the cell. */
1213
- declare function executeFieldUpload({ table: meta, allTables, fieldName, recordId }: FieldUploadTarget, file: File | null, { execute, executeUpload, adapter, onProgress }: FieldUploadTransport): Promise<UploadResponse>;
2126
+ /**
2127
+ * Upload one file into a single-file column, or clear it with null, and write
2128
+ * the cell. A list column takes its whole list: write it with
2129
+ * {@link useFileCellWriter}.
2130
+ */
2131
+ declare function executeFieldUpload(target: FieldUploadTarget, file: File | null, transport: FieldUploadTransport): Promise<UploadResponse>;
2132
+ /** @deprecated Options of {@link useSheetsFieldUpload}. */
2133
+ interface UseFieldUploadOptions {
2134
+ onProgress?: (progress: UploadProgress) => void;
2135
+ onSuccess?: (data: UploadResponse) => void;
2136
+ onError?: (error: Error) => void;
2137
+ /** Ignored, as before. */
2138
+ showToast?: boolean;
2139
+ /** Ignored, as before. */
2140
+ successMessage?: string;
2141
+ /** Ignored, as before. */
2142
+ successToastDelayMs?: number;
2143
+ }
2144
+ /**
2145
+ * @deprecated Use {@link useFileUploadState} with {@link useFileCellWriter}, or
2146
+ * {@link executeFieldUpload}. Uploads one file into a single-file column (or
2147
+ * clears it with null) through the model-driven path.
2148
+ */
1214
2149
  declare function useSheetsFieldUpload(tableName: string, fieldName: string, recordId: SheetsRowIdentifier | null, options?: UseFieldUploadOptions): {
1215
2150
  write: (id: SheetsRowIdentifier, file: File | null) => Promise<UploadResponse>;
1216
2151
  resolveRowIdentifier: (row: Readonly<Record<string, unknown>>) => SheetsRowIdentifier | null;
@@ -1222,14 +2157,14 @@ declare function useSheetsFieldUpload(tableName: string, fieldName: string, reco
1222
2157
  isPending: false;
1223
2158
  isSuccess: false;
1224
2159
  status: "idle";
1225
- mutate: _tanstack_react_query.UseMutateFunction<UploadResponse, Error, File | null, unknown>;
2160
+ mutate: _tanstack_react_query.UseMutateFunction<unknown, Error, File | null, unknown>;
1226
2161
  reset: () => void;
1227
2162
  context: unknown;
1228
2163
  failureCount: number;
1229
2164
  failureReason: Error | null;
1230
2165
  isPaused: boolean;
1231
2166
  submittedAt: number;
1232
- mutateAsync: _tanstack_react_query.UseMutateAsyncFunction<UploadResponse, Error, File | null, unknown>;
2167
+ mutateAsync: _tanstack_react_query.UseMutateAsyncFunction<unknown, Error, File | null, unknown>;
1233
2168
  } | {
1234
2169
  write: (id: SheetsRowIdentifier, file: File | null) => Promise<UploadResponse>;
1235
2170
  resolveRowIdentifier: (row: Readonly<Record<string, unknown>>) => SheetsRowIdentifier | null;
@@ -1241,14 +2176,14 @@ declare function useSheetsFieldUpload(tableName: string, fieldName: string, reco
1241
2176
  isPending: true;
1242
2177
  isSuccess: false;
1243
2178
  status: "pending";
1244
- mutate: _tanstack_react_query.UseMutateFunction<UploadResponse, Error, File | null, unknown>;
2179
+ mutate: _tanstack_react_query.UseMutateFunction<unknown, Error, File | null, unknown>;
1245
2180
  reset: () => void;
1246
2181
  context: unknown;
1247
2182
  failureCount: number;
1248
2183
  failureReason: Error | null;
1249
2184
  isPaused: boolean;
1250
2185
  submittedAt: number;
1251
- mutateAsync: _tanstack_react_query.UseMutateAsyncFunction<UploadResponse, Error, File | null, unknown>;
2186
+ mutateAsync: _tanstack_react_query.UseMutateAsyncFunction<unknown, Error, File | null, unknown>;
1252
2187
  } | {
1253
2188
  write: (id: SheetsRowIdentifier, file: File | null) => Promise<UploadResponse>;
1254
2189
  resolveRowIdentifier: (row: Readonly<Record<string, unknown>>) => SheetsRowIdentifier | null;
@@ -1260,18 +2195,18 @@ declare function useSheetsFieldUpload(tableName: string, fieldName: string, reco
1260
2195
  isPending: false;
1261
2196
  isSuccess: false;
1262
2197
  status: "error";
1263
- mutate: _tanstack_react_query.UseMutateFunction<UploadResponse, Error, File | null, unknown>;
2198
+ mutate: _tanstack_react_query.UseMutateFunction<unknown, Error, File | null, unknown>;
1264
2199
  reset: () => void;
1265
2200
  context: unknown;
1266
2201
  failureCount: number;
1267
2202
  failureReason: Error | null;
1268
2203
  isPaused: boolean;
1269
2204
  submittedAt: number;
1270
- mutateAsync: _tanstack_react_query.UseMutateAsyncFunction<UploadResponse, Error, File | null, unknown>;
2205
+ mutateAsync: _tanstack_react_query.UseMutateAsyncFunction<unknown, Error, File | null, unknown>;
1271
2206
  } | {
1272
2207
  write: (id: SheetsRowIdentifier, file: File | null) => Promise<UploadResponse>;
1273
2208
  resolveRowIdentifier: (row: Readonly<Record<string, unknown>>) => SheetsRowIdentifier | null;
1274
- data: UploadResponse;
2209
+ data: unknown;
1275
2210
  error: null;
1276
2211
  variables: File | null;
1277
2212
  isError: false;
@@ -1279,40 +2214,84 @@ declare function useSheetsFieldUpload(tableName: string, fieldName: string, reco
1279
2214
  isPending: false;
1280
2215
  isSuccess: true;
1281
2216
  status: "success";
1282
- mutate: _tanstack_react_query.UseMutateFunction<UploadResponse, Error, File | null, unknown>;
2217
+ mutate: _tanstack_react_query.UseMutateFunction<unknown, Error, File | null, unknown>;
1283
2218
  reset: () => void;
1284
2219
  context: unknown;
1285
2220
  failureCount: number;
1286
2221
  failureReason: Error | null;
1287
2222
  isPaused: boolean;
1288
2223
  submittedAt: number;
1289
- mutateAsync: _tanstack_react_query.UseMutateAsyncFunction<UploadResponse, Error, File | null, unknown>;
2224
+ mutateAsync: _tanstack_react_query.UseMutateAsyncFunction<unknown, Error, File | null, unknown>;
1290
2225
  };
1291
2226
 
2227
+ interface UploadToFilesTableOptions {
2228
+ /**
2229
+ * The storage service: its GraphQL endpoint and an executor bound to it. Pass the
2230
+ * same object on every call; the storage catalog and schema lookups are cached on it.
2231
+ */
2232
+ storage: SheetsStorageTransport;
2233
+ /** The files table: its `TableModel.key`, its GraphQL type name, or its model. */
2234
+ filesTable: string | Pick<TableModel, 'key' | 'name'>;
2235
+ file: File;
2236
+ /** Owner of the file, for a files table whose uploads need one. Sent only when the mutation takes `ownerId`. */
2237
+ ownerId?: string;
2238
+ /** Bucket to upload into. Sent only when the mutation takes `bucketKey`. */
2239
+ bucketKey?: string;
2240
+ /** Without a bucket key, the public (true, the default) or private default bucket. Sent only when the mutation takes `isPublic`. */
2241
+ isPublic?: boolean;
2242
+ /** Sent only when the mutation takes `databaseId`. */
2243
+ databaseId?: string;
2244
+ /** Cancels the request and the PUT. The promise then rejects with an `AbortError`. */
2245
+ signal?: AbortSignal;
2246
+ onProgress?: (progress: UploadProgressEvent) => void;
2247
+ /** Reads `_meta`, table models and bucket rows. Default: the built-in adapter. */
2248
+ adapter?: Pick<SheetsBackendAdapter, 'fetchMeta' | 'fetchTableModel' | 'listRows'>;
2249
+ }
2250
+ interface UploadedFile {
2251
+ /** Id of the files table row. */
2252
+ fileId: string;
2253
+ /** The stored file as the storage service returned it: the value a file column stores. */
2254
+ file: FileProjection;
2255
+ /** True when the service already held these bytes; no PUT was sent and `file` is the existing file. */
2256
+ deduplicated: boolean;
2257
+ }
2258
+ /**
2259
+ * Upload `file` into `filesTable` and return the stored file and its id. Rejects
2260
+ * with the reason when the storage service does not offer uploads for that
2261
+ * table, when a required input (an owner id) is missing, when the bucket would
2262
+ * refuse the file, or when the request or the PUT fails.
2263
+ */
2264
+ declare function uploadToFilesTable(options: UploadToFilesTableOptions): Promise<UploadedFile>;
2265
+
1292
2266
  declare function isSheetsScopeKey(value: unknown): value is SheetsScopeKey;
1293
2267
  declare const sheetsQueryKeys: {
1294
2268
  readonly root: readonly ["sheets"];
1295
2269
  readonly scope: (scope: SheetsScopeKey) => readonly ["sheets", SheetsScopeKey];
1296
2270
  readonly meta: (scope: SheetsScopeKey) => readonly ["sheets", SheetsScopeKey, "meta"];
2271
+ /** One table model, per `_meta` version and display override. */
2272
+ readonly tableModel: (scope: SheetsScopeKey, tableKey: string, metaVersion: number, displayKey: string | null) => readonly ["sheets", SheetsScopeKey, "table-model", ...string[], number, string | null];
1297
2273
  readonly mediaUrl: (scope: SheetsScopeKey, endpoint: string | undefined, id: string | null) => readonly ["sheets", SheetsScopeKey, "media-url", string | undefined, string | null];
1298
- readonly typeFields: (scope: SheetsScopeKey, typeName: string) => readonly ["sheets", SheetsScopeKey, "type-fields", string];
1299
- readonly enumValues: (scope: SheetsScopeKey, typeName: string) => readonly ["sheets", SheetsScopeKey, "enum-values", string];
1300
- readonly relations: (scope: SheetsScopeKey, tableName: string) => readonly ["sheets", SheetsScopeKey, "relations", string];
1301
- readonly table: (scope: SheetsScopeKey, tableName: string) => readonly ["sheets", SheetsScopeKey, "table", string];
1302
- readonly tableRows: (scope: SheetsScopeKey, tableName: string, options?: unknown) => readonly ["sheets", SheetsScopeKey, "table", string, "rows", unknown];
1303
- readonly tableRow: (scope: SheetsScopeKey, tableName: string, id: unknown) => readonly ["sheets", SheetsScopeKey, "table", string, "row", unknown];
1304
- readonly tableCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown> | null) => readonly ["sheets", SheetsScopeKey, "table", string, "count", Record<string, unknown> | null | undefined];
1305
- readonly infiniteTable: (scope: SheetsScopeKey, tableName: string) => readonly ["sheets", SheetsScopeKey, "infinite-table", string];
1306
- readonly infiniteTablePage: (scope: SheetsScopeKey, tableName: string, pageIndex: number, options: unknown) => readonly ["sheets", SheetsScopeKey, "infinite-table", string, "page", number, unknown];
1307
- readonly infiniteTableTotalCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown>) => readonly ["sheets", SheetsScopeKey, "infinite-table", string, "totalCount", Record<string, unknown> | undefined];
1308
- readonly cursorTable: (scope: SheetsScopeKey, tableName: string, options?: unknown) => readonly ["sheets", SheetsScopeKey, "cursor-table", string, unknown];
2274
+ readonly relations: (scope: SheetsScopeKey, tableName: string) => readonly ["sheets", SheetsScopeKey, "relations", ...string[]];
2275
+ readonly table: (scope: SheetsScopeKey, tableRef: string) => readonly ["sheets", SheetsScopeKey, "table", ...string[]];
2276
+ readonly tableRows: (scope: SheetsScopeKey, tableRef: string, options?: unknown) => readonly ["sheets", SheetsScopeKey, "table", ...string[], "rows", unknown];
2277
+ readonly tableRow: (scope: SheetsScopeKey, tableRef: string, id: unknown) => readonly ["sheets", SheetsScopeKey, "table", ...string[], "row", unknown];
2278
+ readonly tableCount: (scope: SheetsScopeKey, tableRef: string, where?: Readonly<Record<string, unknown>> | null) => readonly ["sheets", SheetsScopeKey, "table", ...string[], "count", Readonly<Record<string, unknown>> | null | undefined];
2279
+ readonly infiniteTable: (scope: SheetsScopeKey, tableRef: string) => readonly ["sheets", SheetsScopeKey, "infinite-table", ...string[]];
2280
+ readonly infiniteTablePage: (scope: SheetsScopeKey, tableRef: string, pageIndex: number, options: unknown) => readonly ["sheets", SheetsScopeKey, "infinite-table", ...string[], "page", number, unknown];
2281
+ readonly infiniteTableTotalCount: (scope: SheetsScopeKey, tableRef: string, where?: Readonly<Record<string, unknown>>) => readonly ["sheets", SheetsScopeKey, "infinite-table", ...string[], "totalCount", Readonly<Record<string, unknown>> | undefined];
2282
+ readonly cursorTable: (scope: SheetsScopeKey, tableRef: string, options?: unknown) => readonly ["sheets", SheetsScopeKey, "cursor-table", ...string[], unknown];
1309
2283
  };
1310
-
1311
2284
  /**
1312
- * Create the default PostGraphile-backed adapter. The metadata preflight makes
1313
- * an outdated endpoint distinguishable from an ordinary transport failure,
1314
- * while the WeakMap deduplicates that introspection for each executor/session.
2285
+ * Mutation keys. Every mutation a Sheets hook creates sits under its table's
2286
+ * query key, `[...table(scope, tableRef), 'mutation', operation, ...detail]`, so
2287
+ * `useIsMutating({ mutationKey: sheetsMutationKeys.table(scope, ref) })` counts
2288
+ * every write in flight on that table.
1315
2289
  */
2290
+ declare const sheetsMutationKeys: {
2291
+ /** Every mutation of a table, or one operation of it when `operation` is given. */
2292
+ readonly table: (scope: SheetsScopeKey, tableRef: string, operation?: string, ...detail: readonly unknown[]) => readonly ["sheets", SheetsScopeKey, "table", ...unknown[]];
2293
+ };
2294
+
1316
2295
  declare function createPostGraphileAdapter(): SheetsBackendAdapter;
1317
2296
 
1318
2297
  /**
@@ -1381,13 +2360,16 @@ declare const ENHANCED_TYPES: Set<string>;
1381
2360
  declare const BUILTIN_EDITOR_TYPES: Set<string>;
1382
2361
  /** Cell types that are never editable (always read-only). */
1383
2362
  declare const NON_EDITABLE_TYPES: Set<string>;
1384
- /** Cell types that can be activated for viewing but not editing. */
2363
+ /** Cell types that open a read-only viewer (show and copy the value) instead of an editor. */
1385
2364
  declare const VIEWER_ONLY_TYPES: Set<string>;
1386
2365
 
1387
2366
  /**
1388
- * Maps GraphQL field metadata to frontend cell types
1389
- * Uses priority: pgAlias > pgType > gqlType for type determination
1390
- * This is completely backend-agnostic and focuses only on frontend rendering needs
2367
+ * Maps raw `_meta` field metadata to a frontend cell type (priority: encoding >
2368
+ * pgType > gqlType).
2369
+ *
2370
+ * @deprecated The grid routes every column from its table model
2371
+ * (`cellTypeForColumn` over a `ColumnModel`). This mapping reads raw `_meta` only and
2372
+ * is kept for hosts that call it directly.
1391
2373
  */
1392
2374
  declare function mapToFrontendCellType(metadata: {
1393
2375
  gqlType: string;
@@ -1456,7 +2438,9 @@ interface ExtractedRange {
1456
2438
  declare function getCellsInRange(range: SelectionRect, rows: readonly unknown[], columnKeys: readonly string[], getDisplay?: (value: unknown, rowIndex: number, colKey: string) => unknown): ExtractedRange;
1457
2439
  /**
1458
2440
  * Serialize a value matrix to TSV (tab-joined cols, newline-joined rows). Each value
1459
- * is stringified; `null`/`undefined` become an empty cell. Spreadsheet-paste shape —
2441
+ * is stringified (an object as JSON); `null`/`undefined` become an empty cell. A cell
2442
+ * with a tab, a line break or a leading quote is quoted (`"two\nlines"`, inner quotes
2443
+ * doubled), so multi-line text survives a copy and paste. Spreadsheet-paste shape —
1460
2444
  * reused by P4 copy.
1461
2445
  */
1462
2446
  declare function toTSV(values: readonly (readonly unknown[])[]): string;
@@ -1533,6 +2517,13 @@ interface BuildFormSpecOptions {
1533
2517
  multilineFields?: Set<string>;
1534
2518
  }
1535
2519
 
2520
+ /**
2521
+ * Build a form spec from a raw `_meta` table.
2522
+ *
2523
+ * @deprecated Use `buildModelFormSpec(tableModel, mode)` and `buildModelFormSchema(spec)`:
2524
+ * they follow the table model's write flags, limits and choices, and check values with
2525
+ * the same rules as the grid.
2526
+ */
1536
2527
  declare function buildScalarFormSpec(metaTable: MetaTable, options?: BuildFormSpecOptions): DynamicFormSpec | null;
1537
2528
  declare function findTableFormSpec(meta: MetaTable[] | null | undefined, tableName: string, options?: BuildFormSpecOptions): DynamicFormSpec | null;
1538
2529
 
@@ -1548,47 +2539,201 @@ declare function useDynamicUpdate(tableName: string, rowId: SheetsRowIdentifier)
1548
2539
 
1549
2540
  declare function createMetadataHash(value: unknown): string;
1550
2541
 
2542
+ /** Whether the form creates a record or edits an existing one. */
2543
+ type ModelFormMode = 'create' | 'update';
2544
+ interface ModelFormField {
2545
+ /** Field name on the row (also the key in the form values). */
2546
+ name: string;
2547
+ /** Readable label. */
2548
+ label: string;
2549
+ /** Column comment, or null. */
2550
+ description: string | null;
2551
+ /** The table-model column. */
2552
+ column: ColumnModel;
2553
+ /** The cell type key the grid uses for this column (a built-in cell type or a host override); it picks the editor. */
2554
+ cellType: string;
2555
+ /** The form may set this field in this mode. */
2556
+ writable: boolean;
2557
+ /** Why the field cannot be set in this mode, or null when it can. */
2558
+ readOnlyReason: string | null;
2559
+ /** A value must be given: create requires it (no default), or an edit cannot empty it. */
2560
+ required: boolean;
2561
+ /** The column accepts no value. */
2562
+ nullable: boolean;
2563
+ /** Fixed choices, or null. `value` is what is stored. */
2564
+ options: readonly ColumnOption[] | null;
2565
+ maxLength: number | null;
2566
+ precision: number | null;
2567
+ scale: number | null;
2568
+ }
2569
+ interface ModelFormSpec {
2570
+ /** `TableModel.key` of the table. */
2571
+ tableKey: string;
2572
+ /** GraphQL type name of the table. */
2573
+ tableName: string;
2574
+ mode: ModelFormMode;
2575
+ /** Changes whenever a field's rules change; use it as a cache key. */
2576
+ versionHash: string;
2577
+ /** Readable fields, in column order. */
2578
+ fields: ModelFormField[];
2579
+ }
2580
+ interface BuildModelFormSpecOptions {
2581
+ /** Host cell-type overrides keyed by `tableName.fieldName` (`SheetsConfig.fieldTypeOverrides`). */
2582
+ typeOverrides?: Readonly<Record<string, string>>;
2583
+ }
2584
+ /**
2585
+ * Build the fields of a create or edit form from the table model. Each field's cell
2586
+ * type and read-only reason come from the grid's own routing (`resolveModelCellRoute`:
2587
+ * a create is routed like a draft row, an edit like a saved row with its key fixed),
2588
+ * so a form and a grid cell never disagree.
2589
+ */
2590
+ declare function buildModelFormSpec(model: TableModel, mode: ModelFormMode, options?: BuildModelFormSpecOptions): ModelFormSpec;
2591
+ /**
2592
+ * Build the validation schema of a model form. Only writable fields are in it; each
2593
+ * one is checked and parsed by the column's rules. Unknown keys are dropped, so a
2594
+ * read-only field can never reach a write.
2595
+ */
2596
+ declare function buildModelFormSchema(spec: ModelFormSpec): z.ZodObject<Record<string, z.ZodType<unknown>>>;
2597
+
2598
+ /**
2599
+ * Map a table-model column to its cell type. A list column routes to a list cell
2600
+ * type (the editor validates each element by the column's value kind); a column with
2601
+ * a fixed option list routes to a choice cell type.
2602
+ */
2603
+ declare function cellTypeForColumn(column: ColumnModel): CellType;
2604
+
2605
+ type ColumnInputResult = {
2606
+ ok: true;
2607
+ value: unknown;
2608
+ } | {
2609
+ ok: false;
2610
+ reason: string;
2611
+ };
2612
+ interface ColumnInputOptions {
2613
+ /**
2614
+ * The input is text the user typed or pasted, so JSON and lists are read from
2615
+ * the text. False (the default) for a value an editor, a fill or an undo produced.
2616
+ */
2617
+ fromText?: boolean;
2618
+ /**
2619
+ * The value is for a record not created yet (a new row, the new-record form): clearing a
2620
+ * required text field keeps '' there, since the create checks the required fields as a whole.
2621
+ */
2622
+ creating?: boolean;
2623
+ }
2624
+ /**
2625
+ * Turn a user's input into the value the column stores, or say why it does not fit.
2626
+ * Empty input clears the column (see `clearedValue`). The result is still encoded by
2627
+ * the write codec (`encodeWriteValues`) before it is sent.
2628
+ */
2629
+ declare function parseColumnInput(column: ColumnModel, input: unknown, options?: ColumnInputOptions): ColumnInputResult;
2630
+ /**
2631
+ * Text for one value when it leaves the grid (copy, export). Structured values and
2632
+ * JSON are written as JSON so a paste reads them back exactly; choices use their label.
2633
+ */
2634
+ declare function formatColumnValue(column: ColumnModel | null | undefined, value: unknown): string;
2635
+
2636
+ type WriteAction = 'update' | 'create' | 'delete';
2637
+ /** Every distinct message of a failed write, in plain words. */
2638
+ declare function writeErrorMessages(error: unknown, action: WriteAction): string[];
2639
+ /** One failed write, as the grid shows it. */
2640
+ interface WriteErrorReport {
2641
+ id: string;
2642
+ title: string;
2643
+ messages: readonly string[];
2644
+ }
2645
+
1551
2646
  /**
1552
2647
  * Grid Feedback Reducer
1553
2648
  *
1554
- * Manages transient UI feedback state for data grid bulk operations.
1555
- * Uses vanilla React (useReducer) instead of Zustand since this state is:
1556
- * - Local to the data grid component tree
1557
- * - Ephemeral (no persistence needed)
1558
- * - Automatically cleaned up on unmount
2649
+ * One save status for every write the grid makes: cell saves (an edit, a paste, a
2650
+ * fill, undo and redo), new rows, deletes, and the editors and record panel that
2651
+ * save on their own. Writes that overlap share the status: it reads "saving" while
2652
+ * any write is in flight and settles once, when the last one ends, to one outcome
2653
+ * for all of them. So two saves can never show two checks, and a fast save cannot
2654
+ * replace the outcome of a slow one that is still running.
2655
+ *
2656
+ * Failed writes are also kept as reports (`writeErrors`) until the user dismisses
2657
+ * them, so a message is never lost when the status clears.
2658
+ *
2659
+ * Uses vanilla React (useReducer): the state is local to the grid, ephemeral, and
2660
+ * cleaned up on unmount.
1559
2661
  */
2662
+
1560
2663
  type OperationStatus = 'idle' | 'pending' | 'success' | 'partial' | 'error';
2664
+ /** What a write does. `update` saves values, `submit` creates rows, `delete` removes rows. */
2665
+ type OperationType = 'delete' | 'submit' | 'update';
2666
+ /** The save status the grid shows. */
1561
2667
  interface OperationFeedback {
2668
+ /** Stable while the status is on screen, so a new write changes it in place. */
1562
2669
  id: string;
1563
- type: 'delete' | 'submit' | 'update';
2670
+ type: OperationType;
1564
2671
  status: OperationStatus;
1565
2672
  message: string;
1566
2673
  total: number;
1567
2674
  completed: number;
1568
2675
  failed: number;
2676
+ /** When the status last changed. A settled status is cleared `dismissAfter` ms after it. */
1569
2677
  timestamp: number;
1570
- /** Auto-dismiss duration in ms. 0 = persistent until manually cleared. */
2678
+ /** Auto-dismiss duration in ms. 0 = shown until it changes. */
1571
2679
  dismissAfter: number;
1572
2680
  }
2681
+ /** One write in flight. */
2682
+ interface PendingWrite {
2683
+ id: string;
2684
+ type: OperationType;
2685
+ total: number;
2686
+ completed: number;
2687
+ failed: number;
2688
+ }
2689
+ /** One write that ended while others in the same status were running or had ended. */
2690
+ interface EndedWrite {
2691
+ type: OperationType;
2692
+ status: 'success' | 'partial' | 'error';
2693
+ message: string;
2694
+ }
1573
2695
  interface FeedbackState {
1574
- /** Current bulk operation feedback (shown in floating status) */
2696
+ /** The save status (shown in the status bar), or null when there is nothing to show. */
1575
2697
  operation: OperationFeedback | null;
2698
+ /** Writes in flight. */
2699
+ pending: readonly PendingWrite[];
2700
+ /** Writes that ended since the status was last idle or settled. */
2701
+ ended: readonly EndedWrite[];
2702
+ /** Failed writes, newest last, until the user dismisses them. */
2703
+ writeErrors: readonly WriteErrorReport[];
1576
2704
  }
1577
2705
 
2706
+ /** The words for one write's outcome: what the status says when it saved and when it did not. */
2707
+ interface WriteMessages {
2708
+ saved: string;
2709
+ failed: string;
2710
+ }
1578
2711
  interface FeedbackContextValue {
1579
2712
  state: FeedbackState;
1580
- startOperation: (type: OperationFeedback['type'], total: number) => string;
2713
+ startOperation: (type: OperationType, total: number) => string;
1581
2714
  updateOperationProgress: (id: string, completed: number, failed: number) => void;
1582
- completeOperation: (id: string, status: 'success' | 'partial' | 'error', message: string, dismissAfter?: number) => void;
2715
+ completeOperation: (id: string, status: 'success' | 'partial' | 'error', message: string,
2716
+ /** Keep the settled status at least this long (ms); the default depends on the status. */
2717
+ dismissAfter?: number) => void;
1583
2718
  clearOperationFeedback: () => void;
2719
+ /** Run one write under the save status; its error is re-thrown after it is reported. */
2720
+ trackWrite: <T>(type: OperationType, total: number, run: () => Promise<T>, messages: WriteMessages) => Promise<T>;
2721
+ /** Report a write that already ended (an editor that saves on its own). */
2722
+ noteWrite: (type: OperationType, status: 'success' | 'error', message: string) => void;
2723
+ /** Show a failed write until the user dismisses it. */
2724
+ reportWriteError: (title: string, messages: readonly string[]) => WriteErrorReport;
2725
+ dismissWriteError: (id: string) => void;
2726
+ clearWriteErrors: () => void;
1584
2727
  }
1585
2728
  interface FeedbackProviderProps {
1586
2729
  children: React.ReactNode;
1587
2730
  }
1588
2731
  declare function FeedbackProvider({ children }: FeedbackProviderProps): react.JSX.Element;
1589
2732
  declare function useFeedback(): FeedbackContextValue;
2733
+ /** The feedback of the grid around this component, or null outside a grid (a standalone record panel). */
2734
+ declare function useOptionalFeedback(): FeedbackContextValue | null;
1590
2735
  /**
1591
- * Hook for accessing only operation feedback - useful for dock status bar
2736
+ * The save status alone - useful for a status indicator.
1592
2737
  */
1593
2738
  declare function useOperationFeedback(): OperationFeedback | null;
1594
2739
 
@@ -1624,6 +2769,25 @@ interface FloatingStatusProps {
1624
2769
  */
1625
2770
  declare function FloatingStatus({ className }: FloatingStatusProps): react.JSX.Element;
1626
2771
 
2772
+ declare function SaveStatus({ className }: {
2773
+ className?: string;
2774
+ }): react.JSX.Element;
2775
+
2776
+ /**
2777
+ * Failed writes, each with every message the server returned. They stay until
2778
+ * the user dismisses them, so a message is never lost to a timeout.
2779
+ */
2780
+ declare function WriteErrorStack({ className }: {
2781
+ className?: string;
2782
+ }): react.JSX.Element | null;
2783
+
2784
+ interface ModelIssuesNoticeProps {
2785
+ model: TableModel | null;
2786
+ dropped: readonly SheetsViewStateDrop[];
2787
+ columnLabel: (name: string) => string;
2788
+ }
2789
+ declare function ModelIssuesNotice({ model, dropped, columnLabel }: ModelIssuesNoticeProps): react.JSX.Element | null;
2790
+
1627
2791
  interface SheetsErrorBoundaryProps {
1628
2792
  children: ReactNode;
1629
2793
  /** Called when a render error is caught. Mirrors SheetsConfig.onError. */
@@ -1653,9 +2817,11 @@ declare class SheetsErrorBoundary extends Component<SheetsErrorBoundaryProps, Sh
1653
2817
  interface SheetsErrorStateProps {
1654
2818
  error: unknown;
1655
2819
  onRetry?: () => void;
2820
+ /** The table that failed. Only this table's grid shows the error; other tables keep working. */
2821
+ tableName?: string;
1656
2822
  }
1657
- /** Shown when the table data (or its metadata) fails to load. */
1658
- declare function SheetsErrorState({ error, onRetry }: SheetsErrorStateProps): react.JSX.Element;
2823
+ /** Shown when one table's rows (or its model) fail to load. */
2824
+ declare function SheetsErrorState({ error, onRetry, tableName }: SheetsErrorStateProps): react.JSX.Element;
1659
2825
  interface SheetsEmptyStateProps {
1660
2826
  tableName?: string;
1661
2827
  onAddRow?: () => void;
@@ -1670,34 +2836,34 @@ declare function SheetsEmptyState({ tableName, onAddRow, readOnlyReason }: Sheet
1670
2836
  */
1671
2837
  declare function SheetsLoadingState(): react.JSX.Element;
1672
2838
 
2839
+ /** Filter bindings for a headless shell. */
1673
2840
  interface DataFilteringContextValue {
1674
- filterTree: FilterGroup;
1675
- filtersOpen: boolean;
1676
- effectiveWhere: any;
1677
- hasActiveFilters: boolean;
1678
- setFilterTree: (tree: FilterGroup) => void;
1679
- setFiltersOpen: (open: boolean) => void;
1680
- clearAllFilters: () => void;
1681
- applyFilters: () => void;
2841
+ /** The filters in use, valid for the model. */
2842
+ filters: SheetsFilterGroup;
2843
+ setFilters: (filters: SheetsFilterGroup) => void;
2844
+ clearFilters: () => void;
2845
+ /** The list filter for the conditions that are complete and valid, or undefined. */
2846
+ where: Record<string, unknown> | undefined;
2847
+ /** Conditions in `where`. */
2848
+ appliedCount: number;
2849
+ /** Status of every condition, by condition id. */
2850
+ conditions: ReadonlyMap<string, ConditionStatus>;
2851
+ /** Conditions of `initialFilters` the model does not support. */
2852
+ dropped: readonly SheetsViewStateDrop[];
1682
2853
  }
1683
2854
  interface UseDataFilteringConfig {
1684
- columnKeys: string[];
1685
- tableMeta?: {
1686
- fields?: Array<{
1687
- name?: string | null;
1688
- type?: {
1689
- gqlType?: string | null;
1690
- } | null;
1691
- } | null> | null;
1692
- } | null;
1693
- initialFilterTree?: FilterGroup;
2855
+ /** The table model, or null while it loads. */
2856
+ model: TableModel | null;
2857
+ /** Filters to start with, for example from a saved view. */
2858
+ initialFilters?: SheetsFilterGroup;
2859
+ /** Models of related tables, for "linked record contains" conditions. */
2860
+ relatedModel?: (key: TableKey) => TableModel | null;
1694
2861
  }
1695
- declare function useDataFiltering({ columnKeys, tableMeta, initialFilterTree, }: UseDataFilteringConfig): {
1696
- contextValue: DataFilteringContextValue;
1697
- Provider: ({ children }: {
1698
- children: ReactNode;
1699
- }) => ReactNode;
1700
- };
2862
+ /**
2863
+ * Headless filter state over the table model, for a custom shell. The built-in
2864
+ * grid uses the same pieces through `useSheetsView`.
2865
+ */
2866
+ declare function useDataFiltering({ model, initialFilters, relatedModel }: UseDataFilteringConfig): DataFilteringContextValue;
1701
2867
 
1702
2868
  interface DataPaginationContextValue {
1703
2869
  pageIndex: number;
@@ -1728,4 +2894,4 @@ declare function useDataPagination({ initialPageSize, initialPageIndex, totalCou
1728
2894
  }) => any;
1729
2895
  };
1730
2896
 
1731
- export { BOOLEAN_TYPES, BUILTIN_EDITOR_TYPES, type Binding, CellPlugin, CellProps, CellRegistry, CellRegistryEntry, CellRenderer, type CellSlot, type CellSlots, CellType, type CellTypeBuiltins, CellTypeDefinition, CellTypeMatchInput, type CellTypeRegistry, ColumnSchema, type CommandResult, DATE_TIME_TYPES, type DataFilteringContextValue, type DataPaginationContextValue, type DispatchEvent, DockStatusBar, DockStatusBarCompact, type DraftMeta, type DraftRow, type DynamicFormSpec, ENHANCED_TYPES, EditorProps, type ExtractedRange, FeedbackProvider, type FieldTypeMap, type FilterCondition, type FilterGroup, type FilterNode, type FilterValue, FloatingStatus, GEOMETRY_TYPES, type GridCommand, type GridCommandContext, type Interceptor, MAX_FILTER_DEPTH, MEDIA_TYPES, type MetaField, type MetaTable, NON_EDITABLE_TYPES, NUMBER_TYPES, type OperationFeedback, RangeSet, type RelationColumnInfo, RelationInfo, type RowWithDraft, STRUCTURED_DATA_TYPES, type ScalarFieldSpec, type SelectionCurrent, type SelectionRect, Sheets, type SheetsAuthState, SheetsBackendAdapter, SheetsCell, SheetsCellRenderContext, SheetsConfig, SheetsControls, type SheetsControlsProps, type SheetsDraftBindings, SheetsEmptyState, SheetsErrorBoundary, SheetsErrorState, type SheetsEvent, SheetsExecuteFn, SheetsFileValue, type SheetsHandle, SheetsLoadingState, SheetsPagination, type SheetsPaginationBindings, type SheetsPaginationProps, type SheetsProps, SheetsProvider, type SheetsRow, SheetsRowIdentifier, SheetsScopeKey, type SheetsSelection, type SheetsSelectionBindings, type SheetsSlots, type SheetsStoreState, SheetsTableSelector, type SheetsThemeInput, type SheetsThemeTokens, SheetsUploadFn, TYPED_ARRAY_TYPES, type TableSelectorProps, type TableWithCategory, type Trigger, type UploadProgress, type UploadResponse, type UseDataFilteringConfig, type UseDataPaginationConfig, type UseFieldUploadOptions, type UseInfiniteTableOptions, type UseInfiniteTableResult, type UseMetaOptions, type UseSheetsResult, type UseSheetsTableCursorOptions, type UseSheetsTableCursorResult, type UseTableOptions, type UseTableResult, VIEWER_ONLY_TYPES, buildScalarFormSpec, buildZodSchema, clear as clearSheetsSelection, computeDraftMetaSignature, countConditions, createCellTypeRegistry, createColumnSchemaFromMeta, createEmptyGroup, createMetadataHash, createPostGraphileAdapter, emptySheetsSelection, executeFieldUpload, extendRangeToCell, fillDownWrites, fillRightWrites, findTableFormSpec, getCellsInRange, getDraftMeta, isArrayCellType, isDraftRow, isSheetsScopeKey, isStructuredDataType, kbd, mapToFrontendCellType, moveActive, sheetsTableQueryKeys as queryKeys, resolveDownloadUrl, selectCell, selectRange, selectRow, sheetsQueryKeys, toTSV, toggleRow, tokensFromCssVars, useDataFiltering, useDataGridColumns, useDataPagination, useDynamicCreate, useDynamicUpdate, useFeedback, useOperationFeedback, useRelationColumns, useSheets, useSheetsAdapter, useSheetsFieldUpload, useSheetsInfiniteTable, useSheetsMeta, useSheetsStore, useSheetsStoreApi, useSheetsTable, useSheetsTableCursor };
2897
+ export { BOOLEAN_TYPES, BUILTIN_EDITOR_TYPES, type Binding, CellPlugin, CellProps, CellRegistry, CellRegistryEntry, CellRenderer, type CellSlot, type CellSlots, CellType, type CellTypeBuiltins, CellTypeDefinition, CellTypeMatchInput, type CellTypeRegistry, type ColumnInputOptions, type ColumnInputResult, ColumnSchema, type ColumnStorage, type CommandResult, type ConditionStatus, DATE_TIME_TYPES, DEFAULT_READ_ONLY_REASON, type DataFilteringContextValue, type DataPaginationContextValue, type DispatchEvent, DockStatusBar, DockStatusBarCompact, type DraftMeta, type DraftRow, type DynamicFormSpec, ENHANCED_TYPES, EditorProps, ExportViewControl, type ExportViewControlProps, type ExtractedRange, FeedbackProvider, type FieldUploadTarget, type FieldUploadTransport, type FileCellWriteJob, type FileProjection, type FileUploadState, type FilterOperatorGroup, type FilterOperatorOption, type FilterValueControl, FloatingStatus, GEOMETRY_TYPES, type GridCommand, type GridCommandContext, ImportRecordsControl, type ImportRecordsControlProps, type Interceptor, MAX_FILTER_DEPTH, MEDIA_TYPES, type MetaField, type MetaTable, type ModelFormField, type ModelFormMode, type ModelFormSpec, ModelIssuesNotice, NON_EDITABLE_TYPES, NUMBER_TYPES, type OperationFeedback, type OperationType, ROW_HEIGHT_PX, RangeSet, type RelationColumnInfo, RelationInfo, RelationSection, type RelationSectionProps, type RowWithDraft, SHEETS_VIEW_STATE_VERSION, STRUCTURED_DATA_TYPES, SaveStatus, type ScalarFieldSpec, type ScalarValueControl, type SelectionCurrent, type SelectionRect, type SendFile, type SendFileOptions, Sheets, type SheetsAuthState, SheetsBackendAdapter, SheetsCell, SheetsCellRenderContext, type SheetsColumnCondition, type SheetsColumnLayout, SheetsConfig, SheetsControls, type SheetsControlsProps, type SheetsDraftBindings, SheetsEmptyState, SheetsErrorBoundary, SheetsErrorState, type SheetsEvent, SheetsExecuteFn, type SheetsFilterCondition, type SheetsFilterGroup, type SheetsFilterLogic, type SheetsFilterNode, type SheetsFilterValue, type SheetsHandle, SheetsLoadingState, SheetsOpenRecordContext, type SheetsOpenRecordHandler, type SheetsOpenRecordRequest, SheetsOpenTableContext, type SheetsOpenTableHandler, type SheetsOpenTableRequest, SheetsPagination, type SheetsPaginationBindings, type SheetsPaginationProps, type SheetsProps, SheetsProvider, SheetsReadOnlyProvider, type SheetsReadOnlyProviderProps, type SheetsRelationCondition, type SheetsRelationTest, type SheetsRow, type SheetsRowHeight, SheetsRowIdentifier, SheetsScopeKey, type SheetsSelection, type SheetsSelectionBindings, type SheetsSlots, type SheetsSortDirection, type SheetsSortKey, SheetsStatusBar, type SheetsStatusBarProps, type SheetsStoreState, SheetsTableSelector, type SheetsThemeInput, type SheetsThemeTokens, type SheetsViewProps, type SheetsViewState, type SheetsViewStateDrop, type SheetsViewStateDropReason, type SheetsViewStateValidation, TYPED_ARRAY_TYPES, type TableSelectorProps, type TableWithCategory, type Trigger, type UnfinishedUpload, type UploadProgress, type UploadProgressEvent, type UploadResponse, type UploadToFilesTableOptions, type UploadedFile, type UseColumnStorageResult, type UseDataFilteringConfig, type UseDataPaginationConfig, type UseFieldUploadOptions, type UseInfiniteTableOptions, type UseInfiniteTableResult, type UseMetaOptions, type UseSheetsResult, type UseSheetsTableCursorOptions, type UseSheetsTableCursorResult, type UseTableModelOptions, type UseTableModelResult, type UseTableModelsResult, type UseTableOptions, type UseTableResult, VIEWER_ONLY_TYPES, type ValidateSheetsViewStateOptions, type ViewQuery, type WriteAction, type WriteErrorReport, WriteErrorStack, type WriteMessages, buildModelFormSchema, buildModelFormSpec, buildScalarFormSpec, buildViewQuery, buildZodSchema, cellTypeForColumn, clear as clearSheetsSelection, computeDraftMetaSignature, createCellTypeRegistry, createColumnLayout, createColumnSchemaFromMeta, createFilterGroup, createMetadataHash, createPostGraphileAdapter, createSheetsViewState, cycleSort, defaultOperatorOption, emptySheetsSelection, executeFieldUpload, extendRangeToCell, fillDownWrites, fillRightWrites, filterConditionsOf, filterOperatorLabel, filterOperatorOptions, findTableFormSpec, formatColumnValue, getCellsInRange, getDraftMeta, gridRelations, isArrayCellType, isDraftRow, isSheetsScopeKey, isStructuredDataType, kbd, mapToFrontendCellType, moveActive, orderedColumnKeys, parseColumnInput, sheetsTableQueryKeys as queryKeys, resolveDownloadUrl, selectCell, selectRange, selectRow, sheetsMutationKeys, sheetsQueryKeys, toTSV, toggleRow, tokensFromCssVars, unfinishedUploadOf, uploadToFilesTable, useColumnStorage, useDataFiltering, useDataGridColumns, useDataPagination, useDynamicCreate, useDynamicUpdate, useFeedback, useFileCellWriter, useFileUploadState, useOpenRecordHandler, useOperationFeedback, useOptionalFeedback, useRelationColumns, useSheets, useSheetsAdapter, useSheetsFieldUpload, useSheetsInfiniteTable, useSheetsMeta, useSheetsStore, useSheetsStoreApi, useSheetsTable, useSheetsTableCursor, useShowSystemTables, useTableModel, useTableModels, validateSheetsViewState, visibleColumnKeys, visibleTables, writeErrorMessages };