@constructive-io/sheets 0.3.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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +188 -0
  3. package/dist/advanced.cjs +5477 -0
  4. package/dist/advanced.cjs.map +1 -0
  5. package/dist/advanced.d.cts +83 -0
  6. package/dist/advanced.d.ts +83 -0
  7. package/dist/advanced.js +34 -0
  8. package/dist/advanced.js.map +1 -0
  9. package/dist/auth.cjs +1396 -0
  10. package/dist/auth.cjs.map +1 -0
  11. package/dist/auth.d.cts +60 -0
  12. package/dist/auth.d.ts +60 -0
  13. package/dist/auth.js +19 -0
  14. package/dist/auth.js.map +1 -0
  15. package/dist/chunk-4PGPVMZB.js +670 -0
  16. package/dist/chunk-4PGPVMZB.js.map +1 -0
  17. package/dist/chunk-FNVHSOQQ.js +1314 -0
  18. package/dist/chunk-FNVHSOQQ.js.map +1 -0
  19. package/dist/chunk-GGECS2BP.js +17 -0
  20. package/dist/chunk-GGECS2BP.js.map +1 -0
  21. package/dist/chunk-GLVZSPV2.js +43 -0
  22. package/dist/chunk-GLVZSPV2.js.map +1 -0
  23. package/dist/chunk-H4JJTMP5.js +160 -0
  24. package/dist/chunk-H4JJTMP5.js.map +1 -0
  25. package/dist/chunk-ODUBS2NL.js +100 -0
  26. package/dist/chunk-ODUBS2NL.js.map +1 -0
  27. package/dist/chunk-PZL2BCWF.js +168 -0
  28. package/dist/chunk-PZL2BCWF.js.map +1 -0
  29. package/dist/chunk-TU7ATZ4X.js +4494 -0
  30. package/dist/chunk-TU7ATZ4X.js.map +1 -0
  31. package/dist/chunk-X7DHTSOX.js +21 -0
  32. package/dist/chunk-X7DHTSOX.js.map +1 -0
  33. package/dist/chunk-YDQQA46V.js +13 -0
  34. package/dist/chunk-YDQQA46V.js.map +1 -0
  35. package/dist/date-editor-CXKKGNL6.js +361 -0
  36. package/dist/date-editor-CXKKGNL6.js.map +1 -0
  37. package/dist/editor-props-M6Dh0P9f.d.cts +245 -0
  38. package/dist/editor-props-M6Dh0P9f.d.ts +245 -0
  39. package/dist/index.cjs +15861 -0
  40. package/dist/index.cjs.map +1 -0
  41. package/dist/index.d.cts +1650 -0
  42. package/dist/index.d.ts +1650 -0
  43. package/dist/index.js +8470 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/map-picker-VTKDS6CM.js +290 -0
  46. package/dist/map-picker-VTKDS6CM.js.map +1 -0
  47. package/dist/sheets-context-CojEFlaY.d.cts +214 -0
  48. package/dist/sheets-context-Da55TTR9.d.ts +214 -0
  49. package/dist/testing.cjs +1113 -0
  50. package/dist/testing.cjs.map +1 -0
  51. package/dist/testing.d.cts +45 -0
  52. package/dist/testing.d.ts +45 -0
  53. package/dist/testing.js +269 -0
  54. package/dist/testing.js.map +1 -0
  55. package/package.json +144 -0
@@ -0,0 +1,1650 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { b as SheetsConfig, C as CellProps, c as CellTypeDefinition, d as CellTypeMatchInput, e as SheetsCellRenderContext, f as SheetsScopeKey, S as SheetsExecuteFn, a as SheetsUploadFn, g as SheetsBackendAdapter } from './sheets-context-Da55TTR9.js';
3
+ export { n as AdapterListQuery, o as AdapterListResult, p as AdapterPageInfo, A as AdapterTableContext, s as CellColumnDescriptor, r as CellTypePlugin, j as SheetsAuthEmbedded, k as SheetsAuthStandalone, h as SheetsContext, i as SheetsContextValue, t as SheetsLogger, l as createSheetsExecute, m as createSheetsUpload, q as defineCellType, u as useSheetsContext } from './sheets-context-Da55TTR9.js';
4
+ import { StoreApi } from 'zustand';
5
+ import { R as RelationInfo, d as RelationInfoSlice, E as EditorProps, F as FieldMetadata, S as SheetsCell, e as CellRegistryEntry, b as CellType, f as CellRenderer, g as CellPlugin, h as ColumnSchema } from './editor-props-M6Dh0P9f.js';
6
+ export { B as BaseCellProps, c as CellCategory, l as CellValue, m as FieldMetadata, i as RelationKind, n as RowData, a as SheetsCellKind, T as TableSchema, j as buildRelationInfoFromMeta, k as isImageField, r as resolveCellType } from './editor-props-M6Dh0P9f.js';
7
+ import React__default, { Component, ReactNode, ErrorInfo } from 'react';
8
+ import * as _tanstack_react_query from '@tanstack/react-query';
9
+ import { UseQueryResult } from '@tanstack/react-query';
10
+ import { FieldSelection, MutationOptions, PageInfo, MetaQuery, QueryOptions, Filter } from '@constructive-io/data';
11
+ export { DataError } from '@constructive-io/data';
12
+ import { z } from 'zod';
13
+ export { SheetsAuthGate, SheetsAuthGateProps, useSheetsForgotPassword, useSheetsLogin, useSheetsRegister, useSheetsResetPassword } from './auth.js';
14
+ import 'graphql';
15
+
16
+ interface SheetsProviderProps {
17
+ config: SheetsConfig;
18
+ children: React.ReactNode;
19
+ }
20
+ declare function SheetsProvider({ config, children }: SheetsProviderProps): react_jsx_runtime.JSX.Element;
21
+
22
+ type DraftRowStatus = 'idle' | 'saving' | 'error';
23
+ interface DraftRow {
24
+ id: string;
25
+ values: Record<string, unknown>;
26
+ status: DraftRowStatus;
27
+ errors: Record<string, string> | null;
28
+ createdAt: number;
29
+ metaVersion: string;
30
+ }
31
+ interface DraftRowsTableState {
32
+ order: string[];
33
+ map: Record<string, DraftRow>;
34
+ template: Record<string, unknown>;
35
+ metaVersion: string;
36
+ columnOrder: string[];
37
+ }
38
+ interface DraftRowCreationArgs {
39
+ tableKey: string;
40
+ columnOrder: readonly string[];
41
+ fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>;
42
+ relationInfoByKey?: Record<string, RelationInfo | undefined>;
43
+ metaVersion: string;
44
+ }
45
+ type DraftRowsSyncArgs = DraftRowCreationArgs;
46
+ interface DraftRowUpdateArgs {
47
+ tableKey: string;
48
+ draftRowId: string;
49
+ columnKey: string;
50
+ value: unknown;
51
+ extraValues?: Record<string, unknown>;
52
+ }
53
+ interface DraftRowsSlice {
54
+ draftRowsByTable: Record<string, DraftRowsTableState | undefined>;
55
+ createDraftRow: (args: DraftRowCreationArgs) => string;
56
+ updateDraftCell: (args: DraftRowUpdateArgs) => void;
57
+ removeDraftRow: (tableKey: string, draftRowId: string) => void;
58
+ clearDraftRowsForTable: (tableKey: string) => void;
59
+ clearDraftRowsForDatabase: (databaseId: string) => void;
60
+ clearAllDraftRows: () => void;
61
+ syncDraftRowsWithMeta: (args: DraftRowsSyncArgs) => void;
62
+ setDraftRowStatus: (args: {
63
+ tableKey: string;
64
+ draftRowId: string;
65
+ status: DraftRowStatus;
66
+ errors?: Record<string, string> | null;
67
+ }) => void;
68
+ }
69
+ type DraftFieldMetadata = {
70
+ name?: string | null;
71
+ isNotNull?: boolean | null;
72
+ hasDefault?: boolean | null;
73
+ type?: {
74
+ gqlType?: string | null;
75
+ isArray?: boolean | null;
76
+ pgAlias?: string | null;
77
+ pgType?: string | null;
78
+ subtype?: string | null;
79
+ } | null;
80
+ };
81
+ declare function computeDraftMetaSignature(columnOrder: readonly string[], fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>, relationInfoByKey?: Record<string, RelationInfo | undefined>): string;
82
+
83
+ interface SheetsAuthState {
84
+ isAuthenticated: boolean;
85
+ accessToken: string | null;
86
+ expiresAt: string | null;
87
+ setAuthenticated: (token: string, expiresAt: string) => void;
88
+ setUnauthenticated: () => void;
89
+ }
90
+ type SheetsStoreState = DraftRowsSlice & RelationInfoSlice & SheetsAuthState;
91
+ declare function useSheetsStore<T>(selector: (state: SheetsStoreState) => T): T;
92
+ declare function useSheetsStoreApi(): StoreApi<SheetsStoreState>;
93
+
94
+ /** A grid row: arbitrary column values keyed by field name, plus an optional id. */
95
+ type SheetsRow = Record<string, unknown> & {
96
+ id?: string | number;
97
+ };
98
+ /** Client-side draft metadata carried by a not-yet-persisted row. */
99
+ interface DraftMeta {
100
+ readonly isDraft: true;
101
+ readonly draftRowId: string;
102
+ readonly status: DraftRow['status'];
103
+ readonly errors: Record<string, string> | null;
104
+ }
105
+ declare const DRAFT_META: unique symbol;
106
+ /** A row that may carry draft metadata under the (non-enumerable) Symbol key. */
107
+ type RowWithDraft<TRow extends SheetsRow = SheetsRow> = TRow & {
108
+ readonly [DRAFT_META]?: DraftMeta;
109
+ };
110
+ /** Read draft metadata, or undefined for a normal (server) row. */
111
+ declare function getDraftMeta(row: SheetsRow | null | undefined): DraftMeta | undefined;
112
+ /** True when the row is a client-side draft. */
113
+ declare function isDraftRow(row: SheetsRow | null | undefined): boolean;
114
+
115
+ /**
116
+ * A single slot: either a bare cell component, or an object overriding the cell
117
+ * view and/or the native editor for a typeKey. The object form lets a consumer
118
+ * override JUST the editor (`{ editor: MyEditor }`) without touching the view.
119
+ */
120
+ type CellSlot = React.ComponentType<CellProps> | {
121
+ cell?: React.ComponentType<CellProps>;
122
+ editor?: React.ComponentType<EditorProps>;
123
+ };
124
+ /** Consumer cell-component / editor overrides keyed by cell typeKey. */
125
+ type CellSlots = Record<string, CellSlot>;
126
+
127
+ /**
128
+ * Sheets theme tokens.
129
+ *
130
+ * A small, semantic token set a host can override per light/dark mode, plus a
131
+ * reader that lifts tokens off CSS custom properties. The native DOM grid styles
132
+ * from CSS variables directly, so these tokens are the glide-free surface that
133
+ * survived the canvas cutover (the old glide `Theme` mapping was removed).
134
+ */
135
+ /**
136
+ * Semantic, composable theme tokens. A small surface a host can override per mode.
137
+ */
138
+ interface SheetsThemeTokens {
139
+ /** Primary accent (selection, links, focus). */
140
+ accent: string;
141
+ /** Foreground rendered on top of `accent` (e.g. selected header text). */
142
+ accentForeground: string;
143
+ /** Base canvas / cell background. */
144
+ background: string;
145
+ /** Header / muted cell surface. */
146
+ surface: string;
147
+ /** Hover / focused surface (one step from `surface`). */
148
+ surfaceMuted: string;
149
+ /** Grid + header border color. */
150
+ border: string;
151
+ /** Primary text color. */
152
+ text: string;
153
+ /** Secondary (muted) text color. */
154
+ textMuted: string;
155
+ /** Optional font stack; falls back to the default Inter-based stack. */
156
+ fontFamily?: string;
157
+ }
158
+ /**
159
+ * Host theme input: a partial token override keyed by mode (deep-merged over the
160
+ * grid's defaults).
161
+ */
162
+ type SheetsThemeInput = Partial<Record<'light' | 'dark', Partial<SheetsThemeTokens>>>;
163
+ /**
164
+ * Read theme tokens off CSS custom properties on `el` (defaults to
165
+ * `document.documentElement`). Only properties that resolve to a non-empty value
166
+ * are returned, so the result is safe to deep-merge over a defaults object.
167
+ */
168
+ declare function tokensFromCssVars(el?: Element | null): Partial<SheetsThemeTokens>;
169
+
170
+ /**
171
+ * RangeSet — the immutable selection primitive for the native (TanStack DOM)
172
+ * grid. It replaces glide's `CompactSelection` for row selection state.
173
+ *
174
+ * Internal representation: a sorted, non-overlapping, NON-ADJACENT array of
175
+ * `[start, end)` half-open ranges. Adjacency MERGES on touch (so `add([0,3))`
176
+ * then `add([3,5))` collapses to a single `[0,5)`), keeping a 10k-row selection
177
+ * O(#ranges) instead of O(#rows). Every mutator returns a NEW RangeSet; the
178
+ * receiver is never mutated.
179
+ *
180
+ * Behavior is frozen by `src/grid/__golden__/selection.golden.json` (the
181
+ * `CompactSelection` reference) — this class MUST reproduce all 26 cases
182
+ * byte-identically. See `src/selection/__tests__/range-set.golden.test.ts`.
183
+ */
184
+ declare class RangeSet {
185
+ private readonly ranges;
186
+ private constructor();
187
+ static empty(): RangeSet;
188
+ /** RESET to a single index `[i, i+1)` or a single `[start, end)` range. */
189
+ static fromSingleSelection(i: number | [number, number]): RangeSet;
190
+ /** Add an index/range; merges adjacent + overlapping ranges; contained = no-op. */
191
+ add(i: number | [number, number]): RangeSet;
192
+ /** Remove an index/range; SPLITS a covering range. */
193
+ remove(i: number | [number, number]): RangeSet;
194
+ /** Shift every range by `amount`. */
195
+ offset(amount: number): RangeSet;
196
+ hasIndex(i: number): boolean;
197
+ /** Ascending expansion of every selected index. */
198
+ toArray(): number[];
199
+ /** Total selected count — sum of `(end - start)` across ranges. */
200
+ get length(): number;
201
+ /** Lowest selected index, or `undefined` when empty. */
202
+ first(): number | undefined;
203
+ /** Highest selected index, or `undefined` when empty. */
204
+ last(): number | undefined;
205
+ }
206
+
207
+ /**
208
+ * SheetsSelection — the native (TanStack DOM) selection value that replaces
209
+ * glide's `GridSelection`. It is the canonical selection state for the new grid;
210
+ * glide's `GridSelection` is only a derived projection (see `glide-projection.ts`)
211
+ * kept alive for the still-drawing canvas during the phased port.
212
+ *
213
+ * Shape mirrors the slice of glide the grid actually reads/round-trips:
214
+ * - `rows` — selected ROW indices (a {@link RangeSet}; the only thing
215
+ * production consumes via `.toArray()` / `.length`).
216
+ * - `columns` — selected COLUMN indices. Nothing consumes it today; it exists
217
+ * solely so the glide projection has a faithful slot. Stays empty.
218
+ * - `current` — the active cell + optional active range (glide's `current.cell`
219
+ * + `current.range`). The canvas keyboard-nav cursor depends on it,
220
+ * so the projection must preserve it round-trip.
221
+ *
222
+ * The interaction helpers below are PURE and own the click logic glide used to
223
+ * own internally (plain/ctrl/shift row clicks). They operate on ROW indices.
224
+ *
225
+ * NOTE — anchor tracking for shift-click is NOT stored here: `selectRange` takes
226
+ * the anchor as an argument, so the caller (the reducer / interaction layer) owns
227
+ * "where the last plain click landed". This keeps the model a pure value with no
228
+ * hidden interaction state.
229
+ */
230
+
231
+ /** A half-open active range in cell coordinates (mirrors glide's `Rectangle`). */
232
+ interface SelectionRect {
233
+ x: number;
234
+ y: number;
235
+ width: number;
236
+ height: number;
237
+ }
238
+ /** The active cell (and optional active range) — glide's `current`, trimmed. */
239
+ interface SelectionCurrent {
240
+ /** `[col, row]` — mirrors glide's `Item` ordering. */
241
+ cell: [number, number];
242
+ /** Active range; absent for a bare single-cell cursor. */
243
+ range?: SelectionRect;
244
+ }
245
+ interface SheetsSelection {
246
+ current?: SelectionCurrent;
247
+ rows: RangeSet;
248
+ columns: RangeSet;
249
+ }
250
+ /** The zero value — no rows, no columns, no active cell. */
251
+ declare const emptySheetsSelection: SheetsSelection;
252
+ /**
253
+ * Plain row click: REPLACE the row selection with just `index` and park the
254
+ * active cell on that row (column 0). Columns are left empty.
255
+ */
256
+ declare function selectRow(sel: SheetsSelection, index: number): SheetsSelection;
257
+ /**
258
+ * Ctrl/cmd row click: TOGGLE `index` in the existing row selection (add when
259
+ * absent, remove when present). The active cell follows the touched row.
260
+ */
261
+ declare function toggleRow(sel: SheetsSelection, index: number): SheetsSelection;
262
+ /**
263
+ * Shift row click: REPLACE the row selection with the contiguous block spanning
264
+ * `anchor`..`index` (inclusive, either order). The active cell follows `index`.
265
+ */
266
+ declare function selectRange(sel: SheetsSelection, anchor: number, index: number): SheetsSelection;
267
+ /** Clear everything back to the empty selection. */
268
+ declare function clear(_sel: SheetsSelection): SheetsSelection;
269
+ /**
270
+ * Park the active cell on `[col, row]`, dropping any prior active range. PRESERVES
271
+ * `rows` and `columns` — cell navigation must NOT touch the row-checkbox selection
272
+ * that drives delete/export.
273
+ */
274
+ declare function selectCell(sel: SheetsSelection, col: number, row: number): SheetsSelection;
275
+ /**
276
+ * Extend the active range from an anchor cell to `[col, row]`. The active cell
277
+ * becomes `[col, row]`; `current.range` is a normalized HALF-OPEN {@link SelectionRect}
278
+ * spanning anchor..target in either order. PRESERVES `rows` and `columns`.
279
+ */
280
+ declare function extendRangeToCell(sel: SheetsSelection, col: number, row: number, anchorCol: number, anchorRow: number): SheetsSelection;
281
+ /**
282
+ * Move the active cell by `[dCol, dRow]`, clamped to the grid bounds. Starts from
283
+ * `[0, 0]` when no active cell exists. Drops any prior range; PRESERVES rows/columns.
284
+ */
285
+ declare function moveActive(sel: SheetsSelection, dCol: number, dRow: number, colCount: number, rowCount: number): SheetsSelection;
286
+
287
+ /** A single cell write request. */
288
+ interface CellWrite {
289
+ rowIndex: number;
290
+ colKey: string;
291
+ value: unknown;
292
+ }
293
+ interface CommitCellsOptions {
294
+ /** When false, the commit is NOT pushed to history (used by undo/redo replays). Default true. */
295
+ record?: boolean;
296
+ }
297
+ interface CommitCellsResult {
298
+ /** Number of server cells actually written (post readonly/null/no-op filtering). */
299
+ applied: number;
300
+ }
301
+
302
+ /**
303
+ * GridCommandContext — the ONE object every {@link GridCommand} runs against.
304
+ *
305
+ * In SheetsDomInner it is REF-LATCHED exactly like the existing `openEditor` latch
306
+ * (grid/sheets.tsx): churning values (selection / combinedRows / counts) are read
307
+ * through live GETTERS off the existing refs, while the dispatcher methods are the
308
+ * EXISTING stable callbacks wrapped VERBATIM — no dispatcher is reinvented. The context
309
+ * identity therefore stays stable across renders, so wiring it into `renderCell` (Phase 2)
310
+ * will not bust the per-cell memo.
311
+ *
312
+ * Getters (live reads off the existing refs):
313
+ * rowCount / colCount / activeCell / selection / combinedRows / columnKeys
314
+ *
315
+ * Anchor access wraps the existing `anchorRef` (the FIXED corner a range extends FROM):
316
+ * getAnchor / setAnchor
317
+ *
318
+ * Dispatchers (the existing stable functions, verbatim — see sheets.tsx for each):
319
+ * setActiveCell, moveActiveCell, extendToCell, setSelection, commitCells,
320
+ * openEditorAtActive, openEditorAt, undo, redo, scrollToCell, sortToggle,
321
+ * getCellsInRange, toTSV, emit
322
+ */
323
+
324
+ /** Extracted cell matrix — mirrors `getCellsInRange`'s return shape. */
325
+ interface CellMatrix {
326
+ cols: string[];
327
+ rows: number[];
328
+ values: (readonly unknown[])[];
329
+ }
330
+ interface GridCommandContext {
331
+ /** Current row count (`combinedRows.length`). */
332
+ readonly rowCount: number;
333
+ /** Current column count (`columns.length`). */
334
+ readonly colCount: number;
335
+ /** The active (keyboard cursor) cell `[col, row]`, or undefined. */
336
+ readonly activeCell: [number, number] | undefined;
337
+ /** The LATEST canonical selection (post-sort/filter-clear safe). */
338
+ readonly selection: SheetsSelection | undefined;
339
+ /** The current combined (server + draft) row window. */
340
+ readonly combinedRows: readonly unknown[];
341
+ /** The ordered column keys. */
342
+ readonly columnKeys: readonly string[];
343
+ /** Read the latched range anchor `[col, row]` (the corner a range extends FROM). */
344
+ getAnchor(): [number, number] | null;
345
+ /** Latch / reset the range anchor. */
346
+ setAnchor(anchor: [number, number] | null): void;
347
+ /** Park the active cell on `[col, row]` (preserves row/col selection). */
348
+ setActiveCell(col: number, row: number): void;
349
+ /** Move the active cell by a delta, clamped to bounds. */
350
+ moveActiveCell(dCol: number, dRow: number, colCount: number, rowCount: number): void;
351
+ /** Extend the contiguous range from the latched anchor to `[col, row]`. */
352
+ extendToCell(col: number, row: number): void;
353
+ /** Write the canonical selection directly (`s.selection.setGridSelection`). */
354
+ setSelection(selection: SheetsSelection | undefined): void;
355
+ /** Batched cell commit (the same setter cell edits round-trip through). */
356
+ commitCells(writes: CellWrite[], opts?: CommitCellsOptions): Promise<CommitCellsResult>;
357
+ /** Open the overlay editor at the active cell; optional seed text (type-to-edit). Returns true when opened. */
358
+ openEditorAtActive(initialText?: string): boolean;
359
+ /** Open the overlay editor at an explicit cell + anchor rect (dblclick path). */
360
+ openEditorAt(rowIndex: number, colKey: string, anchorRect: DOMRect, initialText?: string): void;
361
+ /** Undo the last edit (may kick a Promise). */
362
+ undo(): void | Promise<void>;
363
+ /** Redo the last undone edit (may kick a Promise). */
364
+ redo(): void | Promise<void>;
365
+ /** Scroll a cell into view. */
366
+ scrollToCell(col: number, row: number): void;
367
+ /** Toggle the sort for a column key (the existing header-click sort toggle). */
368
+ sortToggle(colKey: string): void;
369
+ /** Toggle a single row in the checkbox selection (the existing rowMarker.onToggleRow). */
370
+ toggleRow(rowIndex: number, shift: boolean): void;
371
+ /** Toggle select-all in the checkbox selection (the existing rowMarker.onToggleAll). */
372
+ toggleAll(): void;
373
+ /** Extract a cell matrix for a range (pure helper, re-exported into ctx for copy). */
374
+ getCellsInRange(rect: SelectionRect): CellMatrix;
375
+ /** Serialize a value matrix to TSV (pure helper). */
376
+ toTSV(values: (readonly unknown[])[]): string;
377
+ /** Emit an observational event (analytics/telemetry; never changes behavior). */
378
+ emit(type: SheetsEvent['type'], meta?: Record<string, unknown>): void;
379
+ }
380
+
381
+ /**
382
+ * Internal event->command core types (P4 Phase 1).
383
+ *
384
+ * Every existing grid interaction maps to exactly ONE named {@link GridCommand},
385
+ * and every command runs through ONE {@link makeDispatch} pipeline. Commands are
386
+ * PLAIN OBJECTS (no classes — project rule); they receive a {@link GridCommandContext}
387
+ * and an optional payload, call the EXISTING stable dispatchers verbatim, and never
388
+ * own state.
389
+ *
390
+ * Phase 1 is a REFACTOR ONLY: behavior must stay byte-for-byte identical. No public
391
+ * API props ship this phase — the interceptor seam is internal-first.
392
+ */
393
+
394
+ /**
395
+ * A named, dispatchable grid action. `run` performs the effect (calling
396
+ * `ctx.<dispatcher>`); the optional `canRun` is a synchronous guard checked AFTER
397
+ * the interceptor chain — a `false` no-ops the command (and skips `native.preventDefault`).
398
+ * `run` is synchronous-returning by contract; it MAY kick a Promise (undo/redo), but
399
+ * the dispatch pipeline never awaits it (no async-dispatch / re-entrancy machinery).
400
+ */
401
+ interface GridCommand<P = unknown> {
402
+ id: string;
403
+ run(ctx: GridCommandContext, payload?: P): void | Promise<void>;
404
+ canRun?(ctx: GridCommandContext, payload?: P): boolean;
405
+ }
406
+
407
+ /**
408
+ * Keybinding primitives — COPIED from packages/command-palette/src/keybinding.ts
409
+ * (kbd / matchKeyBinding / isMac / isEditableTarget) so @constructive-io/sheets stays
410
+ * distributable WITHOUT a dependency on command-palette. Keep the two in sync by hand;
411
+ * the logic is intentionally identical (strict modifier matching, Mac mod=meta).
412
+ */
413
+ /** Modifier key abstraction. 'mod' = Cmd on Mac, Ctrl on Windows/Linux. */
414
+ type KeyModifier = 'mod' | 'shift' | 'alt';
415
+ /** Structured key binding — matchable against KeyboardEvents. */
416
+ interface KeyBinding {
417
+ modifiers?: KeyModifier[];
418
+ /** Lowercase key name: 'h', 'k', 'enter', 'backspace', ',', '/', etc. */
419
+ key: string;
420
+ }
421
+ /** Ergonomic KeyBinding factory. */
422
+ declare function kbd(key: string, ...modifiers: KeyModifier[]): KeyBinding;
423
+
424
+ /**
425
+ * DEFAULT_KEYMAP + resolveKeyCommand (P4 Phase 1).
426
+ *
427
+ * A keymap is an ordered Binding[]; `resolveKeyCommand` returns the FIRST matching
428
+ * binding's command id (first-match-wins) or `null` when nothing matches — including
429
+ * for an unbound PRINTABLE key, so the dispatch funnel can fall to the `editor.typeToEdit`
430
+ * sentinel (the printable-key path is NOT in the keymap; the funnel routes it explicitly).
431
+ *
432
+ * Triggers come in three kinds — `key` (matched here via the copied matchKeyBinding),
433
+ * `pointer` (gesture, wired in Stage B / Phase 2), and `native` (a raw DOM event name).
434
+ * Pointer + native triggers are declared in the table for invariant completeness even
435
+ * though only key triggers resolve through `resolveKeyCommand`.
436
+ *
437
+ * `Mod` is ctrl on win/linux, cmd on mac — encoded as the copied `'mod'` KeyModifier, so
438
+ * matchKeyBinding's platform branch (isMac) picks the right physical key.
439
+ */
440
+
441
+ /** A pointer gesture name (resolved by the pointer handlers, not the key funnel). */
442
+ type PointerGesture = 'click' | 'shiftClick' | 'dblclick' | 'headerClick' | 'rowToggle' | 'rowToggleAll';
443
+ /** What fires a command. */
444
+ type Trigger = {
445
+ kind: 'key';
446
+ binding: KeyBinding;
447
+ } | {
448
+ kind: 'pointer';
449
+ gesture: PointerGesture;
450
+ } | {
451
+ kind: 'native';
452
+ event: string;
453
+ };
454
+ /** A trigger -> command id mapping. */
455
+ interface Binding {
456
+ trigger: Trigger;
457
+ command: string;
458
+ }
459
+
460
+ /**
461
+ * The ONE interceptable dispatch pipeline (P4 Phase 1).
462
+ *
463
+ * `dispatch(command, native?, payload?)`:
464
+ * 1. resolve `command` in the registry — a missing / null id is a silent NO-OP
465
+ * (so an unbound key falls through to the browser: NO `preventDefault`).
466
+ * 2. run the interceptor chain (reduceRight → first-listed is OUTERMOST). Each
467
+ * interceptor may VETO (not call `next` → command never runs, nothing prevented),
468
+ * TRANSFORM (mutate `ev.payload` before `next`), or OBSERVE (read `next()`'s result).
469
+ * 3. AFTER the chain, check `command.canRun(ctx, payload)` — false NO-OPs (and does
470
+ * NOT preventDefault).
471
+ * 4. `native?.preventDefault()` happens ONLY here in the core (so a vetoed / unresolved /
472
+ * can't-run command leaves the native event untouched and the key reaches the browser).
473
+ * 5. `command.run(ctx, payload)` — synchronous return (it MAY kick a Promise; we never
474
+ * await — NO async-dispatch / re-entrancy machinery).
475
+ *
476
+ * Phase 1 ships ZERO interceptors (the consumer seam is Phase 2); the chain is wired so
477
+ * adding one later is purely additive and behavior stays byte-for-byte identical.
478
+ */
479
+
480
+ /** The mutable event threaded through the interceptor chain. */
481
+ interface DispatchEvent {
482
+ /** The resolved command id. */
483
+ command: string;
484
+ /** The originating native event, if any (the funnel's `preventDefault` target). */
485
+ native?: Event;
486
+ /** The command payload — interceptors MAY mutate this in place to TRANSFORM. */
487
+ payload?: unknown;
488
+ }
489
+ /** Result of a dispatch attempt — observable by interceptors via `next()`. */
490
+ interface CommandResult {
491
+ /** The dispatched command id (or null when nothing resolved). */
492
+ command: string | null;
493
+ /** Whether `command.run` was invoked (false = unresolved / vetoed / canRun=false). */
494
+ ran: boolean;
495
+ /** Whether `native.preventDefault()` was called. */
496
+ prevented: boolean;
497
+ }
498
+ /**
499
+ * An interceptor wraps the rest of the chain (`next`). Call `next()` to continue
500
+ * (returning its CommandResult); SKIP it to VETO; mutate `ev.payload` before `next()`
501
+ * to TRANSFORM. The OUTERMOST (first-listed) interceptor sees the final result.
502
+ */
503
+ type Interceptor = (ev: DispatchEvent, next: () => CommandResult) => CommandResult;
504
+
505
+ /**
506
+ * Lifecycle/interaction event emitted by {@link Sheets} via the optional
507
+ * `onEvent` prop. Purely observational: firing an event never changes grid
508
+ * behavior, so consumers can wire analytics/telemetry without side effects.
509
+ */
510
+ interface SheetsEvent {
511
+ type: 'load:success' | 'load:error' | 'cell:edit' | 'row:create' | 'row:delete' | 'filter:apply' | 'sort:change' | 'page:change';
512
+ /** The table the event originated from. */
513
+ tableName: string;
514
+ /** Epoch ms (`Date.now()`) when the event fired. */
515
+ at: number;
516
+ /** Event-specific extra context (ids, values, error, page index, …). */
517
+ meta?: Record<string, unknown>;
518
+ }
519
+ /** Context passed to the `toolbar` slot when supplied as a render function. */
520
+ interface SheetsToolbarSlotContext {
521
+ tableName: string;
522
+ }
523
+ /**
524
+ * Render-slot overrides. Each provided slot replaces the corresponding default
525
+ * (the Phase-0 SheetsErrorState / SheetsEmptyState / SheetsLoadingState stay as
526
+ * fallbacks when a slot is omitted). All slots are optional and additive.
527
+ */
528
+ interface SheetsSlots {
529
+ /** Replaces (precedes) the default <SheetsControls> toolbar block. */
530
+ toolbar?: React.ReactNode | ((ctx: SheetsToolbarSlotContext) => React.ReactNode);
531
+ /** Replaces the default full-screen empty state. */
532
+ empty?: React.ReactNode | ((ctx: {
533
+ tableName: string;
534
+ }) => React.ReactNode);
535
+ /** Replaces the default full-screen error state. */
536
+ error?: (ctx: {
537
+ error: unknown;
538
+ retry: () => void;
539
+ }) => React.ReactNode;
540
+ /** Replaces the default full-screen loading state. */
541
+ loading?: React.ReactNode;
542
+ }
543
+ /**
544
+ * Alias kept in sync with {@link SheetsSlots}. The `slots` prop is typed with
545
+ * this name to match the shared Phase-4 contract; `SheetsSlots` is the exported
546
+ * public name.
547
+ */
548
+ type SheetsSlotsInput = SheetsSlots;
549
+ /**
550
+ * Imperative handle exposed through a `ref` on {@link Sheets}. Lets host apps
551
+ * drive the grid (scroll, submit drafts, refetch, read selection, export CSV)
552
+ * without reaching into internals.
553
+ */
554
+ interface SheetsHandle {
555
+ /** Scroll the viewport so the row at `index` is visible. */
556
+ scrollToRow(index: number): void;
557
+ /** Submit all pending draft rows (awaits the in-flight submission). */
558
+ submitDrafts(): Promise<void>;
559
+ /** Refetch the underlying table data (mode-aware: infinite vs paginated). */
560
+ refetch(): void;
561
+ /** Return the currently selected rows (empty array when nothing selected). */
562
+ getSelectedRows(): Record<string, unknown>[];
563
+ /** Download the selected rows (or all rows when none selected) as CSV. */
564
+ exportCsv(opts?: {
565
+ columns?: string[];
566
+ filename?: string;
567
+ }): void;
568
+ }
569
+ interface DataGridProps<TRow extends SheetsRow = SheetsRow> {
570
+ tableName: string;
571
+ className?: string;
572
+ pageSize?: number;
573
+ showSelection?: boolean;
574
+ showPagination?: boolean;
575
+ onRowSelect?: (selectedRows: TRow[]) => void;
576
+ onCellEdit?: (id: string | number, field: string, value: unknown) => void;
577
+ relationChipLimit?: number;
578
+ relationLabelMaxLength?: number;
579
+ /**
580
+ * Enable infinite scroll mode with cursor-based pagination.
581
+ * When enabled:
582
+ * - Rows are loaded on-demand as user scrolls
583
+ * - Traditional pagination UI is hidden
584
+ * - Uses hybrid cursor/offset pagination for optimal performance
585
+ * @default false
586
+ */
587
+ infiniteScroll?: boolean;
588
+ /** Per-instance cell types merged over provider plugins. */
589
+ cellTypes?: CellTypeDefinition<any>[];
590
+ /** Consumer cell-component overrides keyed by cell typeKey. */
591
+ cellSlots?: CellSlots;
592
+ /**
593
+ * Optional observational event callback. Fired on load success/error, cell
594
+ * edits, row create/delete, filter apply, sort change, and page change.
595
+ * Omitting it leaves behavior unchanged.
596
+ */
597
+ onEvent?: (e: SheetsEvent) => void;
598
+ /**
599
+ * Optional render-slot overrides for the toolbar / empty / error / loading
600
+ * regions. Any omitted slot falls back to the built-in default.
601
+ */
602
+ slots?: SheetsSlotsInput;
603
+ /**
604
+ * Override or extend the grid command set: a command with a matching id REPLACES
605
+ * the built-in body, a new id ADDS a command. Omitting it = the default set.
606
+ */
607
+ commands?: GridCommand[];
608
+ /**
609
+ * Extra / override key bindings, scanned BEFORE the defaults (first-match-wins),
610
+ * so a rebind of a built-in chord wins. Omitting it = the default keymap.
611
+ */
612
+ keymap?: Binding[];
613
+ /**
614
+ * Interceptors wrapping every dispatch (observe / veto / transform). Listed FIRST
615
+ * = OUTERMOST; the consumer list runs outside the `onCommand` tail observer.
616
+ */
617
+ interceptors?: Interceptor[];
618
+ /**
619
+ * Observe every dispatch and its result (sugar for an innermost tail-observer
620
+ * interceptor — runs after all consumer interceptors, never alters behavior).
621
+ */
622
+ onCommand?: (ev: DispatchEvent, result: CommandResult) => void;
623
+ /** Optional theme token overrides (per light/dark mode) or a Glide-theme function. */
624
+ theme?: SheetsThemeInput;
625
+ /** Optional explicit theme mode; defaults to following the document `dark` class. */
626
+ themeMode?: 'light' | 'dark' | 'system';
627
+ /**
628
+ * @internal Render-path switch for the TanStack DOM port spike. `'dom'`
629
+ * renders the native DOM grid; anything else (default) renders the canvas
630
+ * `<DataEditor>`. Double-underscore = internal/undocumented; NOT a public API.
631
+ */
632
+ __impl?: 'canvas' | 'dom';
633
+ }
634
+
635
+ declare const Sheets: <TRow extends SheetsRow = SheetsRow>(props: DataGridProps<TRow> & {
636
+ ref?: React__default.Ref<SheetsHandle>;
637
+ }) => React__default.ReactElement;
638
+ type SheetsProps<TRow extends SheetsRow = SheetsRow> = DataGridProps<TRow>;
639
+
640
+ type RelationMetadataSource = 'relation' | 'foreignKey';
641
+ interface RelationMetadata {
642
+ tableName: string;
643
+ fieldName: string;
644
+ relationKind: 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';
645
+ targetTable: string;
646
+ isOptional: boolean;
647
+ foreignKeyFields: string[];
648
+ /** Headline relation field name when this metadata originates from a foreign key */
649
+ relationFieldName?: string | null;
650
+ /** Primary foreign key field associated with the relation */
651
+ foreignKeyField?: string;
652
+ /** Indicates whether the metadata entry is for the relation field or the FK column */
653
+ sourceField: RelationMetadataSource;
654
+ junctionTable?: string;
655
+ displayName?: string;
656
+ }
657
+
658
+ type RelationKind = 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';
659
+ /** Native column descriptor — key/title/width, mappable 1:1 to {@link SheetsColumnDescriptor}. */
660
+ interface RelationGridColumn {
661
+ id: string;
662
+ title: string;
663
+ width: number;
664
+ }
665
+ /**
666
+ * Relation-aware column info with simple error handling
667
+ */
668
+ interface RelationColumnInfo {
669
+ columns: RelationGridColumn[];
670
+ columnKeys: string[];
671
+ relationMetadata: Record<string, RelationMetadata>;
672
+ metaFields?: FieldMetadata[];
673
+ hasRelationErrors: boolean;
674
+ relationCount: number;
675
+ isImageField: (fieldMeta: FieldMetadata | undefined, fieldName?: string) => boolean;
676
+ findImageColumnKey: (columnKeys: string[], fieldMetaMap: Map<string, unknown>, currentColKey?: string) => string;
677
+ getRelationKind: (fieldName: string) => RelationKind | null;
678
+ isRelationField: (fieldName: string) => boolean;
679
+ invalidateRelationCache: () => Promise<void>;
680
+ relationTypeByField: Map<string, RelationKind>;
681
+ }
682
+ /**
683
+ * Create data grid columns with relation metadata baked in
684
+ */
685
+ declare function useRelationColumns(tableName?: string, rows?: unknown[]): RelationColumnInfo;
686
+ /**
687
+ * Drop-in replacement for the original useDataGridColumns hook
688
+ * Maintains complete backward compatibility while providing improvements
689
+ */
690
+ declare function useDataGridColumns(tableName?: string, rows?: unknown[]): {
691
+ columns: RelationGridColumn[];
692
+ columnKeys: string[];
693
+ metaFields: FieldMetadata[] | undefined;
694
+ isImageField: (fieldMeta: FieldMetadata | undefined, fieldName?: string) => boolean;
695
+ findImageColumnKey: (columnKeys: string[], fieldMetaMap: Map<string, unknown>, currentColKey?: string) => string;
696
+ relationTypeByField: Map<string, RelationKind>;
697
+ relationMetadata: Record<string, RelationMetadata>;
698
+ hasRelationErrors: boolean;
699
+ relationCount: number;
700
+ getRelationKind: (fieldName: string) => RelationKind | null;
701
+ isRelationField: (fieldName: string) => boolean;
702
+ invalidateRelationCache: () => Promise<void>;
703
+ };
704
+
705
+ /** The built-in engine the registry falls back to (injected to avoid a cycle). */
706
+ interface CellTypeBuiltins {
707
+ toSheetsCell: (value: unknown, ctx: SheetsCellRenderContext) => SheetsCell;
708
+ }
709
+ interface CellTypeRegistry {
710
+ /** Detection: consumer `match()` chain first (later defs win), else the built-in resolver. */
711
+ resolveTypeKey(meta: CellTypeMatchInput, builtinFallback: () => string): string;
712
+ /** Native display: consumer `def.toSheetsCell` for this typeKey, else the built-in renderer. */
713
+ toSheetsCell(typeKey: string, value: unknown, ctx: SheetsCellRenderContext): SheetsCell;
714
+ /** The registered definition for a typeKey, if any (consumer defs only). */
715
+ get(typeKey: string): CellTypeDefinition<any> | undefined;
716
+ /** The native cell COMPONENT override for a typeKey, if any (consumer `def.cell`). */
717
+ getCellComponent(typeKey: string): React.ComponentType<CellProps> | undefined;
718
+ /** The native EDITOR override for a typeKey, if any (consumer `def.editorComponent`). */
719
+ getEditorComponent(typeKey: string): React.ComponentType<EditorProps> | undefined;
720
+ }
721
+ /**
722
+ * Build a registry. `cellTypes` are consumer definitions in precedence order
723
+ * (provider `plugins` first, then per-instance `cellTypes`); later entries win,
724
+ * so an instance-level def overrides a provider-level one with the same typeKey.
725
+ */
726
+ declare function createCellTypeRegistry(cellTypes: CellTypeDefinition<any>[], builtins: CellTypeBuiltins): CellTypeRegistry;
727
+
728
+ /** Result of submitting a draft row */
729
+ interface DraftSubmitResult {
730
+ /** The created row with real database ID */
731
+ createdRow: {
732
+ id: string | number;
733
+ [key: string]: unknown;
734
+ } | null;
735
+ }
736
+
737
+ /** Resolved DOM cell payload: the neutral cell plus its (optional) view component. */
738
+ interface SheetsCellResolution {
739
+ cell: SheetsCell;
740
+ component?: React.ComponentType<CellProps>;
741
+ colKey: string;
742
+ /**
743
+ * The resolved cell-type key (post detection-override) — the SINGLE source of
744
+ * truth the host feeds to `resolveEditIntent` to route activation. Always set;
745
+ * `'text'` for the loading/empty fallthrough cells that carry no type. (Mirror
746
+ * of the `meta.cellType` the cell itself now self-describes.)
747
+ */
748
+ typeKey: string;
749
+ /** Field metadata for the column — fed to a native overlay editor's EditorProps.fieldMeta. */
750
+ fieldMeta?: FieldMetadata;
751
+ /** Relation info for the column (when relational) — fed to a native overlay editor's EditorProps.relationInfo. */
752
+ relationInfo?: RelationInfo;
753
+ }
754
+
755
+ type FilterValue = string | number | boolean | null | undefined;
756
+ type FilterNode = FilterCondition | FilterGroup;
757
+ interface FilterCondition {
758
+ type: "condition";
759
+ id: string;
760
+ field: string;
761
+ operator: string;
762
+ value: FilterValue;
763
+ }
764
+ interface FilterGroup {
765
+ type: "group";
766
+ id: string;
767
+ conjunction: "and" | "or";
768
+ children: FilterNode[];
769
+ }
770
+ declare const MAX_FILTER_DEPTH = 3;
771
+ type FieldTypeMap = Record<string, {
772
+ gqlType: string;
773
+ isArray: boolean;
774
+ }>;
775
+ declare function createEmptyGroup(conjunction?: "and" | "or"): FilterGroup;
776
+ declare function countConditions(node: FilterNode): number;
777
+ interface SheetsControlsProps {
778
+ openSearch?: () => void;
779
+ filterTree: FilterGroup;
780
+ setFilterTree: (tree: FilterGroup) => void;
781
+ filtersOpen: boolean;
782
+ setFiltersOpen: (open: boolean) => void;
783
+ clearAllFilters: () => void;
784
+ applyFilters: () => void;
785
+ columnKeys: string[];
786
+ fieldTypeMap: FieldTypeMap;
787
+ showSelection: boolean;
788
+ gridSelection: SheetsSelection | null;
789
+ setGridSelection: (selection: SheetsSelection | null) => void;
790
+ deleteSelected: () => void;
791
+ onAddRow?: () => void;
792
+ onExport?: () => void;
793
+ }
794
+ declare function SheetsControls(props: SheetsControlsProps): react_jsx_runtime.JSX.Element;
795
+
796
+ interface GridState {
797
+ sorting: {
798
+ id: string | null;
799
+ desc: boolean;
800
+ };
801
+ pageIndex: number;
802
+ filterTree: FilterGroup;
803
+ filtersOpen: boolean;
804
+ columnWidths: Map<string, number>;
805
+ gridSelection: SheetsSelection | undefined;
806
+ }
807
+ declare function useGridState(): {
808
+ state: GridState;
809
+ actions: {
810
+ setSorting: (sorting: GridState["sorting"]) => void;
811
+ toggleSorting: (colId: string) => void;
812
+ setPageIndex: (pageIndex: number) => void;
813
+ setFilterTree: (tree: FilterGroup) => void;
814
+ clearAllFilters: () => void;
815
+ toggleFiltersPanel: () => void;
816
+ setFiltersOpen: (open: boolean) => void;
817
+ resizeColumn: (id: string, width: number) => void;
818
+ setGridSelection: (selection: SheetsSelection | undefined) => void;
819
+ setActiveCell: (col: number, row: number) => void;
820
+ moveActiveCell: (dCol: number, dRow: number, colCount: number, rowCount: number) => void;
821
+ resetPageIfNeeded: (totalPages: number) => void;
822
+ };
823
+ };
824
+
825
+ type RowRecord$2 = Record<string, unknown>;
826
+ /** Data for a single loaded page */
827
+ interface PageData<T = RowRecord$2> {
828
+ rows: T[];
829
+ pageInfo: PageInfo;
830
+ pageIndex: number;
831
+ totalCount?: number;
832
+ }
833
+ /** Options for the infinite table hook */
834
+ interface UseInfiniteTableOptions {
835
+ /** Page size for fetching */
836
+ pageSize?: number;
837
+ /** Order by clauses */
838
+ orderBy?: Array<{
839
+ field: string;
840
+ direction: 'asc' | 'desc';
841
+ }>;
842
+ /** Filter conditions */
843
+ where?: Record<string, unknown>;
844
+ /** Field selection preset or custom selection */
845
+ select?: FieldSelection;
846
+ /** Enable/disable the hook */
847
+ enabled?: boolean;
848
+ /** Mutation options for CRUD operations */
849
+ mutationOptions?: MutationOptions;
850
+ }
851
+ /** Result from the infinite table hook */
852
+ interface UseInfiniteTableResult<T = RowRecord$2> {
853
+ /** Get row at a specific index, returns null if not loaded */
854
+ getRowAtIndex: (index: number) => T | null;
855
+ /** Total count of rows in the table */
856
+ totalCount: number;
857
+ /** Check if a specific row index is loaded */
858
+ isRowLoaded: (rowIndex: number) => boolean;
859
+ /** Check if a specific page is currently loading */
860
+ isPageLoading: (pageIndex: number) => boolean;
861
+ /** Ensure rows in a range are loaded (call from onVisibleRegionChanged) */
862
+ ensureRowsLoaded: (startRow: number, endRow: number) => void;
863
+ /** All loaded pages */
864
+ loadedPages: Map<number, PageData<T>>;
865
+ /** Page size */
866
+ pageSize: number;
867
+ /** Overall loading state (true if any page is loading) */
868
+ isLoading: boolean;
869
+ /** Whether initial data has been loaded */
870
+ hasInitialData: boolean;
871
+ /** Error from the most recent failed fetch */
872
+ error: Error | null;
873
+ /** Invalidate all pages and refetch */
874
+ invalidate: () => void;
875
+ /** Reset to initial state (clears all pages, refetches page 0) */
876
+ reset: () => void;
877
+ /**
878
+ * Optimistically update a single row in the page cache without refetching.
879
+ * @param rowIndex The absolute row index
880
+ * @param patch Partial row data to merge with existing row
881
+ * @returns true if the row was found and updated, false otherwise
882
+ */
883
+ updateRowAtIndex: (rowIndex: number, patch: Partial<T>) => boolean;
884
+ }
885
+ /**
886
+ * Hook for infinite scroll table with hybrid cursor-based pagination.
887
+ * Uses React Query cache as the source of truth for data persistence.
888
+ */
889
+ declare function useSheetsInfiniteTable<T extends RowRecord$2 = RowRecord$2>(tableName: string, options?: UseInfiniteTableOptions): UseInfiniteTableResult<T>;
890
+
891
+ /** Native inclusive row window — the DOM grid's visible-range shape (no glide Rectangle). */
892
+ interface VisibleRowRange {
893
+ startIndex: number;
894
+ endIndex: number;
895
+ }
896
+
897
+ /** Draft-row bindings for a headless shell. */
898
+ interface SheetsDraftBindings {
899
+ /** Whether any client-side draft rows exist. */
900
+ hasDrafts: boolean;
901
+ /** Append a new draft row. Returns the new row index. */
902
+ appendRow: () => Promise<number | undefined>;
903
+ /** Submit all pending draft rows. */
904
+ submitDrafts: () => Promise<void>;
905
+ /** Delete the currently selected rows (draft + server). */
906
+ deleteSelected: () => Promise<void>;
907
+ }
908
+ /**
909
+ * Selection bindings for a headless shell.
910
+ *
911
+ * The selection value is the native {@link SheetsSelection} (RangeSet-backed `rows`).
912
+ */
913
+ interface SheetsSelectionBindings {
914
+ /** Current native grid selection. */
915
+ gridSelection: SheetsSelection | undefined;
916
+ /** Setter. */
917
+ setGridSelection: (selection: SheetsSelection | undefined) => void;
918
+ /** Park the active cell on `[col, row]` (preserves row/column selection). */
919
+ setActiveCell: (col: number, row: number) => void;
920
+ /** Move the active cell by `[dCol, dRow]`, clamped to grid bounds. */
921
+ moveActive: (dCol: number, dRow: number, colCount: number, rowCount: number) => void;
922
+ }
923
+ /** Pagination bindings for a headless shell (paginated mode). */
924
+ interface SheetsPaginationBindings {
925
+ /** Current zero-based page index. */
926
+ pageIndex: number;
927
+ /** Total page count (>= 1). */
928
+ pageCount: number;
929
+ /** Set the page index (emits a `page:change` event). */
930
+ setPageIndex: (updater: number | ((prev: number) => number)) => void;
931
+ }
932
+ /**
933
+ * Stable headless surface returned by {@link useSheets}. (The hook also returns a
934
+ * few `_shell`-grouped extras consumed only by the built-in {@link Sheets} chrome —
935
+ * those are not part of this supported contract.)
936
+ */
937
+ interface UseSheetsResult {
938
+ /** Native column descriptors (key/title/width). */
939
+ columns: RelationGridColumn[];
940
+ /** Number of rows to render. */
941
+ rowCount: number;
942
+ /** Draft-row bindings. */
943
+ draft: SheetsDraftBindings;
944
+ /** Selection bindings. */
945
+ selection: SheetsSelectionBindings;
946
+ /** Pagination bindings. */
947
+ pagination: SheetsPaginationBindings;
948
+ /** True only during the very first load (refetches keep previous data). */
949
+ isInitialLoading: boolean;
950
+ /** Data-load error, if any. */
951
+ dataError: Error | null;
952
+ /** Whether the initial load has completed (success). */
953
+ hasCompletedInitialLoad: boolean;
954
+ /** True when loaded, no server rows, no drafts, and no active filter. */
955
+ isEmpty: boolean;
956
+ /** Refetch the underlying data (mode-aware: infinite vs paginated). */
957
+ refetch: () => void;
958
+ }
959
+ /**
960
+ * Internal bindings consumed only by the built-in {@link Sheets} chrome
961
+ * (toolbar, dock, pagination chrome). NOT a supported part of the headless contract.
962
+ */
963
+ interface SheetsShellBindings {
964
+ combinedRows: SheetsRow[];
965
+ columnKeys: string[];
966
+ totalCount: number;
967
+ serverRowCount: number;
968
+ draftRowCount: number;
969
+ infiniteScroll: boolean;
970
+ filterTree: ReturnType<typeof useGridState>['state']['filterTree'];
971
+ filtersOpen: boolean;
972
+ setFilterTree: ReturnType<typeof useGridState>['actions']['setFilterTree'];
973
+ setFiltersOpen: ReturnType<typeof useGridState>['actions']['setFiltersOpen'];
974
+ clearAllFilters: ReturnType<typeof useGridState>['actions']['clearAllFilters'];
975
+ applyFilters: () => void;
976
+ fieldTypeMap: Record<string, {
977
+ gqlType: string;
978
+ isArray: boolean;
979
+ }>;
980
+ setGridSelectionForControls: (selection: SheetsSelection | null) => void;
981
+ /** Header sort toggle (colIndex → toggleSorting on the sortable column). */
982
+ onHeaderClicked: (colIndex: number) => void;
983
+ /** Prefetch the rows in an inclusive visible window (native range, infinite mode). */
984
+ onVisibleRegionChanged: (range: VisibleRowRange) => void;
985
+ /** @internal Sort state mirror ({ id, desc }) — the DOM header reads this for its caret. NOT a stable API. */
986
+ sorting: ReturnType<typeof useGridState>['state']['sorting'];
987
+ /** @internal Committed column widths (id → px) — the DOM grid maps these to v9 columnSizing. NOT a stable API. */
988
+ columnWidths: ReturnType<typeof useGridState>['state']['columnWidths'];
989
+ /** @internal Commit a column width (id, px) — the DOM resize handle drives this directly. NOT a stable API. */
990
+ resizeColumn: ReturnType<typeof useGridState>['actions']['resizeColumn'];
991
+ frozenCount: number;
992
+ selectedRowCount: number;
993
+ isSubmittingDrafts: boolean;
994
+ submitDraftButtonDisabled: boolean;
995
+ submitDraftLabel: string;
996
+ /** @internal Native DOM content resolver for the TanStack DOM grid. NOT a stable API. */
997
+ getSheetsCellContent: (rowIndex: number, colKey: string) => SheetsCellResolution;
998
+ /** @internal Per-instance cell-type registry (consumer overrides over built-ins). NOT a stable API. */
999
+ cellRegistry: CellTypeRegistry;
1000
+ /** @internal Native value-commit for the TanStack DOM portal editors. NOT a stable API. */
1001
+ commitCellValue: (rowIndex: number, colKey: string, nextValue: unknown) => void;
1002
+ /** @internal Batched server-row value commit (paste/fill/bulk + the single cell). NOT a stable API. */
1003
+ commitCells: (writes: CellWrite[], opts?: CommitCellsOptions) => Promise<CommitCellsResult>;
1004
+ /** @internal Native MULTI-field patch-commit for self-committing DOM portal editors (relation/image). NOT a stable API. */
1005
+ commitCellPatch: (rowIndex: number, patch: Record<string, unknown>) => void;
1006
+ /** @internal Submit a client-side draft row for a self-committing DOM portal editor. NOT a stable API. */
1007
+ submitDraftRow: (draftRowId: string) => Promise<DraftSubmitResult>;
1008
+ /** @internal Invalidate cached grid data after a self-committing DOM portal editor mutates out-of-band. NOT a stable API. */
1009
+ invalidateData: () => void;
1010
+ /** @internal Undo the last recorded server-row value write. NOT a stable API. */
1011
+ undo: () => Promise<void>;
1012
+ /** @internal Redo the last undone server-row value write. NOT a stable API. */
1013
+ redo: () => Promise<void>;
1014
+ /** @internal Whether an undo is available. NOT a stable API. */
1015
+ canUndo: boolean;
1016
+ /** @internal Whether a redo is available. NOT a stable API. */
1017
+ canRedo: boolean;
1018
+ /** @internal Observational event emitter (analytics/telemetry) — threaded into the command context. NOT a stable API. */
1019
+ emit: (type: SheetsEvent['type'], meta?: Record<string, unknown>) => void;
1020
+ }
1021
+ type UseSheetsInternalResult<TRow extends SheetsRow = SheetsRow> = UseSheetsResult & {
1022
+ /** @internal Bindings for the built-in <Sheets> chrome — not a stable API. */
1023
+ _shell: SheetsShellBindings;
1024
+ };
1025
+ /**
1026
+ * Headless grid hook — returns the data/state bindings the built-in {@link Sheets}
1027
+ * component renders with the native DOM grid.
1028
+ *
1029
+ * Preconditions:
1030
+ * - You MUST render inside a `<FeedbackProvider>` (exported from this package) —
1031
+ * the hook uses the bulk-operation feedback context and throws without it.
1032
+ *
1033
+ * NOTE: the generic `TRow` flows through {@link DataGridProps}'s row callbacks
1034
+ * (e.g. `onRowSelect`). It does not retype the cell bindings, which operate on
1035
+ * the dynamic schema-derived row shape.
1036
+ */
1037
+ declare function useSheets<TRow extends SheetsRow = SheetsRow>(props: DataGridProps<TRow>): UseSheetsInternalResult<TRow>;
1038
+
1039
+ interface SheetsPaginationProps {
1040
+ pageIndex: number;
1041
+ pageSize: number;
1042
+ totalCount: number;
1043
+ totalPages: number;
1044
+ setPageIndex: React.Dispatch<React.SetStateAction<number>>;
1045
+ }
1046
+ declare function SheetsPagination(props: SheetsPaginationProps): react_jsx_runtime.JSX.Element;
1047
+
1048
+ type TableWithCategory = {
1049
+ name: string;
1050
+ category?: string;
1051
+ };
1052
+ interface TableSelectorProps {
1053
+ tables: string[] | TableWithCategory[];
1054
+ activeTable: string;
1055
+ onTableChange: (table: string) => void;
1056
+ isLoading?: boolean;
1057
+ /** When true, scroll the active table into view and expand its section */
1058
+ shouldScrollToActive?: boolean;
1059
+ /** Optional callback when user clicks the "New table" button */
1060
+ onNewTable?: () => void;
1061
+ }
1062
+ declare const SheetsTableSelector: React__default.NamedExoticComponent<TableSelectorProps>;
1063
+
1064
+ interface UseMetaOptions {
1065
+ enabled?: boolean;
1066
+ }
1067
+ declare function useSheetsMeta(options?: UseMetaOptions): UseQueryResult<MetaQuery, Error>;
1068
+
1069
+ type RowRecord$1 = Record<string, unknown>;
1070
+ type DeleteIdentifier = string | number | Record<string, string | number>;
1071
+ /**
1072
+ * Unified table hook options
1073
+ */
1074
+ interface UseTableOptions extends QueryOptions {
1075
+ /** Enable/disable automatic data fetching */
1076
+ enabled?: boolean;
1077
+ /** Field selection for queries */
1078
+ select?: FieldSelection;
1079
+ /** Mutation options */
1080
+ mutationOptions?: MutationOptions;
1081
+ }
1082
+ /**
1083
+ * Unified table hook result
1084
+ */
1085
+ interface UseTableResult<TData extends RowRecord$1 = RowRecord$1> {
1086
+ data: TData[];
1087
+ totalCount: number;
1088
+ isLoading: boolean;
1089
+ error: Error | null;
1090
+ findOne: (id: string | number) => Promise<TData | null>;
1091
+ create: (data: RowRecord$1) => Promise<{
1092
+ createdRow: TData | null;
1093
+ }>;
1094
+ update: (id: string | number, patch: RowRecord$1) => Promise<{
1095
+ updatedRow: TData | null;
1096
+ }>;
1097
+ delete: (id: DeleteIdentifier) => Promise<{
1098
+ deletedId: DeleteIdentifier;
1099
+ }>;
1100
+ isCreating: boolean;
1101
+ isUpdating: boolean;
1102
+ isDeleting: boolean;
1103
+ createError: Error | null;
1104
+ updateError: Error | null;
1105
+ deleteError: Error | null;
1106
+ refetch: () => Promise<unknown>;
1107
+ invalidate: () => void;
1108
+ }
1109
+ /**
1110
+ * Generate query keys for consistent cache management
1111
+ */
1112
+ declare const sheetsTableQueryKeys: {
1113
+ scope: (scope: SheetsScopeKey) => readonly ["sheets", SheetsScopeKey];
1114
+ table: (scope: SheetsScopeKey, tableName: string) => readonly ["sheets", SheetsScopeKey, "table", string];
1115
+ tableRows: (scope: SheetsScopeKey, tableName: string, options?: QueryOptions) => readonly ["sheets", SheetsScopeKey, "table", string, "rows", unknown];
1116
+ tableRow: (scope: SheetsScopeKey, tableName: string, id: unknown) => readonly ["sheets", SheetsScopeKey, "table", string, "row", unknown];
1117
+ tableCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown>) => readonly ["sheets", SheetsScopeKey, "table", string, "count", Record<string, unknown> | null | undefined];
1118
+ };
1119
+ /**
1120
+ * Main unified table hook
1121
+ * Returns all table operations in a single hook
1122
+ */
1123
+ declare function useSheetsTable<TData extends RowRecord$1 = RowRecord$1>(tableName: string, options?: UseTableOptions): UseTableResult<TData>;
1124
+
1125
+ type RowRecord = Record<string, unknown>;
1126
+ interface UseSheetsTableCursorOptions {
1127
+ enabled?: boolean;
1128
+ select?: FieldSelection;
1129
+ pageSize?: number;
1130
+ where?: Filter;
1131
+ orderBy?: Array<{
1132
+ field: string;
1133
+ direction: 'asc' | 'desc';
1134
+ }>;
1135
+ }
1136
+ interface UseSheetsTableCursorResult<TData extends RowRecord = RowRecord> {
1137
+ data: TData[];
1138
+ totalCount: number;
1139
+ isLoading: boolean;
1140
+ isFetchingNextPage: boolean;
1141
+ hasNextPage: boolean;
1142
+ fetchNextPage: () => void;
1143
+ error: Error | null;
1144
+ }
1145
+ declare function useSheetsTableCursor<TData extends RowRecord = RowRecord>(tableName: string, options?: UseSheetsTableCursorOptions): UseSheetsTableCursorResult<TData>;
1146
+
1147
+ /**
1148
+ * Upload progress callback type
1149
+ */
1150
+ interface UploadProgress {
1151
+ loaded: number;
1152
+ total: number;
1153
+ percentage: number;
1154
+ }
1155
+ /**
1156
+ * Upload response from backend
1157
+ */
1158
+ interface UploadResponse {
1159
+ url: string;
1160
+ filename: string;
1161
+ mime: string;
1162
+ size: number;
1163
+ }
1164
+ /**
1165
+ * Field upload options
1166
+ */
1167
+ interface UseFieldUploadOptions {
1168
+ onProgress?: (progress: UploadProgress) => void;
1169
+ onSuccess?: (data: UploadResponse) => void;
1170
+ onError?: (error: Error) => void;
1171
+ showToast?: boolean;
1172
+ successMessage?: string;
1173
+ successToastDelayMs?: number;
1174
+ }
1175
+ interface UploadNaming {
1176
+ mutationName: string;
1177
+ singularName: string;
1178
+ patchFieldName: string;
1179
+ updateInputTypeName: string;
1180
+ }
1181
+ interface ExecuteFieldUploadOptions {
1182
+ onAuthError?: () => void;
1183
+ /**
1184
+ * Transport seam. When the hooks call this, they thread the context
1185
+ * `execute`/`executeUpload` here so injected/mock implementations intercept
1186
+ * both steps. When omitted (e.g. image-editor's direct retry path), the
1187
+ * functions are built from `endpoint`/`getToken`/`onAuthError` via the same
1188
+ * factories — never a raw fetch.
1189
+ */
1190
+ execute?: SheetsExecuteFn;
1191
+ executeUpload?: SheetsUploadFn;
1192
+ onProgress?: (progress: UploadProgress) => void;
1193
+ }
1194
+ /**
1195
+ * Execute field upload using two sequential requests, both routed through the
1196
+ * injectable transport seam:
1197
+ * 1. File upload via `executeUpload` → returns file metadata
1198
+ * 2. GraphQL mutation via `execute` to patch the row with the upload result
1199
+ *
1200
+ * Exported for direct use when record ID is known at call time (e.g., after draft submission)
1201
+ *
1202
+ * @param tableName - Table name
1203
+ * @param fieldName - Field name for the upload (the actual DB column, e.g. "photo")
1204
+ * @param recordId - Record ID to update
1205
+ * @param file - File to upload
1206
+ * @param endpoint - GraphQL endpoint URL (used to build the seam when none injected)
1207
+ * @param getToken - Function that returns the current auth token (or null)
1208
+ * @param naming - Optional pre-resolved naming overrides
1209
+ * @param options - Auth callback + optional injected execute/executeUpload + progress
1210
+ */
1211
+ declare function executeFieldUpload(tableName: string, fieldName: string, recordId: string | number, file: File, endpoint: string, getToken: () => string | null, naming?: UploadNaming, options?: ExecuteFieldUploadOptions): Promise<UploadResponse>;
1212
+ /**
1213
+ * Hook for uploading files to specific table fields
1214
+ * Integrates with the existing dynamic mutation system
1215
+ */
1216
+ declare function useSheetsFieldUpload(tableName: string, fieldName: string, recordId: string | number, options?: UseFieldUploadOptions): _tanstack_react_query.UseMutationResult<UploadResponse, Error, File, unknown>;
1217
+ /**
1218
+ * Hook for uploading images with validation
1219
+ * Convenience wrapper around useSheetsFieldUpload with image-specific validation
1220
+ */
1221
+ declare function useSheetsImageUpload(tableName: string, fieldName: string, recordId: string | number, options?: UseFieldUploadOptions): _tanstack_react_query.UseMutationResult<UploadResponse, Error, File, unknown>;
1222
+
1223
+ declare function isSheetsScopeKey(value: unknown): value is SheetsScopeKey;
1224
+ declare const sheetsQueryKeys: {
1225
+ readonly root: readonly ["sheets"];
1226
+ readonly scope: (scope: SheetsScopeKey) => readonly ["sheets", SheetsScopeKey];
1227
+ readonly meta: (scope: SheetsScopeKey) => readonly ["sheets", SheetsScopeKey, "meta"];
1228
+ readonly typeFields: (scope: SheetsScopeKey, typeName: string) => readonly ["sheets", SheetsScopeKey, "type-fields", string];
1229
+ readonly enumValues: (scope: SheetsScopeKey, typeName: string) => readonly ["sheets", SheetsScopeKey, "enum-values", string];
1230
+ readonly relations: (scope: SheetsScopeKey, tableName: string) => readonly ["sheets", SheetsScopeKey, "relations", string];
1231
+ readonly table: (scope: SheetsScopeKey, tableName: string) => readonly ["sheets", SheetsScopeKey, "table", string];
1232
+ readonly tableRows: (scope: SheetsScopeKey, tableName: string, options?: unknown) => readonly ["sheets", SheetsScopeKey, "table", string, "rows", unknown];
1233
+ readonly tableRow: (scope: SheetsScopeKey, tableName: string, id: unknown) => readonly ["sheets", SheetsScopeKey, "table", string, "row", unknown];
1234
+ readonly tableCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown> | null) => readonly ["sheets", SheetsScopeKey, "table", string, "count", Record<string, unknown> | null | undefined];
1235
+ readonly infiniteTable: (scope: SheetsScopeKey, tableName: string) => readonly ["sheets", SheetsScopeKey, "infinite-table", string];
1236
+ readonly infiniteTablePage: (scope: SheetsScopeKey, tableName: string, pageIndex: number, options: unknown) => readonly ["sheets", SheetsScopeKey, "infinite-table", string, "page", number, unknown];
1237
+ readonly infiniteTableTotalCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown>) => readonly ["sheets", SheetsScopeKey, "infinite-table", string, "totalCount", Record<string, unknown> | undefined];
1238
+ readonly cursorTable: (scope: SheetsScopeKey, tableName: string, options?: unknown) => readonly ["sheets", SheetsScopeKey, "cursor-table", string, unknown];
1239
+ };
1240
+
1241
+ /**
1242
+ * Create the default PostGraphile-backed adapter. Stateless — safe to share as a
1243
+ * module-level singleton.
1244
+ */
1245
+ declare function createPostGraphileAdapter(): SheetsBackendAdapter;
1246
+
1247
+ /**
1248
+ * Resolve the active backend adapter. A consumer that never sets
1249
+ * `config.adapter` transparently gets the default PostGraphile adapter,
1250
+ * preserving today's behavior exactly.
1251
+ */
1252
+ declare function useSheetsAdapter(): SheetsBackendAdapter;
1253
+
1254
+ declare class CellRegistryClass {
1255
+ private entries;
1256
+ private plugins;
1257
+ register(entry: CellRegistryEntry): void;
1258
+ registerBatch(entries: CellRegistryEntry[]): void;
1259
+ get(type: CellType): CellRegistryEntry | undefined;
1260
+ getAll(): CellRegistryEntry[];
1261
+ getComponent(type: CellType): CellRenderer | undefined;
1262
+ findByMatch(metadata: {
1263
+ gqlType: string;
1264
+ isArray: boolean;
1265
+ pgAlias?: string | null;
1266
+ pgType?: string | null;
1267
+ subtype?: string | null;
1268
+ fieldName?: string;
1269
+ }): CellRegistryEntry | undefined;
1270
+ getComponentWithMatch(type: CellType, metadata?: {
1271
+ gqlType: string;
1272
+ isArray: boolean;
1273
+ pgAlias?: string | null;
1274
+ pgType?: string | null;
1275
+ subtype?: string | null;
1276
+ fieldName?: string;
1277
+ }): CellRenderer | undefined;
1278
+ getEditComponent(type: CellType): CellRenderer | undefined;
1279
+ has(type: CellType): boolean;
1280
+ installPlugin(plugin: CellPlugin): void;
1281
+ uninstallPlugin(pluginName: string): void;
1282
+ getInstalledPlugins(): CellPlugin[];
1283
+ clear(): void;
1284
+ getByCategory(category: string): CellRegistryEntry[];
1285
+ }
1286
+ /**
1287
+ * @deprecated since 0.2.0 — pass cell types via <SheetsProvider config={{ plugins }}> or <Sheets cellTypes>. CellRegistry only ever affected detection.
1288
+ */
1289
+ declare const CellRegistry: CellRegistryClass;
1290
+
1291
+ /**
1292
+ * Canonical cell-type group constants.
1293
+ *
1294
+ * Every file that needs to check "is this cell type a date?" or "is this a
1295
+ * geometry?" should import from here instead of maintaining inline arrays.
1296
+ *
1297
+ * All Sets are typed as `Set<string>` so `.has(cellType)` works without casts.
1298
+ */
1299
+ declare const DATE_TIME_TYPES: Set<string>;
1300
+ declare const GEOMETRY_TYPES: Set<string>;
1301
+ declare const NUMBER_TYPES: Set<string>;
1302
+ declare const BOOLEAN_TYPES: Set<string>;
1303
+ declare const TYPED_ARRAY_TYPES: Set<string>;
1304
+ /** Check for any array-like cell type (typed arrays + generic `-array` suffix) */
1305
+ declare function isArrayCellType(cellType: string): boolean;
1306
+ declare const STRUCTURED_DATA_TYPES: Set<string>;
1307
+ declare const MEDIA_TYPES: Set<string>;
1308
+ declare const ENHANCED_TYPES: Set<string>;
1309
+ /** Cell types that use Glide's built-in text editor (no custom overlay). */
1310
+ declare const BUILTIN_EDITOR_TYPES: Set<string>;
1311
+ /** Cell types that are never editable (always read-only). */
1312
+ declare const NON_EDITABLE_TYPES: Set<string>;
1313
+ /** Cell types that can be activated for viewing but not editing. */
1314
+ declare const VIEWER_ONLY_TYPES: Set<string>;
1315
+
1316
+ /**
1317
+ * Maps GraphQL field metadata to frontend cell types
1318
+ * Uses priority: pgAlias > pgType > gqlType for type determination
1319
+ * This is completely backend-agnostic and focuses only on frontend rendering needs
1320
+ */
1321
+ declare function mapToFrontendCellType(metadata: {
1322
+ gqlType: string;
1323
+ isArray: boolean;
1324
+ pgAlias?: string | null;
1325
+ pgType?: string | null;
1326
+ subtype?: string | null;
1327
+ }): CellType;
1328
+ /**
1329
+ * Determines if a field represents structured data that should be rendered as JSON
1330
+ */
1331
+ declare function isStructuredDataType(cellType: CellType): boolean;
1332
+ /**
1333
+ * Create a ColumnSchema from GraphQL meta field data
1334
+ */
1335
+ declare function createColumnSchemaFromMeta(field: {
1336
+ name: string;
1337
+ type: {
1338
+ gqlType: string;
1339
+ isArray: boolean;
1340
+ modifier?: string | number | null;
1341
+ pgAlias?: string | null;
1342
+ pgType?: string | null;
1343
+ subtype?: string | null;
1344
+ typmod?: any;
1345
+ };
1346
+ }): ColumnSchema;
1347
+
1348
+ /**
1349
+ * Range-value extractor — pulls the matrix of cell values covered by a
1350
+ * {@link SelectionRect} out of the (possibly virtualized) row array.
1351
+ *
1352
+ * PURE + SSR-safe — no React, no DOM. The BOUNDED contract is load-bearing: it
1353
+ * reads only the cells inside the rect (w×h), never enumerates `rows.length`, so
1354
+ * a paste/fill/copy targeting a few cells of a million-row grid stays O(w·h). An
1355
+ * unfetched proxy row (infinite-mode) reads as `null` -> its cells come back as
1356
+ * `null`; an out-of-range column reads as `null` too.
1357
+ *
1358
+ * Reused by P3 (paste/fill writes the same coordinate matrix back) and P4 (copy
1359
+ * serializes {@link toTSV}).
1360
+ */
1361
+
1362
+ /** The extracted block: a `values[row][col]` matrix plus the row indices + col keys it covers. */
1363
+ interface ExtractedRange {
1364
+ /** `values[r][c]` — outer index aligns with `rows[r]`, inner with `cols[c]`. */
1365
+ values: unknown[][];
1366
+ /** Absolute row indices covered (y .. y+height-1). */
1367
+ rows: number[];
1368
+ /** Column keys covered (columnKeys[x .. x+width-1]). */
1369
+ cols: string[];
1370
+ }
1371
+ /**
1372
+ * Read every cell inside `range` (half-open: x/width = cols, y/height = rows) from
1373
+ * `rows` keyed by `columnKeys`. `getDisplay`, when supplied, maps the raw value to
1374
+ * the value to emit (e.g. a display string for copy) — defaults to the raw value.
1375
+ * Null-safe for unfetched proxy rows and out-of-range columns.
1376
+ */
1377
+ declare function getCellsInRange(range: SelectionRect, rows: readonly unknown[], columnKeys: readonly string[], getDisplay?: (value: unknown, rowIndex: number, colKey: string) => unknown): ExtractedRange;
1378
+ /**
1379
+ * Serialize a value matrix to TSV (tab-joined cols, newline-joined rows). Each value
1380
+ * is stringified; `null`/`undefined` become an empty cell. Spreadsheet-paste shape —
1381
+ * reused by P4 copy.
1382
+ */
1383
+ declare function toTSV(values: readonly (readonly unknown[])[]): string;
1384
+
1385
+ /**
1386
+ * Fill-math — REPLICATE a source row/column across a target range (P4 Phase 3).
1387
+ *
1388
+ * PURE + SSR-safe (no React, no DOM) — the analog of {@link getCellsInRange} on the
1389
+ * WRITE side: it reads the seed cells out of the raw `rows` array (null-safe for
1390
+ * unfetched proxy rows / out-of-range columns, exactly like the extractor) and emits
1391
+ * the {@link CellWrite}[] the command hands to `commitCells` (readonly/UUID skips +
1392
+ * undo live inside that batch, never here).
1393
+ *
1394
+ * SCOPE — value REPLICATION only. Numeric/date SERIES detection (1,2 -> 3,4 ; Jan,Feb
1395
+ * -> Mar) is DEFERRED: every filled cell is a verbatim copy of the seed.
1396
+ */
1397
+
1398
+ /**
1399
+ * Fill DOWN: SOURCE = the TOP row of `range` (y). For each col `x..x+width-1`, replicate
1400
+ * the seed cell value into every row `y+1..y+height-1`. Returns the writes column-major
1401
+ * is not required — emitted row-major (top-to-bottom within each... actually outer loop is
1402
+ * target rows, inner is cols) so commitCells coalesces per row. A single-row range yields
1403
+ * no writes (nothing below the seed).
1404
+ */
1405
+ declare function fillDownWrites(range: SelectionRect, rows: readonly unknown[], columnKeys: readonly string[]): CellWrite[];
1406
+ /**
1407
+ * Fill RIGHT: SOURCE = the LEFT column of `range` (x). For each col `x+1..x+width-1`,
1408
+ * replicate that column's seed (the value in the LEFT column of the SAME row) rightward
1409
+ * across every row `y..y+height-1`. A single-column range yields no writes.
1410
+ */
1411
+ declare function fillRightWrites(range: SelectionRect, rows: readonly unknown[], columnKeys: readonly string[]): CellWrite[];
1412
+
1413
+ type MetaTable = NonNullable<NonNullable<NonNullable<MetaQuery['_meta']>['tables']>[number]>;
1414
+ type MetaField = NonNullable<NonNullable<MetaTable['fields']>[number]>;
1415
+ interface ScalarConstraintHints {
1416
+ isUnique?: boolean;
1417
+ isPrimaryKey?: boolean;
1418
+ }
1419
+ type ScalarFieldKind = 'text' | 'multiline' | 'email' | 'url' | 'phone' | 'uuid' | 'inet' | 'number' | 'integer' | 'smallint' | 'decimal' | 'currency' | 'percentage' | 'boolean' | 'bit' | 'date' | 'datetime' | 'timestamptz' | 'time' | 'json' | 'tsvector';
1420
+ interface ScalarFieldSpec {
1421
+ name: string;
1422
+ label: string;
1423
+ description?: string;
1424
+ kind: ScalarFieldKind;
1425
+ nullable: boolean;
1426
+ defaultValue?: unknown;
1427
+ enumValues?: string[];
1428
+ maxLength?: number;
1429
+ minLength?: number;
1430
+ minimum?: number;
1431
+ maximum?: number;
1432
+ numericPrecision?: number;
1433
+ numericScale?: number;
1434
+ metadata: {
1435
+ cellType: CellType;
1436
+ gqlType: string;
1437
+ pgType?: string | null;
1438
+ pgAlias?: string | null;
1439
+ subtype?: string | null;
1440
+ typmod?: number | null;
1441
+ };
1442
+ constraints: ScalarConstraintHints;
1443
+ }
1444
+ interface DynamicFormSpec {
1445
+ tableName: string;
1446
+ versionHash: string;
1447
+ fields: ScalarFieldSpec[];
1448
+ }
1449
+ interface BuildFormSpecOptions {
1450
+ /**
1451
+ * Optional set of field names that should be treated as multiline inputs despite being text-based.
1452
+ */
1453
+ multilineFields?: Set<string>;
1454
+ }
1455
+
1456
+ declare function buildScalarFormSpec(metaTable: MetaTable, options?: BuildFormSpecOptions): DynamicFormSpec | null;
1457
+ declare function findTableFormSpec(meta: MetaTable[] | null | undefined, tableName: string, options?: BuildFormSpecOptions): DynamicFormSpec | null;
1458
+
1459
+ declare function buildZodSchema(spec: DynamicFormSpec): z.ZodObject<Record<string, z.ZodTypeAny>>;
1460
+
1461
+ interface DynamicMutationResult<TData = unknown> {
1462
+ submit: (values: Record<string, unknown>) => Promise<TData | null>;
1463
+ isSubmitting: boolean;
1464
+ error: Error | null;
1465
+ }
1466
+ declare function useDynamicCreate(tableName: string): DynamicMutationResult;
1467
+ declare function useDynamicUpdate(tableName: string, rowId: string | number): DynamicMutationResult;
1468
+
1469
+ declare function createMetadataHash(value: unknown): string;
1470
+
1471
+ /**
1472
+ * Grid Feedback Reducer
1473
+ *
1474
+ * Manages transient UI feedback state for data grid bulk operations.
1475
+ * Uses vanilla React (useReducer) instead of Zustand since this state is:
1476
+ * - Local to the data grid component tree
1477
+ * - Ephemeral (no persistence needed)
1478
+ * - Automatically cleaned up on unmount
1479
+ */
1480
+ type OperationStatus = 'idle' | 'pending' | 'success' | 'partial' | 'error';
1481
+ interface OperationFeedback {
1482
+ id: string;
1483
+ type: 'delete' | 'submit' | 'update';
1484
+ status: OperationStatus;
1485
+ message: string;
1486
+ total: number;
1487
+ completed: number;
1488
+ failed: number;
1489
+ timestamp: number;
1490
+ /** Auto-dismiss duration in ms. 0 = persistent until manually cleared. */
1491
+ dismissAfter: number;
1492
+ }
1493
+ interface FeedbackState {
1494
+ /** Current bulk operation feedback (shown in floating status) */
1495
+ operation: OperationFeedback | null;
1496
+ }
1497
+
1498
+ interface FeedbackContextValue {
1499
+ state: FeedbackState;
1500
+ startOperation: (type: OperationFeedback['type'], total: number) => string;
1501
+ updateOperationProgress: (id: string, completed: number, failed: number) => void;
1502
+ completeOperation: (id: string, status: 'success' | 'partial' | 'error', message: string, dismissAfter?: number) => void;
1503
+ clearOperationFeedback: () => void;
1504
+ }
1505
+ interface FeedbackProviderProps {
1506
+ children: React.ReactNode;
1507
+ }
1508
+ declare function FeedbackProvider({ children }: FeedbackProviderProps): react_jsx_runtime.JSX.Element;
1509
+ declare function useFeedback(): FeedbackContextValue;
1510
+ /**
1511
+ * Hook for accessing only operation feedback - useful for dock status bar
1512
+ */
1513
+ declare function useOperationFeedback(): OperationFeedback | null;
1514
+
1515
+ interface DockStatusBarProps {
1516
+ className?: string;
1517
+ /** Called when user clicks retry on a failed/partial operation */
1518
+ onRetry?: () => void;
1519
+ }
1520
+ /**
1521
+ * Inline status bar that appears in the floating dock during bulk operations.
1522
+ * Replaces toast notifications for delete, submit, and batch update operations.
1523
+ *
1524
+ * Shows:
1525
+ * - Progress spinner + message during pending operations
1526
+ * - Success checkmark + message (auto-dismisses)
1527
+ * - Error/partial warning + message with optional retry
1528
+ */
1529
+ declare function DockStatusBar({ className, onRetry }: DockStatusBarProps): react_jsx_runtime.JSX.Element | null;
1530
+ /**
1531
+ * Compact variant for space-constrained layouts.
1532
+ * Shows only icon + abbreviated message.
1533
+ */
1534
+ declare function DockStatusBarCompact({ className }: {
1535
+ className?: string;
1536
+ }): react_jsx_runtime.JSX.Element | null;
1537
+
1538
+ interface FloatingStatusProps {
1539
+ className?: string;
1540
+ }
1541
+ /**
1542
+ * Standalone floating status indicator for bulk operations.
1543
+ * Shows independently of row selection, positioned at bottom-center of grid.
1544
+ */
1545
+ declare function FloatingStatus({ className }: FloatingStatusProps): react_jsx_runtime.JSX.Element;
1546
+
1547
+ interface SheetsErrorBoundaryProps {
1548
+ children: ReactNode;
1549
+ /** Called when a render error is caught. Mirrors SheetsConfig.onError. */
1550
+ onError?: (error: unknown, ctx?: {
1551
+ source?: 'grid' | 'editor' | 'mutation' | 'upload';
1552
+ tableName?: string;
1553
+ }) => void;
1554
+ /** Custom fallback. Receives the error and a reset callback to retry rendering. */
1555
+ fallback?: (error: unknown, reset: () => void) => ReactNode;
1556
+ }
1557
+ interface SheetsErrorBoundaryState {
1558
+ error: unknown;
1559
+ }
1560
+ /**
1561
+ * Render-error boundary for the grid subtree. Catches exceptions thrown during
1562
+ * render of the DataEditor and editors, logs them through the injectable logger,
1563
+ * forwards them to the host via onError, and shows a recoverable error state.
1564
+ */
1565
+ declare class SheetsErrorBoundary extends Component<SheetsErrorBoundaryProps, SheetsErrorBoundaryState> {
1566
+ state: SheetsErrorBoundaryState;
1567
+ static getDerivedStateFromError(error: unknown): SheetsErrorBoundaryState;
1568
+ componentDidCatch(error: unknown, info: ErrorInfo): void;
1569
+ reset: () => void;
1570
+ render(): ReactNode;
1571
+ }
1572
+
1573
+ interface SheetsErrorStateProps {
1574
+ error: unknown;
1575
+ onRetry?: () => void;
1576
+ }
1577
+ /** Shown when the table data (or its metadata) fails to load. */
1578
+ declare function SheetsErrorState({ error, onRetry }: SheetsErrorStateProps): react_jsx_runtime.JSX.Element;
1579
+ interface SheetsEmptyStateProps {
1580
+ tableName?: string;
1581
+ onAddRow?: () => void;
1582
+ }
1583
+ /** Shown when the table loaded successfully but has no rows. */
1584
+ declare function SheetsEmptyState({ tableName, onAddRow }: SheetsEmptyStateProps): react_jsx_runtime.JSX.Element;
1585
+ /**
1586
+ * Shown during the initial data load. A STRUCTURAL skeleton of the grid (baseline-ui:
1587
+ * prefer skeletons over spinners) — mirrors the real grid's 40px header + 44px rows +
1588
+ * horizontal hairlines so the load→loaded swap doesn't jump. Pulse is motion-safe only.
1589
+ */
1590
+ declare function SheetsLoadingState(): react_jsx_runtime.JSX.Element;
1591
+
1592
+ interface DataFilteringContextValue {
1593
+ filterTree: FilterGroup;
1594
+ filtersOpen: boolean;
1595
+ effectiveWhere: any;
1596
+ hasActiveFilters: boolean;
1597
+ setFilterTree: (tree: FilterGroup) => void;
1598
+ setFiltersOpen: (open: boolean) => void;
1599
+ clearAllFilters: () => void;
1600
+ applyFilters: () => void;
1601
+ }
1602
+ interface UseDataFilteringConfig {
1603
+ columnKeys: string[];
1604
+ tableMeta?: {
1605
+ fields?: Array<{
1606
+ name?: string | null;
1607
+ type?: {
1608
+ gqlType?: string | null;
1609
+ } | null;
1610
+ } | null> | null;
1611
+ } | null;
1612
+ initialFilterTree?: FilterGroup;
1613
+ }
1614
+ declare function useDataFiltering({ columnKeys, tableMeta, initialFilterTree, }: UseDataFilteringConfig): {
1615
+ contextValue: DataFilteringContextValue;
1616
+ Provider: ({ children }: {
1617
+ children: ReactNode;
1618
+ }) => ReactNode;
1619
+ };
1620
+
1621
+ interface DataPaginationContextValue {
1622
+ pageIndex: number;
1623
+ pageSize: number;
1624
+ totalCount: number;
1625
+ totalPages: number;
1626
+ hasNextPage: boolean;
1627
+ hasPreviousPage: boolean;
1628
+ startIndex: number;
1629
+ endIndex: number;
1630
+ setPageIndex: (index: number) => void;
1631
+ setPageSize: (size: number) => void;
1632
+ goToNextPage: () => void;
1633
+ goToPreviousPage: () => void;
1634
+ goToFirstPage: () => void;
1635
+ goToLastPage: () => void;
1636
+ }
1637
+ interface UseDataPaginationConfig {
1638
+ initialPageSize?: number;
1639
+ initialPageIndex?: number;
1640
+ totalCount?: number;
1641
+ onPageChange?: (pageIndex: number, pageSize: number) => void;
1642
+ }
1643
+ declare function useDataPagination({ initialPageSize, initialPageIndex, totalCount, onPageChange, }: UseDataPaginationConfig): {
1644
+ contextValue: DataPaginationContextValue;
1645
+ Provider: ({ children }: {
1646
+ children: any;
1647
+ }) => any;
1648
+ };
1649
+
1650
+ 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, type SheetsHandle, SheetsLoadingState, SheetsPagination, type SheetsPaginationBindings, type SheetsPaginationProps, type SheetsProps, SheetsProvider, type SheetsRow, 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, selectCell, selectRange, selectRow, sheetsQueryKeys, toTSV, toggleRow, tokensFromCssVars, useDataFiltering, useDataGridColumns, useDataPagination, useDynamicCreate, useDynamicUpdate, useFeedback, useOperationFeedback, useRelationColumns, useSheets, useSheetsAdapter, useSheetsFieldUpload, useSheetsImageUpload, useSheetsInfiniteTable, useSheetsMeta, useSheetsStore, useSheetsStoreApi, useSheetsTable, useSheetsTableCursor };