@constructive-io/sheets 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/grid/sheets.tsx","../src/grid/sheets.controls.tsx","../src/grid/filter-operators.ts","../src/grid/sheets.context-menu.tsx","../src/grid/feedback/feedback-context.tsx","../src/grid/feedback/feedback-reducer.ts","../src/grid/feedback/dock-status-bar.tsx","../src/utils/motion-config.ts","../src/grid/feedback/floating-status.tsx","../src/grid/feedback/sheets-error-boundary.tsx","../src/grid/feedback/sheets-error-state.tsx","../src/grid/sheets.pagination.tsx","../src/grid/use-sheets.ts","../src/hooks/use-relation-columns.ts","../src/cell-types/cell-registry.ts","../src/cell-types/type-mapping.ts","../src/cell-types/cell-type-resolver.ts","../src/grid/sheets.utils.ts","../src/hooks/use-relation-metadata-cache.ts","../src/grid/row-model.ts","../src/cell-types/cell-type-registry.ts","../src/cell-model/cell-slots.ts","../src/grid/sheets.constants.ts","../src/grid/hooks/use-cell-editing.ts","../src/grid/hooks/use-batch-commit.ts","../src/grid/hooks/use-undo-redo.ts","../src/grid/hooks/use-draft-rows.ts","../src/grid/hooks/use-draft-submission.ts","../src/config/sheets-concurrency.ts","../src/grid-dom/use-sheets-content.ts","../src/grid/cell-routing.ts","../src/grid/hooks/use-grid-operations.ts","../src/grid/hooks/use-grid-selection.ts","../src/grid/hooks/use-grid-state.ts","../src/selection/range-set.ts","../src/selection/selection-model.ts","../src/grid/hooks/use-infinite-grid-data.ts","../src/hooks/use-sheets-infinite-table.ts","../src/grid/hooks/use-load-grid.ts","../src/table/use-sheets-table-instance.ts","../src/table/features.ts","../src/table/grid-viewport.tsx","../src/grid-dom/sheets-cell-host.tsx","../src/cell-model/badge-tones.ts","../src/cell-model/views/badges-view.tsx","../src/cell-model/views/boolean-view.tsx","../src/cell-model/views/draft-action-view.tsx","../src/cell-model/views/geometry-view.tsx","../src/cell-model/views/image-view.tsx","../src/cell-model/image-cache.ts","../src/cell-model/views/loading-view.tsx","../src/cell-model/views/number-view.tsx","../src/cell-model/views/relation-view.tsx","../src/cell-model/views/text-view.tsx","../src/cell-model/views/uri-view.tsx","../src/grid-dom/inline-cell-editor.tsx","../src/grid-dom/overlay/use-overlay-controller.ts","../src/grid-dom/overlay/overlay-manager.tsx","../src/grid/feedback/editor-error-boundary.tsx","../src/grid-dom/editors/edit-intent.ts","../src/selection/cell-extract.ts","../src/selection/fill.ts","../src/selection/tsv.ts","../src/commands/registry.ts","../src/commands/dispatch.ts","../src/commands/keybinding.ts","../src/commands/keymap.ts","../src/grid/sheets.theme.ts","../src/grid/sheets.table-selector.tsx","../src/cell-types/define-cell-type.ts","../src/forms/metadata-hash.ts","../src/forms/form-spec-builder.ts","../src/forms/zod-schema.ts","../src/forms/mutations.ts","../src/grid/hooks/use-filter-grid.ts","../src/grid/hooks/use-paginate-grid.ts"],"sourcesContent":["import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\nimport type React from 'react';\nimport {\n\tfunctionalUpdate,\n\ttype ColumnPinningState,\n\ttype ColumnSizingState,\n\ttype OnChangeFn,\n\ttype RowSelectionState\n} from '@tanstack/react-table';\nimport { RiFilterOffLine, RiSearchEyeLine } from '@remixicon/react';\n\nimport { useSheetsContext } from '../context/sheets-context';\nimport { cn } from '../utils/cn';\nimport { Button } from '@constructive-io/ui/button';\nimport type { DataGridProps, SheetsHandle } from './sheets.types';\nimport type { SheetsRow } from './row-model';\n\nimport { SheetsControls, countConditions } from './sheets.controls';\nimport { SheetsContextMenu, type ContextMenuState } from './sheets.context-menu';\nimport { FeedbackProvider, FloatingStatus } from './feedback';\nimport { SheetsErrorBoundary } from './feedback/sheets-error-boundary';\nimport { SheetsEmptyState, SheetsErrorState, SheetsLoadingState } from './feedback/sheets-error-state';\nimport { SheetsPagination } from './sheets.pagination';\nimport { useSheets } from './use-sheets';\nimport { useSheetsTableInstance, type SheetsColumnDescriptor } from '../table/use-sheets-table-instance';\nimport { GridViewport, type GridViewportHandle, type RenderCell, type RowMarker, type VisibleRange } from '../table/grid-viewport';\nimport { SheetsCellHost, type OpenEditor } from '../grid-dom/sheets-cell-host';\nimport { useOverlayController } from '../grid-dom/overlay/use-overlay-controller';\nimport { OverlayManager } from '../grid-dom/overlay/overlay-manager';\nimport { resolveEditIntent } from '../grid-dom/editors/edit-intent';\nimport { computeOverlayGeometry } from './editors/overlay-viewport-guard';\nimport { RangeSet } from '../selection/range-set';\nimport { clear, emptySheetsSelection, extendRangeToCell, selectRange, toggleRow } from '../selection/selection-model';\nimport type { SelectionRect } from '../selection/selection-model';\nimport { getCellsInRange as extractCellsInRange, toTSV as serializeTSV } from '../selection/cell-extract';\nimport { bulkEditWrites } from '../selection/fill';\nimport { createGridCommandRegistry, type NavAbsolutePayload } from '../commands/registry';\nimport type { GridCommandRegistry } from '../commands/types';\nimport type { GridCommandContext, CellMatrix } from '../commands/context';\nimport { makeDispatch, tailObserver, type Dispatch, type Interceptor } from '../commands/dispatch';\nimport { resolveKeyCommand, DEFAULT_KEYMAP, type Binding } from '../commands/keymap';\n\n// Rows moved per PageUp/PageDown when the scroll element's clientHeight can't be read\n// (jsdom / detached). A sensible spreadsheet page span.\nconst FALLBACK_PAGE_ROWS = 10;\n/** Estimated body row height — MUST match grid-viewport's ESTIMATED_ROW_HEIGHT (page-span math). */\nconst ESTIMATED_ROW_HEIGHT = 34;\n\n/** Escape a single CSV field: wrap in quotes when it contains comma/quote/newline. */\nfunction escapeCsvField(value: unknown): string {\n\tconst str = value == null ? '' : String(value);\n\tif (/[\",\\n\\r]/.test(str)) {\n\t\treturn `\"${str.replace(/\"/g, '\"\"')}\"`;\n\t}\n\treturn str;\n}\n\n/**\n * Build a CSV string from rows + columns and trigger a browser download.\n * Dependency-free: values are stringified via String() (objects become\n * \"[object Object]\" — callers wanting rich serialization should pre-flatten).\n */\nfunction downloadCsv(rows: Record<string, unknown>[], columns: string[], filename?: string): void {\n\tif (typeof document === 'undefined') return;\n\tconst header = columns.map(escapeCsvField).join(',');\n\tconst body = rows.map((row) => columns.map((col) => escapeCsvField(row?.[col])).join(',')).join('\\n');\n\tconst csv = body ? `${header}\\n${body}` : header;\n\n\tconst blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });\n\tconst url = URL.createObjectURL(blob);\n\tconst link = document.createElement('a');\n\tlink.href = url;\n\tlink.download = filename ?? 'export.csv';\n\tdocument.body.appendChild(link);\n\tlink.click();\n\tdocument.body.removeChild(link);\n\tURL.revokeObjectURL(url);\n}\n\n/**\n * Coerce a cell's raw row value to a boolean for the inline-toggle commit — MUST\n * match the boolean SheetsCell factory (cell-model/factories/boolean.ts) so the\n * toggle flips against the SAME boolean the cell renders: null/undefined -> false,\n * a boolean passes through, anything else via Boolean(). The host commits the\n * negation, so an unset boolean toggles on first.\n */\nfunction coerceCellBoolean(value: unknown): boolean {\n\tif (value === null || value === undefined) return false;\n\treturn typeof value === 'boolean' ? value : Boolean(value);\n}\n\n/** The absolute-nav keys whose command (`cell.navAbsolute`) needs the payload below. */\nconst ABSOLUTE_NAV_KEYS = new Set(['Tab', 'Home', 'End', 'PageUp', 'PageDown']);\n\n/**\n * Build the dispatch payload for a key event. Only `cell.navAbsolute` (Tab/Home/End/Page*)\n * needs one — the funnel's old inline branch derived the page span from the scroll element's\n * clientHeight (e.currentTarget IS the scroll root), falling back to a constant under jsdom.\n * Arrows / extends / undo / redo / select-all / open read everything from the command context,\n * so they get `undefined`.\n */\nfunction buildKeyPayload(e: React.KeyboardEvent): NavAbsolutePayload | undefined {\n\tif (!ABSOLUTE_NAV_KEYS.has(e.key)) return undefined;\n\tconst clientHeight = (e.currentTarget as HTMLElement).clientHeight;\n\tconst pageRows = clientHeight > 0 ? Math.max(1, Math.floor(clientHeight / ESTIMATED_ROW_HEIGHT)) : FALLBACK_PAGE_ROWS;\n\treturn { key: e.key, ctrlOrMeta: e.ctrlKey || e.metaKey, shift: e.shiftKey, pageRows };\n}\n\nfunction SheetsInnerComponent<TRow extends SheetsRow = SheetsRow>(\n\tprops: DataGridProps<TRow>,\n\tref: React.ForwardedRef<SheetsHandle>,\n) {\n\t// The native TanStack DOM grid is the only render path (the canvas <DataEditor>\n\t// branch was removed at the glide cutover).\n\treturn (\n\t\t<FeedbackProvider>\n\t\t\t<SheetsDomInner {...props} forwardedRef={ref} />\n\t\t</FeedbackProvider>\n\t);\n}\n\n// forwardRef erases the component's own generic parameter; the cast restores a\n// generic call signature so `Sheets<MyRow>` keeps inferring TRow. This is the\n// single allowed `as` cast for Unit A (well-known generic-forwardRef pattern).\nexport const Sheets = forwardRef(SheetsInnerComponent) as <TRow extends SheetsRow = SheetsRow>(\n\tprops: DataGridProps<TRow> & { ref?: React.Ref<SheetsHandle> },\n) => React.ReactElement;\n\n// ============================================================================\n// The (only) render path. Reuses the useSheets hook for data/state, feeds its\n// bindings into the v9 table instance + GridViewport, and renders native DOM\n// cells via SheetsCellHost. Surfaces the same load states (error / loading /\n// empty + consumer slots) the removed canvas branch owned.\n// ============================================================================\n\n// Row selection (Phase 6), column sizing + pinning (Stage 2) are all wired to the shell now.\n// Pinning is shell-DERIVED (frozenCount), never edited from the grid, so its onChange is a no-op.\n// Stable empty row-selection map returned when nothing is selected.\nconst EMPTY_ROW_SELECTION: RowSelectionState = {};\nconst noop = () => {};\n\n// Overlay flip-geometry knobs — MUST match the OverlayManager's private constants so\n// the geometry we hand the editor via EditorProps.overlay matches where it's placed.\nconst OVERLAY_MARGIN_PX = 12;\nconst OVERLAY_MIN_BELOW_PX = 320;\n\nfunction SheetsDomInner<TRow extends SheetsRow = SheetsRow>({\n\tforwardedRef,\n\t...props\n}: DataGridProps<TRow> & { forwardedRef?: React.ForwardedRef<SheetsHandle> }) {\n\tconst {\n\t\ttableName,\n\t\tclassName,\n\t\tpageSize = 100,\n\t\tshowSelection = true,\n\t\tshowPagination = true,\n\t\tinfiniteScroll = false,\n\t\tslots,\n\t} = props;\n\tconst s = useSheets<TRow>(props);\n\tconst shell = s._shell;\n\n\tconst { config } = useSheetsContext();\n\n\tconst viewportRef = useRef<GridViewportHandle>(null);\n\n\t// ============== EVENT->COMMAND DISPATCH (P4 Phase 1) ==============\n\t// ONE interceptable pipeline: every grid event resolves to a named command and runs\n\t// through `dispatch`. The registry + keymap are latched (so a Phase 2 consumer override\n\t// is a ref swap, not a new dispatch identity); `ctxRef.current` is the assembled\n\t// GridCommandContext, repointed each render below (mirrors the openEditor ref-latch).\n\t// `dispatch` is useCallback([]) reading the refs, so it stays referentially STABLE — the\n\t// per-cell memo gates on the pointer callbacks that close over it, so it must never churn.\n\t// PUBLIC CUSTOMIZATION SEAM (P4 Phase 2): registry / keymap / interceptors derive from the\n\t// consumer props but rebuild ONLY when the prop IDENTITY changes (useMemo), so omitting them\n\t// is identical to the defaults. Each is latched into a ref so the keydown handler + dispatch\n\t// read the latest without re-creating. The PUBLIC `dispatch` callback stays referentially\n\t// STABLE (reads dispatchRef.current), so the per-cell memo never churns; dispatchRef itself is\n\t// rebuilt when the registry or interceptor list identity changes (additive, no identity leak).\n\tconst { commands, keymap, interceptors, onCommand } = props;\n\tconst registry = useMemo<GridCommandRegistry>(() => createGridCommandRegistry(commands), [commands]);\n\t// Consumer bindings scan FIRST (resolveKeyCommand is first-match-wins) so a rebind of a\n\t// built-in chord wins over the default; the defaults follow as the fallback set.\n\tconst fullKeymap = useMemo<Binding[]>(() => [...(keymap ?? []), ...DEFAULT_KEYMAP], [keymap]);\n\tconst keymapRef = useRef<Binding[]>(fullKeymap);\n\tkeymapRef.current = fullKeymap;\n\t// Consumer interceptors are OUTERMOST (first-listed); the onCommand tail observer is appended\n\t// LAST so it sits innermost (after every consumer interceptor) and observes the real result.\n\tconst chain = useMemo<Interceptor[]>(\n\t\t() => [...(interceptors ?? []), ...(onCommand ? [tailObserver(onCommand)] : [])],\n\t\t[interceptors, onCommand],\n\t);\n\tconst ctxRef = useRef<GridCommandContext>(undefined as unknown as GridCommandContext);\n\tconst dispatchRef = useRef<Dispatch>(undefined as unknown as Dispatch);\n\tdispatchRef.current = useMemo<Dispatch>(() => makeDispatch(registry, () => ctxRef.current, chain), [registry, chain]);\n\tconst dispatch = useCallback<Dispatch>((command, native, payload) => dispatchRef.current(command, native, payload), []);\n\n\tconst columns = useMemo<SheetsColumnDescriptor[]>(\n\t\t() => s.columns.map((col) => ({ key: col.id, name: col.title, size: col.width })),\n\t\t[s.columns],\n\t);\n\n\t// ============== COLUMN SIZING + PINNING STATE MIRROR (Stage 2) ==============\n\t// Sizing: project the shell's columnWidths Map → v9 ColumnSizingState; a width committed\n\t// by the header drag-resize handle goes STRAIGHT to resizeColumn (the same setter the canvas\n\t// onColumnResize uses), so the Map stays the single source of truth and the table just mirrors.\n\t// Pinning: pin col0 ('id') exactly when the canvas freezes it (frozenCount), else nothing —\n\t// GridViewport's findStickyColumnIndex falls back to col0 anyway, so the sticky column is identical.\n\tconst columnWidths = shell.columnWidths;\n\tconst resizeColumn = shell.resizeColumn;\n\tconst frozenCount = shell.frozenCount;\n\tconst firstColumnKey = shell.columnKeys[0];\n\n\tconst columnSizing = useMemo<Record<string, number>>(() => {\n\t\tconst sizing: Record<string, number> = {};\n\t\tcolumnWidths.forEach((width, key) => {\n\t\t\tsizing[key] = width;\n\t\t});\n\t\treturn sizing;\n\t}, [columnWidths]);\n\n\tconst columnPinning = useMemo<ColumnPinningState>(\n\t\t() => ({ start: frozenCount > 0 && firstColumnKey ? [firstColumnKey] : [], end: [] }),\n\t\t[frozenCount, firstColumnKey],\n\t);\n\n\tconst onColumnSizingChange = useCallback<OnChangeFn<ColumnSizingState>>(\n\t\t(updater) => {\n\t\t\tconst next = functionalUpdate(updater, columnSizing);\n\t\t\tfor (const key of Object.keys(next)) {\n\t\t\t\tif (next[key] !== columnSizing[key]) resizeColumn(key, next[key]);\n\t\t\t}\n\t\t},\n\t\t[columnSizing, resizeColumn],\n\t);\n\n\t// ============== ROW-SELECTION STATE MIRROR (Phase 6, both directions) ==============\n\t// The native SheetsSelection (RangeSet of ROW indices) stays canonical; the v9\n\t// table only needs a derived `Record<rowId, true>` view. Both directions use the\n\t// same metadata-defined row key, so renamed/composite PK selections round-trip.\n\tconst combinedRows = shell.combinedRows;\n\tconst getRowId = shell.getRowId;\n\tconst selection = s.selection.gridSelection;\n\tconst setSelection = s.selection.setGridSelection;\n\t// Active (keyboard cursor) cell `[col, row]`, threaded to the viewport for the focus ring +\n\t// aria-activedescendant. Derived in render (a plain read, no setState) per the no-setState-in-render rule.\n\tconst activeCell = selection?.current?.cell;\n\n\tconst rowSelection = useMemo<RowSelectionState>(() => {\n\t\tif (!selection) return EMPTY_ROW_SELECTION;\n\t\tconst map: RowSelectionState = {};\n\t\tfor (const index of selection.rows.toArray()) {\n\t\t\tmap[getRowId(combinedRows[index], index)] = true;\n\t\t}\n\t\treturn map;\n\t}, [selection, combinedRows, getRowId]);\n\n\tconst onRowSelectionChange = useCallback<OnChangeFn<RowSelectionState>>(\n\t\t(updater) => {\n\t\t\tconst next = functionalUpdate(updater, rowSelection);\n\t\t\t// Map the selected row IDS back to row INDICES via combinedRows, then fold\n\t\t\t// into a fresh RangeSet. Active cell follows the lowest selected index (or\n\t\t\t// clears to the empty selection when nothing is selected).\n\t\t\tconst indexById = new Map<string, number>();\n\t\t\tfor (let i = 0; i < combinedRows.length; i++) indexById.set(getRowId(combinedRows[i], i), i);\n\n\t\t\tlet rows = RangeSet.empty();\n\t\t\tlet lowest: number | undefined;\n\t\t\tfor (const id of Object.keys(next)) {\n\t\t\t\tif (!next[id]) continue;\n\t\t\t\tconst index = indexById.get(id);\n\t\t\t\tif (index === undefined) continue;\n\t\t\t\trows = rows.add(index);\n\t\t\t\tif (lowest === undefined || index < lowest) lowest = index;\n\t\t\t}\n\n\t\t\tif (lowest === undefined) {\n\t\t\t\tsetSelection(emptySheetsSelection);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsetSelection({ current: { cell: [0, lowest] }, rows, columns: RangeSet.empty() });\n\t\t},\n\t\t[rowSelection, combinedRows, getRowId, setSelection],\n\t);\n\n\tconst table = useSheetsTableInstance({\n\t\tcolumns,\n\t\tdata: combinedRows,\n\t\tcolumnSizing,\n\t\tcolumnPinning,\n\t\trowSelection,\n\t\tonColumnSizingChange,\n\t\t// Pinning is shell-derived (frozenCount), never edited from the grid → no writer needed.\n\t\tonColumnPinningChange: noop,\n\t\tonRowSelectionChange,\n\t\tgetRowId,\n\t});\n\n\t// ============== LEADING CHECKBOX / SELECT-ALL COLUMN (drives the canonical RangeSet) ==============\n\t// The DOM grid has no canvas rowMarkers, so the GridViewport paints a sticky checkbox column whose\n\t// toggles write the canonical SheetsSelection directly (the rowSelection mirror above derives FROM\n\t// it). selectRange/toggleRow/clear are the same pure helpers the canvas projection round-trips, so\n\t// shift-range and ctrl-toggle behave identically. `shiftAnchorRef` records the last-toggled index so\n\t// a subsequent shift-click selects the contiguous block — caller-owned, matching selectRange's contract.\n\tconst rowCount = combinedRows.length;\n\tconst shiftAnchorRef = useRef<number | null>(null);\n\t// Latch selection + rowCount so the STABLE toggle impls (ctx methods) read the latest values\n\t// without re-creating, while rowMarker's handlers dispatch the named commands through `dispatch`.\n\tconst rowMarkerSelectionRef = useRef(selection);\n\trowMarkerSelectionRef.current = selection;\n\tconst rowCountRef = useRef(rowCount);\n\trowCountRef.current = rowCount;\n\t// Verbatim toggle bodies, lifted from the previous inline rowMarker handlers — the rowMarker\n\t// dispatches `rowmarker.toggleRow` / `rowmarker.toggleAll`, whose commands call these.\n\tconst toggleRowImpl = useCallback((index: number, shiftKey: boolean) => {\n\t\tconst sel = rowMarkerSelectionRef.current ?? emptySheetsSelection;\n\t\tconst anchor = shiftAnchorRef.current;\n\t\tconst next = shiftKey && anchor !== null ? selectRange(sel, anchor, index) : toggleRow(sel, index);\n\t\tshiftAnchorRef.current = index;\n\t\tsetSelection(next);\n\t}, [setSelection]);\n\tconst toggleAllImpl = useCallback(() => {\n\t\tconst sel = rowMarkerSelectionRef.current ?? emptySheetsSelection;\n\t\tconst rc = rowCountRef.current;\n\t\tconst allSelected = rc > 0 && sel.rows.length === rc;\n\t\tshiftAnchorRef.current = null;\n\t\tsetSelection(\n\t\t\tallSelected || rc === 0\n\t\t\t\t? clear(sel)\n\t\t\t\t: { current: { cell: [0, 0] }, rows: RangeSet.fromSingleSelection([0, rc]), columns: RangeSet.empty() },\n\t\t);\n\t}, [setSelection]);\n\tconst rowMarker = useMemo<RowMarker>(() => {\n\t\tconst sel = selection ?? emptySheetsSelection;\n\t\tconst selectedCount = sel.rows.length;\n\t\tconst allSelected = rowCount > 0 && selectedCount === rowCount;\n\t\treturn {\n\t\t\tisSelected: (index) => sel.rows.hasIndex(index),\n\t\t\t// Toggle handlers route through the ONE dispatch pipeline (rowmarker.toggleRow /\n\t\t\t// rowmarker.toggleAll); the command bodies call toggleRowImpl / toggleAllImpl (the\n\t\t\t// verbatim selectRange/toggleRow/clear logic lifted above).\n\t\t\tonToggleRow: (index, shiftKey) => dispatch('rowmarker.toggleRow', undefined, { rowIndex: index, shift: shiftKey }),\n\t\t\tallSelected,\n\t\t\tsomeSelected: selectedCount > 0 && !allSelected,\n\t\t\tonToggleAll: () => dispatch('rowmarker.toggleAll'),\n\t\t};\n\t}, [selection, rowCount, dispatch]);\n\n\t// Imperative getSelectedRows reads the SAME canonical RangeSet the canvas handle uses.\n\tconst getSelectedRows = useCallback(\n\t\t(): Record<string, unknown>[] =>\n\t\t\t(selection?.rows.toArray() ?? []).map((i) => combinedRows[i]).filter(Boolean) as Record<string, unknown>[],\n\t\t[selection, combinedRows],\n\t);\n\n\t// Shared CSV export body — selected rows if any, else the loaded/filtered set. Reused by\n\t// the imperative SheetsHandle.exportCsv() and the toolbar Export button (handleExport).\n\tconst runCsvExport = useCallback(\n\t\t(opts?: { columns?: string[]; filename?: string }) => {\n\t\t\tconst selected = getSelectedRows();\n\t\t\tconst rows = selected.length ? selected : (shell.combinedRows as Record<string, unknown>[]);\n\t\t\tdownloadCsv(rows, opts?.columns ?? shell.columnKeys, opts?.filename);\n\t\t},\n\t\t[getSelectedRows, shell.combinedRows, shell.columnKeys],\n\t);\n\n\tuseImperativeHandle(\n\t\tforwardedRef,\n\t\t(): SheetsHandle => ({\n\t\t\tscrollToRow: (index) => viewportRef.current?.scrollToIndex(index),\n\t\t\tsubmitDrafts: () => s.draft.submitDrafts(),\n\t\t\trefetch: () => s.refetch(),\n\t\t\tgetSelectedRows,\n\t\t\texportCsv: (opts) => runCsvExport(opts),\n\t\t}),\n\t\t[s.draft.submitDrafts, s.refetch, getSelectedRows, runCsvExport],\n\t);\n\n\t// ============== ADD ROW (toolbar) ==============\n\t// Append a draft via the shell API, then scroll it into view. appendRow resolves to the\n\t// new draft's index (or undefined when metadata isn't ready yet — then there's nothing to\n\t// scroll to). Threaded into <SheetsControls onAddRow=…> so the toolbar renders an Add-row button.\n\tconst appendRow = s.draft.appendRow;\n\tconst handleAddRow = useCallback(() => {\n\t\tvoid appendRow().then((index) => {\n\t\t\tif (index !== undefined) viewportRef.current?.scrollToIndex(index);\n\t\t});\n\t}, [appendRow]);\n\n\t// Toolbar Export button — same path as the imperative SheetsHandle.exportCsv().\n\tconst handleExport = useCallback(() => runCsvExport({ filename: `${tableName}.csv` }), [runCsvExport, tableName]);\n\n\t// ============== SCROLL + SELECTION RESET ON SORT/FILTER CHANGE ==============\n\t// When sort or filter changes the infinite query re-keys and the row set is a different,\n\t// index-based window — so any held selection/active-cell now points at the wrong rows.\n\t// Per the locked decision we CLEAR selection + active cell and scroll back to the top.\n\t// Keyed precisely on the same sort+filter inputs the query derives its where/orderBy from,\n\t// so it fires only on a real sort/filter transition (not on data refetch or draft edits).\n\tconst optionsKey = useMemo(\n\t\t() => JSON.stringify({ id: shell.sorting.id, desc: shell.sorting.desc, filter: shell.filterTree }),\n\t\t[shell.sorting.id, shell.sorting.desc, shell.filterTree],\n\t);\n\tconst didMountResetRef = useRef(false);\n\tuseEffect(() => {\n\t\tif (!didMountResetRef.current) {\n\t\t\tdidMountResetRef.current = true;\n\t\t\treturn;\n\t\t}\n\t\tsetSelection(emptySheetsSelection);\n\t\tviewportRef.current?.scrollToIndex(0);\n\t}, [optionsKey, setSelection]);\n\n\t// ============== NATIVE OVERLAY EDITING (Phase 4, additive) ==============\n\t// Open/close state for the native React-portal overlay editor. The host measures\n\t// the activated cell's rect (only it knows the cell DOM node) and calls openEditor.\n\tconst overlay = useOverlayController();\n\tconst overlayOpen = overlay.open;\n\tconst overlayClose = overlay.close;\n\tconst overlayReanchor = overlay.reanchor;\n\n\t// Inject the shell's native content resolver into the cell host (Phase 3): the\n\t// host renders the consumer component when registered, else the kind→view map.\n\t// openEditor is threaded so the cell wrapper can activate the overlay editor;\n\t// submitDraftRow is threaded so the draft-action cell's Button can submit (Stage 4).\n\tconst getSheetsCellContent = shell.getSheetsCellContent;\n\tconst submitDraftRow = shell.submitDraftRow;\n\tconst commitCellValue = shell.commitCellValue;\n\tconst getEditorComponent = shell.cellRegistry.getEditorComponent;\n\t// Undo/redo handlers (stable from useUndoRedo) — wired into the edit.undo / edit.redo commands.\n\tconst undo = shell.undo;\n\tconst redo = shell.redo;\n\t// Batched commit + observational emit — threaded into the command context (commitCells/emit).\n\tconst commitCells = shell.commitCells;\n\tconst emit = shell.emit;\n\n\t// REF-LATCH (perf): `openEditor` is a dep of `renderCell`, which the cell host\n\t// memo-gates on (prev.openEditor === next.openEditor). Closing over `combinedRows` /\n\t// `commitCellValue` / the resolver directly would give `openEditor` a NEW identity on\n\t// every data/draft change, busting the per-cell memo for the ENTIRE visible window.\n\t// Instead we latch each churning value into a ref kept current every render and read\n\t// `*Ref.current` inside the callback, so `openEditor` stays referentially STABLE while\n\t// still seeing the latest values. (`overlayOpen` is already stable — useCallback([]) —\n\t// so it stays a direct, guaranteed-stable dep.)\n\tconst getSheetsCellContentRef = useRef(getSheetsCellContent);\n\tgetSheetsCellContentRef.current = getSheetsCellContent;\n\tconst getEditorComponentRef = useRef(getEditorComponent);\n\tgetEditorComponentRef.current = getEditorComponent;\n\tconst combinedRowsRef = useRef(combinedRows);\n\tcombinedRowsRef.current = combinedRows;\n\tconst commitCellValueRef = useRef(commitCellValue);\n\tcommitCellValueRef.current = commitCellValue;\n\tconst commitCellsRef = useRef(commitCells);\n\tcommitCellsRef.current = commitCells;\n\t// Read the LATEST selection inside the keydown handler so a queued move can't resurrect a\n\t// stale active cell right after a sort/filter clear (the optionsKey effect resets selection).\n\tconst selectionRef = useRef(selection);\n\tselectionRef.current = selection;\n\n\t// EDIT-INTENT BRANCH (Stage 2): activation routes through the SINGLE edit-intent\n\t// resolver off the resolved `typeKey` — NOT the broken `cell.meta?.cellType ?? 'text'`\n\t// lookup that mis-routed every non-text cell to TextEditor. The cell-host fires this\n\t// on double-click / Enter / F2 (it already no-ops readonly cells); here we branch\n\t// BEFORE opening any overlay:\n\t// • inline-toggle (booleans): commit `!currentBool` in place, no overlay.\n\t// • overlay: open the portal (the editorNode block resolves intent.editor).\n\t// • none (readonly / non-editable): do nothing.\n\tconst openEditorImpl = useCallback<OpenEditor>(\n\t\t(rowIndex, colKey, anchorRect, initialText) => {\n\t\t\tconst resolution = getSheetsCellContentRef.current(rowIndex, colKey);\n\t\t\tconst intent = resolveEditIntent(\n\t\t\t\tresolution.typeKey,\n\t\t\t\t{ readonly: resolution.cell.readonly },\n\t\t\t\tgetEditorComponentRef.current,\n\t\t\t);\n\t\t\tif (intent.mode === 'none') return;\n\t\t\tif (intent.mode === 'inline-toggle') {\n\t\t\t\tconst current = (combinedRowsRef.current[rowIndex] as Record<string, unknown> | undefined)?.[colKey];\n\t\t\t\tcommitCellValueRef.current(rowIndex, colKey, !coerceCellBoolean(current));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// inline-edit (simple text/number): edit IN PLACE — same active-cell controller (so nav/\n\t\t\t// clipboard suppression + scroll commit-on-unmount are shared) but the cell host renders\n\t\t\t// the input and the portal is skipped (editorNode is null for a non-overlay intent).\n\t\t\tif (intent.mode === 'inline-edit') {\n\t\t\t\toverlayOpen({ rowIndex, colKey, anchorRect, initialText, mode: 'inline' });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\toverlayOpen({ rowIndex, colKey, anchorRect, initialText, mode: 'overlay' });\n\t\t},\n\t\t[overlayOpen],\n\t);\n\t// The dblclick entrypoint threaded into the cell host: route through the ONE pipeline as\n\t// `editor.open`; the command body calls ctx.openEditorAt → openEditorImpl. STABLE (closes\n\t// over the stable `dispatch`), so it never busts the per-cell memo.\n\tconst openEditor = useCallback<OpenEditor>(\n\t\t(rowIndex, colKey, anchorRect, initialText) =>\n\t\t\tdispatch('editor.open', undefined, { rowIndex, colKey, anchorRect, initialText }),\n\t\t[dispatch],\n\t);\n\t// ============== RANGE-AWARE BULK EDIT (Stage B) ==============\n\t// The editor's onCommit routes through here. When a MULTI-CELL range is selected AND the\n\t// active (edited) cell sits inside it, the committed value FANS OUT across the whole range\n\t// as ONE undo-aware batch (single optimistic patch + coalesced per-row mutations + one undo\n\t// entry — commitCells skips readonly/UUID internally and resolveServerPatch coerces the\n\t// string value PER target column). A single-cell selection (or none, or an active cell\n\t// outside the range) keeps the existing single-cell commit byte-for-byte. The LATEST range\n\t// is read off `selectionRef` so a queued sort/filter clear wins (same latch the keymap uses).\n\tconst columnKeysRef = useRef(shell.columnKeys);\n\tcolumnKeysRef.current = shell.columnKeys;\n\tconst commitBulkOrSingle = useCallback(\n\t\t(rowIndex: number, colKey: string, value: unknown) => {\n\t\t\tconst range = selectionRef.current?.current?.range;\n\t\t\tconst keys = columnKeysRef.current;\n\t\t\tconst activeCol = keys.indexOf(colKey);\n\t\t\tconst multiCell = !!range && range.width * range.height > 1;\n\t\t\tconst inside =\n\t\t\t\t!!range &&\n\t\t\t\tactiveCol >= 0 &&\n\t\t\t\tactiveCol >= range.x &&\n\t\t\t\tactiveCol < range.x + range.width &&\n\t\t\t\trowIndex >= range.y &&\n\t\t\t\trowIndex < range.y + range.height;\n\t\t\tif (multiCell && inside && range) {\n\t\t\t\tconst writes = bulkEditWrites(range, value, keys);\n\t\t\t\tif (writes.length) void commitCellsRef.current(writes);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcommitCellValueRef.current(rowIndex, colKey, value);\n\t\t},\n\t\t[],\n\t);\n\t// ============== CELL-RANGE SELECTION (Stage B) ==============\n\t// `anchorRef` holds the FIXED corner a contiguous range extends FROM. A plain activate\n\t// (click / non-shift Arrow) resets it to the new active cell; a shift extend keeps it put.\n\t// It is the caller-owned anchor `extendRangeToCell` expects (the model stays a pure value).\n\tconst anchorRef = useRef<[number, number] | null>(null);\n\tconst setSelectionRange = s.selection.setGridSelection;\n\t// Extend the contiguous range from the latched anchor to `[col, row]`. Reads the LATEST\n\t// selection (post-sort-clear safe) and falls back to the target as anchor when none latched.\n\tconst extendToCell = useCallback(\n\t\t(col: number, row: number) => {\n\t\t\tconst sel = selectionRef.current ?? emptySheetsSelection;\n\t\t\tconst anchor = anchorRef.current ?? sel.current?.cell ?? [col, row];\n\t\t\tanchorRef.current = anchor;\n\t\t\tsetSelectionRange(extendRangeToCell(sel, col, row, anchor[0], anchor[1]));\n\t\t},\n\t\t[setSelectionRange],\n\t);\n\t// Click-to-activate: park the active cell on the clicked cell. Stable (the shell's\n\t// setActiveCell is a stable useCallback), so it never busts the per-cell memo. Shift-click\n\t// EXTENDS the range from the latched anchor; a plain click activates AND resets the anchor.\n\tconst setActiveCell = s.selection.setActiveCell;\n\tconst handleActivateCell = useCallback(\n\t\t(col: number, row: number, shiftKey?: boolean) =>\n\t\t\tdispatch(shiftKey ? 'cell.extendToClicked' : 'cell.activate', undefined, { col, row }),\n\t\t[dispatch],\n\t);\n\n\t// ============== RIGHT-CLICK CONTEXT MENU (Stage B) ==============\n\t// A menu is just another EVENT SOURCE → dispatch. State is the pointer anchor (null = closed),\n\t// rendered ONCE at the grid level. `handleContextMenu` is STABLE (reads selectionRef + the stable\n\t// dispatch), so it never busts the per-cell memo. When the right-clicked cell sits OUTSIDE the\n\t// current active cell / selection range, we activate it first so the menu acts on the clicked cell.\n\tconst [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);\n\tconst handleContextMenu = useCallback(\n\t\t(col: number, row: number, clientX: number, clientY: number) => {\n\t\t\tconst sel = selectionRef.current;\n\t\t\tconst active = sel?.current?.cell;\n\t\t\tconst range = sel?.current?.range;\n\t\t\tconst inRange =\n\t\t\t\t!!range && col >= range.x && col < range.x + range.width && row >= range.y && row < range.y + range.height;\n\t\t\tconst isActive = !!active && active[0] === col && active[1] === row;\n\t\t\tif (!isActive && !inRange) dispatch('cell.activate', undefined, { col, row });\n\t\t\tsetContextMenu({ clientX, clientY });\n\t\t},\n\t\t[dispatch],\n\t);\n\tconst closeContextMenu = useCallback(() => setContextMenu(null), []);\n\t// Enabled-state probe for the menu items: run the resolved command's `canRun` against the latched\n\t// context (same gate the dispatch core applies). A missing canRun means \"always runnable\".\n\tconst isCommandEnabled = useCallback(\n\t\t(commandId: string) => {\n\t\t\tconst cmd = registry.get(commandId);\n\t\t\treturn cmd ? (cmd.canRun ? cmd.canRun(ctxRef.current, undefined) : true) : false;\n\t\t},\n\t\t[registry],\n\t);\n\n\t// ============== INLINE (IN-CELL) EDIT WIRING ==============\n\t// Simple text/number types edit in place via the cell host's <input> instead of the portal.\n\t// They ride the SAME active-editor controller (`overlay`) tagged `mode: 'inline'`, so the only\n\t// extra wiring here is (a) telling the editing cell to render the input and (b) commit/cancel\n\t// routed through the existing value-commit pipeline. The inline KEY is the editing cell identity,\n\t// NULL during overlay editing — so `renderCell` stays referentially stable across overlay\n\t// scroll-reanchors (which mutate `overlay.active.anchorRect` but never this key).\n\tconst inlineActive = overlay.active?.mode === 'inline' ? overlay.active : null;\n\tconst inlineKey = inlineActive ? `${inlineActive.rowIndex}:${inlineActive.colKey}` : null;\n\tconst inlineInitialText = inlineActive?.initialText;\n\tconst onInlineCommit = useCallback(\n\t\t(rowIndex: number, colKey: string, value: unknown) => {\n\t\t\tcommitBulkOrSingle(rowIndex, colKey, value);\n\t\t\toverlayClose();\n\t\t},\n\t\t[commitBulkOrSingle, overlayClose],\n\t);\n\n\tconst renderCell = useCallback<RenderCell>(\n\t\t(c, ctx) => {\n\t\t\tconst editingThisCell = inlineKey != null && inlineKey === `${c.row.index}:${c.column.id}`;\n\t\t\treturn (\n\t\t\t\t<SheetsCellHost\n\t\t\t\t\tcell={c}\n\t\t\t\t\tctx={ctx}\n\t\t\t\t\tgetSheetsCellContent={getSheetsCellContent}\n\t\t\t\t\topenEditor={openEditor}\n\t\t\t\t\tisEditing={editingThisCell}\n\t\t\t\t\tinlineInitialText={editingThisCell ? inlineInitialText : undefined}\n\t\t\t\t\tonInlineCommit={onInlineCommit}\n\t\t\t\t\tonInlineCancel={overlayClose}\n\t\t\t\t\tonActivateCell={handleActivateCell}\n\t\t\t\t\tonContextMenu={handleContextMenu}\n\t\t\t\t\tonSubmitDraftRow={submitDraftRow}\n\t\t\t\t/>\n\t\t\t);\n\t\t},\n\t\t[inlineKey, inlineInitialText, onInlineCommit, overlayClose, getSheetsCellContent, openEditor, handleActivateCell, handleContextMenu, submitDraftRow],\n\t);\n\n\t// ============== SPREADSHEET KEYBOARD NAV (grid root owns keys) ==============\n\t// The grid root (role=grid, tabIndex=0, aria-activedescendant) owns spreadsheet keys.\n\t// Arrows move the active cell (clamped); Enter/F2 open the overlay at the active cell.\n\t// IGNORE keydowns while an overlay editor is open so nav doesn't fight editing. The\n\t// active cell + col/row counts are read LATEST (refs) so a post-sort/filter clear wins.\n\tconst moveActiveCell = s.selection.moveActive;\n\tconst isOverlayOpen = overlay.isOpen;\n\n\t// Shared open-at-active-cell path (Enter / F2 / type-to-edit): resolve the active cell's\n\t// DOM node by its stable id, null-guarding the row (infinite-mode proxy rows can be null at\n\t// unloaded indices) + the colKey, then open the overlay. `initialText` seeds type-to-edit\n\t// (OVERWRITE). Returns true when an overlay was opened.\n\tconst openEditorAtActiveCell = useCallback(\n\t\t(initialText?: string): boolean => {\n\t\t\tconst cell = selectionRef.current?.current?.cell;\n\t\t\tif (!cell) return false;\n\t\t\tconst [col, row] = cell;\n\t\t\tconst rowData = combinedRowsRef.current[row];\n\t\t\tif (!rowData) return false;\n\t\t\tconst colKey = columns[col]?.key;\n\t\t\tif (!colKey) return false;\n\t\t\tconst node = document.getElementById(`sheets-cell-${row}-${col}`);\n\t\t\tif (!node) return false;\n\t\t\t// Open directly via the impl (NOT the dispatching `openEditor`) — this fn is itself the\n\t\t\t// body of the editor.openActive / editor.typeToEdit commands' canRun, so going through\n\t\t\t// dispatch again would double-route. Matches the original (which called openEditor directly).\n\t\t\topenEditorImpl(row, colKey, node.getBoundingClientRect(), initialText);\n\t\t\treturn true;\n\t\t},\n\t\t[columns, openEditorImpl],\n\t);\n\n\t// Every grid key now resolves to a NAMED command through the ONE dispatch pipeline. The\n\t// keymap (first-match-wins) covers undo/redo/select-all/arrows/extend/abs-nav/open; an\n\t// UNRESOLVED key that is a single printable char (no ctrl/meta/alt) falls to the\n\t// `editor.typeToEdit` sentinel (also through dispatch, so it is interceptable). Any other\n\t// unresolved key is left untouched — NO dispatch, NO preventDefault — so it reaches the\n\t// browser. preventDefault lives in the dispatch CORE, gated on a resolved+runnable command.\n\tconst handleGridKeyDown = useCallback(\n\t\t(e: React.KeyboardEvent) => {\n\t\t\t// Don't intercept while editing — the overlay editor owns its own keys.\n\t\t\tif (isOverlayOpen) return;\n\t\t\tconst cmd = resolveKeyCommand(e.nativeEvent, keymapRef.current);\n\t\t\tif (cmd) {\n\t\t\t\tdispatch(cmd, e.nativeEvent, buildKeyPayload(e));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Unresolved: only the printable-key sentinel routes through dispatch; everything\n\t\t\t// else falls through to the browser with no preventDefault.\n\t\t\tif (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {\n\t\t\t\tdispatch('editor.typeToEdit', e.nativeEvent, { char: e.key });\n\t\t\t}\n\t\t},\n\t\t[isOverlayOpen, dispatch],\n\t);\n\n\t// ============== NATIVE CLIPBOARD (Stage B) ==============\n\t// The grid root (role=grid, tabIndex=0) receives the browser's native copy/cut/paste events\n\t// when focused. We do NOT bind Ctrl/Cmd+C/X/V in the keymap — pressing them fires these native\n\t// events directly, so binding the keys too would double-handle. Each handler is SKIPPED while an\n\t// overlay editor is open (the editor owns its own clipboard) and routes through the ONE dispatch\n\t// pipeline as `clipboard.copy`/`cut`/`paste`, threading the native ClipboardData as the payload.\n\t// preventDefault happens in the dispatch core (so the browser does not also copy/paste).\n\tconst handleCopy = useCallback(\n\t\t(e: React.ClipboardEvent) => {\n\t\t\tif (isOverlayOpen) return;\n\t\t\tdispatch('clipboard.copy', e.nativeEvent, { clipboard: (e.nativeEvent as ClipboardEvent).clipboardData });\n\t\t},\n\t\t[isOverlayOpen, dispatch],\n\t);\n\tconst handleCut = useCallback(\n\t\t(e: React.ClipboardEvent) => {\n\t\t\tif (isOverlayOpen) return;\n\t\t\tdispatch('clipboard.cut', e.nativeEvent, { clipboard: (e.nativeEvent as ClipboardEvent).clipboardData });\n\t\t},\n\t\t[isOverlayOpen, dispatch],\n\t);\n\tconst handlePaste = useCallback(\n\t\t(e: React.ClipboardEvent) => {\n\t\t\tif (isOverlayOpen) return;\n\t\t\tdispatch('clipboard.paste', e.nativeEvent, { clipboard: (e.nativeEvent as ClipboardEvent).clipboardData });\n\t\t},\n\t\t[isOverlayOpen, dispatch],\n\t);\n\n\t// FOLLOW-CELL-ON-SCROLL (Stage B): on viewport scroll, re-measure the active cell's DOM\n\t// node and re-anchor the overlay to it (cheap, passive — DOM read + a position state set)\n\t// instead of closing. If the node is GONE (the cell scrolled out of the virtual window and\n\t// unmounted), we COMMIT-AND-CLOSE rather than silently discard: blur the focused editor\n\t// element so a commit-on-blur editor (text/number) commits its in-progress value, then\n\t// close. (Backgrounded-tab rAF throttling is irrelevant — this runs straight off scroll.)\n\tconst activeRef = useRef(overlay.active);\n\tactiveRef.current = overlay.active;\n\tconst columnsRef = useRef(columns);\n\tcolumnsRef.current = columns;\n\tconst handleOverlayScroll = useCallback(() => {\n\t\tconst a = activeRef.current;\n\t\tif (!a) return;\n\t\t// The cell DOM id is `sheets-cell-${rowIndex}-${columnIndex}` — map the stored colKey\n\t\t// back to its rendered column index (same ordering the cell host + activedescendant use).\n\t\tconst colIndex = columnsRef.current.findIndex((c) => c.key === a.colKey);\n\t\tconst node = colIndex >= 0 ? document.getElementById(`sheets-cell-${a.rowIndex}-${colIndex}`) : null;\n\t\tif (node) {\n\t\t\t// Inline edits live INSIDE the cell, so they ride the virtualized row natively — no\n\t\t\t// reposition needed (and reanchoring would churn state every scroll frame). Only the\n\t\t\t// portal overlay re-anchors to the cell on scroll.\n\t\t\tif (a.mode !== 'inline') overlayReanchor(node.getBoundingClientRect());\n\t\t\treturn;\n\t\t}\n\t\t// Cell unmounted (scrolled out of the virtual window) — commit any in-progress value\n\t\t// (commit-on-blur editors, incl. the inline input) then close.\n\t\tconst focused = document.activeElement;\n\t\tif (focused instanceof HTMLElement) focused.blur();\n\t\toverlayClose();\n\t}, [overlayReanchor, overlayClose]);\n\n\t// Resolve the active editor + its EditorProps. Computed in render (cheap, only when\n\t// an overlay is open) — the cell resolution, value, native editor and flip geometry\n\t// all derive from overlay.active, so no effect/state mirror is needed.\n\tconst active = overlay.active;\n\tconst editorNode = (() => {\n\t\tif (!active) return null;\n\t\tconst resolution = getSheetsCellContent(active.rowIndex, active.colKey);\n\t\t// Resolve the editor through the SAME edit-intent resolver the activation branch\n\t\t// used (typeKey-driven, consumer-override aware). Only `overlay` intents ever open\n\t\t// here (openEditor short-circuits inline-toggle/none), but resolving again keeps a\n\t\t// single source of truth — and guards against a non-overlay intent slipping through.\n\t\tconst intent = resolveEditIntent(resolution.typeKey, { readonly: resolution.cell.readonly }, getEditorComponent);\n\t\tif (intent.mode !== 'overlay') return null;\n\t\tconst Editor = intent.editor;\n\t\tconst rowValue = (combinedRows[active.rowIndex] as Record<string, unknown> | undefined)?.[active.colKey];\n\t\tconst geom = computeOverlayGeometry(\n\t\t\ttypeof window !== 'undefined' ? window.innerHeight : 800,\n\t\t\tactive.anchorRect.top,\n\t\t\tactive.anchorRect.height,\n\t\t\tOVERLAY_MARGIN_PX,\n\t\t\tOVERLAY_MIN_BELOW_PX,\n\t\t);\n\t\treturn {\n\t\t\tpresetClass: Editor.overlayPresetClass,\n\t\t\t// Commit-on-click-away (Stage B): editors that own an onBlur→onCommit advertise it\n\t\t\t// so the OverlayManager dismisses by blurring (commit) instead of cancelling.\n\t\t\tdismissMode: Editor.commitsOnBlur ? ('commit' as const) : ('cancel' as const),\n\t\t\telement: (\n\t\t\t\t<Editor\n\t\t\t\t\tvalue={rowValue}\n\t\t\t\t\tcell={resolution.cell}\n\t\t\t\t\tcolKey={active.colKey}\n\t\t\t\t\trowId={getRowId(combinedRows[active.rowIndex], active.rowIndex)}\n\t\t\t\t\trowIndex={active.rowIndex}\n\t\t\t\t\ttableName={props.tableName}\n\t\t\t\t\tfieldMeta={resolution.fieldMeta}\n\t\t\t\t\trelationInfo={resolution.relationInfo}\n\t\t\t\t\tinitialText={active.initialText}\n\t\t\t\t\tonCommit={(next) => {\n\t\t\t\t\t\tcommitBulkOrSingle(active.rowIndex, active.colKey, next);\n\t\t\t\t\t\toverlayClose();\n\t\t\t\t\t}}\n\t\t\t\t\tonCommitPatch={(patch) => {\n\t\t\t\t\t\tshell.commitCellPatch(active.rowIndex, patch);\n\t\t\t\t\t\toverlayClose();\n\t\t\t\t\t}}\n\t\t\t\t\tonSubmitDraftRow={shell.submitDraftRow}\n\t\t\t\t\tonInvalidateData={shell.invalidateData}\n\t\t\t\t\tonCancel={overlayClose}\n\t\t\t\t\toverlay={{ maxHeight: geom.maxHeight, flipped: geom.shouldFlip }}\n\t\t\t\t/>\n\t\t\t),\n\t\t};\n\t})();\n\n\t// INFINITE SCROLL: the virtualizer COUNT is left to its default (`rows.length`) — in\n\t// infinite mode `combinedRows` IS the full-length proxy (`serverRowCount + drafts`, null-backing\n\t// unloaded indices), so `rows.length` already spans every lazy row AND includes drafts; forcing\n\t// `count = totalCount` would drop the appended draft rows. We only wire the prefetch handler:\n\t// the viewport's overscan-inclusive {startIndex,endIndex} window IS the native range the shell\n\t// prefetches against (handleVisibleRegionChanged no-ops when paginated + clamps to the server\n\t// row count, but we still attach only in infinite mode, matching the prior paginated omission).\n\tconst onVisibleRegionChanged = shell.onVisibleRegionChanged;\n\tconst onVisibleRangeChange = useCallback(\n\t\t(range: VisibleRange) => {\n\t\t\tonVisibleRegionChanged(range);\n\t\t},\n\t\t[onVisibleRegionChanged],\n\t);\n\n\t// Sort caret state mirror (the shell owns it via useGridState). The shell's onHeaderClicked is\n\t// the sort toggle keyed by colIndex (the draft-action column is excluded as non-sortable); the\n\t// DOM header speaks colKey, so map back to the colIndex it expects via columnKeys.\n\tconst sorting = shell.sorting;\n\tconst onHeaderClicked = shell.onHeaderClicked;\n\tconst columnKeys = shell.columnKeys;\n\t// Header click routes through the ONE pipeline as `header.sortToggle`; the command body calls\n\t// ctx.sortToggle(colKey), which maps the colKey back to the colIndex onHeaderClicked expects.\n\tconst onHeaderClick = useCallback((colKey: string) => dispatch('header.sortToggle', undefined, { colKey }), [dispatch]);\n\n\t// Fill-handle drag release routes through the ONE pipeline as `fill.drag`; the command extends\n\t// the source band toward `target`, replicates the source values, and widens the selection.\n\tconst handleFillDrag = useCallback(\n\t\t(sourceRange: SelectionRect, target: [number, number]) => dispatch('fill.drag', undefined, { from: sourceRange, to: target }),\n\t\t[dispatch],\n\t);\n\n\t// ============== ASSEMBLE + LATCH THE GRID COMMAND CONTEXT ==============\n\t// ONE object the commands run against: live GETTERS read the existing refs/derived render\n\t// values; methods are the EXISTING stable callbacks wrapped VERBATIM (no dispatcher is\n\t// reinvented). Rebuilt each render (cheap) and REPOINTED into `ctxRef` so `dispatch`\n\t// (stable, reads ctxRef.current) always sees the latest values — mirrors the openEditor\n\t// ref-latch. The pointer callbacks threaded into renderCell close over `dispatch`, not this,\n\t// so the per-cell memo is unaffected.\n\tctxRef.current = {\n\t\tget rowCount() {\n\t\t\treturn combinedRowsRef.current.length;\n\t\t},\n\t\tget colCount() {\n\t\t\treturn columnsRef.current.length;\n\t\t},\n\t\tget activeCell() {\n\t\t\treturn selectionRef.current?.current?.cell;\n\t\t},\n\t\tget selection() {\n\t\t\treturn selectionRef.current;\n\t\t},\n\t\tget combinedRows() {\n\t\t\treturn combinedRowsRef.current;\n\t\t},\n\t\tget columnKeys() {\n\t\t\treturn columnsRef.current.map((c) => c.key);\n\t\t},\n\t\tgetAnchor: () => anchorRef.current,\n\t\tsetAnchor: (anchor) => {\n\t\t\tanchorRef.current = anchor;\n\t\t},\n\t\tsetActiveCell,\n\t\tmoveActiveCell,\n\t\textendToCell,\n\t\tsetSelection: setSelectionRange,\n\t\tcommitCells,\n\t\topenEditorAtActive: openEditorAtActiveCell,\n\t\topenEditorAt: openEditorImpl,\n\t\tundo,\n\t\tredo,\n\t\tscrollToCell: (col, row) => viewportRef.current?.scrollToCell(col, row),\n\t\tsortToggle: (colKey) => onHeaderClicked(columnKeys.indexOf(colKey)),\n\t\ttoggleRow: toggleRowImpl,\n\t\ttoggleAll: toggleAllImpl,\n\t\tgetCellsInRange: (rect: SelectionRect): CellMatrix => {\n\t\t\tconst r = extractCellsInRange(rect, combinedRowsRef.current, columnsRef.current.map((c) => c.key));\n\t\t\treturn { cols: r.cols, rows: r.rows, values: r.values };\n\t\t},\n\t\ttoTSV: (values) => serializeTSV(values),\n\t\temit,\n\t} satisfies GridCommandContext;\n\n\t// ============== LOAD STATES ==============\n\t// Surface real error/empty/loading states instead of a blank grid (moved here from\n\t// the removed canvas branch). The full-screen error is for INITIAL-load failure only\n\t// (no server rows AND no drafts); background-refetch errors keep the populated grid\n\t// mounted and surface via the `load:error` onEvent emission instead.\n\tif (s.dataError && shell.combinedRows.length === 0) {\n\t\tconst retry = () => s.refetch();\n\t\tif (slots?.error) {\n\t\t\treturn <>{slots.error({ error: s.dataError, retry })}</>;\n\t\t}\n\t\treturn <SheetsErrorState error={s.dataError} onRetry={retry} />;\n\t}\n\n\t// Initial load only; same-scope refetches retain their current query data.\n\tif (s.isInitialLoading) {\n\t\tif (slots?.loading) return <>{slots.loading}</>;\n\t\treturn <SheetsLoadingState />;\n\t}\n\n\t// Loaded successfully but no server rows and nothing drafted yet (and no active filter).\n\tif (s.isEmpty) {\n\t\tif (slots?.empty) {\n\t\t\treturn <>{typeof slots.empty === 'function' ? slots.empty({ tableName }) : slots.empty}</>;\n\t\t}\n\t\treturn (\n\t\t\t<SheetsEmptyState\n\t\t\t\ttableName={tableName}\n\t\t\t\treadOnlyReason={shell.readOnlyReason}\n\t\t\t\tonAddRow={shell.canCreate ? () => {\n\t\t\t\t\tvoid s.draft.appendRow();\n\t\t\t\t} : undefined}\n\t\t\t/>\n\t\t);\n\t}\n\n\t// Filtered-empty: the server returned 0 rows while a filter is active (so `isEmpty` above is\n\t// false — it requires no filter). Without this the body renders blank under the header and looks\n\t// broken; instead we keep the toolbar/filter bar mounted and overlay a \"No matching rows\" panel\n\t// with a one-click clear back to the unfiltered set.\n\tconst activeFilterCount = shell.filterTree ? countConditions(shell.filterTree) : 0;\n\tconst isFilteredEmpty = shell.serverRowCount === 0 && shell.draftRowCount === 0 && activeFilterCount > 0;\n\n\treturn (\n\t\t<SheetsErrorBoundary onError={config.onError}>\n\t\t\t{/* Controls — consumer toolbar slot replaces the default <SheetsControls> block. */}\n\t\t\t<div data-part-id='sheets-controls-container'>\n\t\t\t\t{slots?.toolbar ? (\n\t\t\t\t\t<>{typeof slots.toolbar === 'function' ? slots.toolbar({ tableName }) : slots.toolbar}</>\n\t\t\t\t) : (\n\t\t\t\t\t<SheetsControls\n\t\t\t\t\t\tfilterTree={shell.filterTree}\n\t\t\t\t\t\tsetFilterTree={shell.setFilterTree}\n\t\t\t\t\t\tfiltersOpen={shell.filtersOpen}\n\t\t\t\t\t\tsetFiltersOpen={shell.setFiltersOpen}\n\t\t\t\t\t\tclearAllFilters={shell.clearAllFilters}\n\t\t\t\t\t\tapplyFilters={shell.applyFilters}\n\t\t\t\t\t\tcolumnKeys={shell.columnKeys}\n\t\t\t\t\t\tfieldTypeMap={shell.fieldTypeMap}\n\t\t\t\t\t\tshowSelection={showSelection}\n\t\t\t\t\t\tgridSelection={s.selection.gridSelection ?? null}\n\t\t\t\t\t\tsetGridSelection={shell.setGridSelectionForControls}\n\t\t\t\t\t\tdeleteSelected={s.draft.deleteSelected}\n\t\t\t\t\t\tonAddRow={shell.canCreate ? handleAddRow : undefined}\n\t\t\t\t\t\tcanDelete={shell.canDelete}\n\t\t\t\t\t\treadOnlyReason={shell.readOnlyReason}\n\t\t\t\t\t\tonExport={handleExport}\n\t\t\t\t\t/>\n\t\t\t\t)}\n\t\t\t</div>\n\n\t\t\t<div\n\t\t\t\tdata-part-id='sheets-container'\n\t\t\t\trole='region'\n\t\t\t\taria-label={`${tableName} table`}\n\t\t\t\tclassName={cn('bg-background relative isolate h-full min-h-0 flex-1 overflow-hidden rounded-lg border', className)}\n\t\t\t>\n\t\t\t\t<GridViewport\n\t\t\t\t\ttable={table}\n\t\t\t\t\trenderCell={renderCell}\n\t\t\t\t\thandleRef={viewportRef}\n\t\t\t\t\tonScroll={handleOverlayScroll}\n\t\t\t\t\tsorting={sorting}\n\t\t\t\t\tonHeaderClick={onHeaderClick}\n\t\t\t\t\tonResize={resizeColumn}\n\t\t\t\t\tonVisibleRangeChange={infiniteScroll ? onVisibleRangeChange : undefined}\n\t\t\t\t\trowMarker={showSelection ? rowMarker : undefined}\n\t\t\t\t\tactiveCell={activeCell}\n\t\t\t\t\tactiveRange={s.selection.gridSelection?.current?.range}\n\t\t\t\t\tonGridKeyDown={handleGridKeyDown}\n\t\t\t\t\tonCopy={handleCopy}\n\t\t\t\t\tonCut={handleCut}\n\t\t\t\t\tonPaste={handlePaste}\n\t\t\t\t\tonFillDrag={handleFillDrag}\n\t\t\t\t\tactiveDescendantId={activeCell ? `sheets-cell-${activeCell[1]}-${activeCell[0]}` : undefined}\n\t\t\t\t/>\n\n\t\t\t\t{/* Filtered-empty panel — overlays the empty body while the filter bar stays visible above. */}\n\t\t\t\t{isFilteredEmpty && (\n\t\t\t\t\t<div className='bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-center'>\n\t\t\t\t\t\t<RiSearchEyeLine className='text-muted-foreground h-8 w-8' />\n\t\t\t\t\t\t<div className='space-y-1'>\n\t\t\t\t\t\t\t<p className='text-foreground text-sm font-medium'>No matching rows</p>\n\t\t\t\t\t\t\t<p className='text-muted-foreground max-w-md text-sm'>\n\t\t\t\t\t\t\t\tNo rows match the active {activeFilterCount === 1 ? 'filter' : 'filters'}.\n\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<Button variant='outline' size='sm' onClick={shell.clearAllFilters}>\n\t\t\t\t\t\t\t<RiFilterOffLine className='h-4 w-4' />\n\t\t\t\t\t\t\t<span className='ms-1'>Clear filters</span>\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</div>\n\t\t\t\t)}\n\n\t\t\t\t{/* Floating status indicator — surfaces save/delete/submit feedback from the FeedbackProvider. */}\n\t\t\t\t<div className='pointer-events-none absolute bottom-4 left-1/2 z-10 -translate-x-1/2'>\n\t\t\t\t\t<FloatingStatus />\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t{/* Pagination — hidden in infinite scroll mode (canvas parity). */}\n\t\t\t{showPagination && !infiniteScroll && s.pagination.pageCount > 1 && (\n\t\t\t\t<SheetsPagination\n\t\t\t\t\tpageIndex={s.pagination.pageIndex}\n\t\t\t\t\tpageSize={pageSize}\n\t\t\t\t\ttotalCount={shell.totalCount}\n\t\t\t\t\ttotalPages={s.pagination.pageCount}\n\t\t\t\t\tsetPageIndex={s.pagination.setPageIndex}\n\t\t\t\t/>\n\t\t\t)}\n\n\t\t\t<OverlayManager\n\t\t\t\topen={overlay.isOpen && editorNode != null}\n\t\t\t\tanchorRect={active?.anchorRect ?? null}\n\t\t\t\tpresetClass={editorNode?.presetClass}\n\t\t\t\tdismissMode={editorNode?.dismissMode}\n\t\t\t\tonCancel={overlayClose}\n\t\t\t>\n\t\t\t\t{editorNode?.element}\n\t\t\t</OverlayManager>\n\n\t\t\t{/* Right-click context menu — items dispatch through the SAME pipeline as keys/clicks\n\t\t\t (clipboard.* with no native event take the navigator.clipboard fallback). Rendered once. */}\n\t\t\t<SheetsContextMenu\n\t\t\t\tstate={contextMenu}\n\t\t\t\tonClose={closeContextMenu}\n\t\t\t\tonAction={(commandId) => dispatch(commandId)}\n\t\t\t\tisEnabled={isCommandEnabled}\n\t\t\t\tonAddRow={handleAddRow}\n\t\t\t\tonDeleteRows={s.draft.deleteSelected}\n\t\t\t\tselectedRowCount={selection?.rows.length ?? 0}\n\t\t\t\tcanAddRows={shell.canCreate}\n\t\t\t\tcanDeleteRows={shell.canDelete}\n\t\t\t/>\n\t\t</SheetsErrorBoundary>\n\t);\n}\n\n// Public props alias — generic over the consumer's row type (default SheetsRow keeps\n// existing untyped callers compiling). Carries DataGridProps' TRow through.\nexport type SheetsProps<TRow extends SheetsRow = SheetsRow> = DataGridProps<TRow>;\n","import { memo, useCallback, useEffect, useMemo, useState } from \"react\";\nimport {\n RiAddLine,\n RiCloseCircleLine,\n RiDeleteBin6Line,\n RiDownloadLine,\n RiFilter3Line,\n RiSearch2Line,\n} from \"@remixicon/react\";\n\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n AlertDialogTrigger,\n} from \"@constructive-io/ui/alert-dialog\";\nimport { Button } from \"@constructive-io/ui/button\";\nimport { Input } from \"@constructive-io/ui/input\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"@constructive-io/ui/popover\";\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from \"@constructive-io/ui/select\";\n\nimport {\n getDefaultOperator,\n getOperatorsForGqlType,\n isFilterableType,\n type FilterOperator,\n type OperatorValueType,\n} from \"./filter-operators\";\nimport type { SheetsSelection } from \"../selection/selection-model\";\n\n// Filter value can be string, number, boolean, null, or undefined\n// This matches the usage in buildWhereFromFilters and GraphQL filter operations\nexport type FilterValue = string | number | boolean | null | undefined;\n\n// ── Filter tree types ──\n\nexport type FilterNode = FilterCondition | FilterGroup;\n\nexport interface FilterCondition {\n type: \"condition\";\n id: string;\n field: string;\n operator: string;\n value: FilterValue;\n}\n\nexport interface FilterGroup {\n type: \"group\";\n id: string;\n conjunction: \"and\" | \"or\";\n children: FilterNode[];\n}\n\nexport const MAX_FILTER_DEPTH = 3;\n\nexport type FieldTypeMap = Record<string, { gqlType: string; isArray: boolean }>;\n\n// ── Tree helpers ──\n\nfunction uid(): string {\n return Math.random().toString(36).slice(2, 9);\n}\n\nexport function createEmptyGroup(conjunction: \"and\" | \"or\" = \"and\"): FilterGroup {\n return { type: \"group\", id: uid(), conjunction, children: [] };\n}\n\nfunction createCondition(field: string, operator: string): FilterCondition {\n return { type: \"condition\", id: uid(), field, operator, value: \"\" };\n}\n\nexport function countConditions(node: FilterNode): number {\n if (node.type === \"condition\") return 1;\n return node.children.reduce((sum, child) => sum + countConditions(child), 0);\n}\n\nexport interface SheetsControlsProps {\n openSearch?: () => void;\n filterTree: FilterGroup;\n setFilterTree: (tree: FilterGroup) => void;\n filtersOpen: boolean;\n setFiltersOpen: (open: boolean) => void;\n clearAllFilters: () => void;\n applyFilters: () => void;\n columnKeys: string[];\n fieldTypeMap: FieldTypeMap;\n showSelection: boolean;\n gridSelection: SheetsSelection | null;\n setGridSelection: (selection: SheetsSelection | null) => void;\n deleteSelected: () => void;\n onAddRow?: () => void;\n onExport?: () => void;\n canDelete?: boolean;\n readOnlyReason?: string | null;\n}\n\nfunction getInputType(valueType: OperatorValueType): string {\n switch (valueType) {\n case \"number\":\n return \"number\";\n case \"date\":\n return \"date\";\n case \"datetime\":\n return \"datetime-local\";\n default:\n return \"text\";\n }\n}\n\nfunction getPlaceholder(valueType: OperatorValueType): string {\n if (valueType === \"key\") return \"key name\";\n return \"Value...\";\n}\n\n/** Parse a JSON-encoded IntervalInput string into individual fields. */\nfunction parseIntervalValue(raw: FilterValue): {\n days: string;\n hours: string;\n minutes: string;\n seconds: string;\n} {\n const empty = { days: \"\", hours: \"\", minutes: \"\", seconds: \"\" };\n if (!raw || typeof raw !== \"string\") return empty;\n try {\n const obj = JSON.parse(raw);\n return {\n days: obj.days ? String(obj.days) : \"\",\n hours: obj.hours ? String(obj.hours) : \"\",\n minutes: obj.minutes ? String(obj.minutes) : \"\",\n seconds: obj.seconds ? String(obj.seconds) : \"\",\n };\n } catch {\n return empty;\n }\n}\n\n/** Compose individual interval fields into a JSON-encoded IntervalInput string. */\nfunction composeIntervalValue(fields: {\n days: string;\n hours: string;\n minutes: string;\n seconds: string;\n}): string {\n const obj: Record<string, number> = {};\n const d = parseInt(fields.days, 10);\n const h = parseInt(fields.hours, 10);\n const m = parseInt(fields.minutes, 10);\n const s = parseInt(fields.seconds, 10);\n if (!isNaN(d) && d !== 0) obj.days = d;\n if (!isNaN(h) && h !== 0) obj.hours = h;\n if (!isNaN(m) && m !== 0) obj.minutes = m;\n if (!isNaN(s) && s !== 0) obj.seconds = s;\n return Object.keys(obj).length > 0 ? JSON.stringify(obj) : \"\";\n}\n\n/** Structured interval input — renders d/h/m/s number fields that map to IntervalInput. */\nfunction IntervalFilterInput({\n value,\n onChange,\n}: {\n value: FilterValue;\n onChange: (v: string) => void;\n}) {\n const fields = useMemo(() => parseIntervalValue(value), [value]);\n\n const handleChange = useCallback(\n (unit: \"days\" | \"hours\" | \"minutes\" | \"seconds\", v: string) => {\n onChange(composeIntervalValue({ ...fields, [unit]: v }));\n },\n [fields, onChange],\n );\n\n return (\n <div className=\"flex items-center gap-1\">\n <Input\n className=\"w-[52px] px-1.5 text-center\"\n type=\"number\"\n placeholder=\"d\"\n min={0}\n value={fields.days}\n onChange={(e) => handleChange(\"days\", e.target.value)}\n />\n <Input\n className=\"w-[52px] px-1.5 text-center\"\n type=\"number\"\n placeholder=\"h\"\n min={0}\n max={23}\n value={fields.hours}\n onChange={(e) => handleChange(\"hours\", e.target.value)}\n />\n <Input\n className=\"w-[52px] px-1.5 text-center\"\n type=\"number\"\n placeholder=\"m\"\n min={0}\n max={59}\n value={fields.minutes}\n onChange={(e) => handleChange(\"minutes\", e.target.value)}\n />\n <Input\n className=\"w-[52px] px-1.5 text-center\"\n type=\"number\"\n placeholder=\"s\"\n min={0}\n max={59}\n value={fields.seconds}\n onChange={(e) => handleChange(\"seconds\", e.target.value)}\n />\n </div>\n );\n}\n\nconst FilterConditionRow = memo(function FilterConditionRow({\n condition,\n columns,\n fieldTypeMap,\n onChange,\n onRemove,\n}: {\n condition: FilterCondition;\n columns: readonly string[];\n fieldTypeMap: FieldTypeMap;\n onChange: (updates: Partial<FilterCondition>) => void;\n onRemove: () => void;\n}) {\n const typeInfo = fieldTypeMap[condition.field];\n const operators = useMemo<FilterOperator[]>(\n () => getOperatorsForGqlType(typeInfo?.gqlType, typeInfo?.isArray ?? false),\n [typeInfo?.gqlType, typeInfo?.isArray],\n );\n const currentOp = operators.find((o) => o.operator === condition.operator) ?? operators[0];\n\n const handleColumnChange = useCallback(\n (newField: string) => {\n const info = fieldTypeMap[newField];\n const defaultOp = getDefaultOperator(info?.gqlType, info?.isArray ?? false) ?? \"equalTo\";\n onChange({ field: newField, operator: defaultOp, value: \"\" });\n },\n [fieldTypeMap, onChange],\n );\n\n const handleOperatorChange = useCallback(\n (newOp: string) => {\n const opEntry = operators.find((o) => o.operator === newOp);\n if (opEntry?.valueType === \"none\") {\n onChange({ operator: newOp, value: \"\" });\n } else {\n onChange({ operator: newOp });\n }\n },\n [operators, onChange],\n );\n\n return (\n <div className=\"flex items-center gap-2\">\n <Select value={condition.field} onValueChange={handleColumnChange}>\n <SelectTrigger className=\"w-[140px]\">\n <SelectValue placeholder=\"Column\" />\n </SelectTrigger>\n <SelectContent>\n {columns.map((k) => (\n <SelectItem key={k} value={k}>\n {k}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n {operators.length > 0 && (\n <Select value={currentOp?.operator ?? \"\"} onValueChange={handleOperatorChange}>\n <SelectTrigger className=\"w-[130px]\">\n <SelectValue placeholder=\"Operator\" />\n </SelectTrigger>\n <SelectContent>\n {operators.map((op) => (\n <SelectItem key={op.operator} value={op.operator}>\n {op.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )}\n\n {currentOp && currentOp.valueType === \"interval\" && (\n <IntervalFilterInput value={condition.value} onChange={(v) => onChange({ value: v })} />\n )}\n\n {currentOp && currentOp.valueType !== \"none\" && currentOp.valueType !== \"interval\" && (\n <Input\n className=\"w-[150px]\"\n type={getInputType(currentOp.valueType)}\n placeholder={getPlaceholder(currentOp.valueType)}\n value={\n typeof condition.value === \"string\" || typeof condition.value === \"number\"\n ? String(condition.value)\n : \"\"\n }\n onChange={(e) => onChange({ value: e.target.value })}\n />\n )}\n\n <Button variant=\"ghost\" size=\"icon\" onClick={onRemove} aria-label=\"Remove filter\">\n <RiCloseCircleLine className=\"h-4 w-4\" />\n </Button>\n </div>\n );\n});\n\n/** Recursive filter group UI — renders AND/OR toggle + conditions + nested groups. */\nconst FilterGroupUI = memo(function FilterGroupUI({\n group,\n depth,\n fieldTypeMap,\n filterableColumns,\n onChange,\n onRemove,\n}: {\n group: FilterGroup;\n depth: number;\n fieldTypeMap: FieldTypeMap;\n filterableColumns: readonly string[];\n onChange: (updated: FilterGroup) => void;\n onRemove?: () => void;\n}) {\n const toggleConjunction = useCallback(() => {\n onChange({ ...group, conjunction: group.conjunction === \"and\" ? \"or\" : \"and\" });\n }, [group, onChange]);\n\n const addCondition = useCallback(() => {\n const firstCol = filterableColumns[0];\n if (!firstCol) return;\n const info = fieldTypeMap[firstCol];\n const defaultOp = getDefaultOperator(info?.gqlType, info?.isArray ?? false) ?? \"equalTo\";\n onChange({ ...group, children: [...group.children, createCondition(firstCol, defaultOp)] });\n }, [group, filterableColumns, fieldTypeMap, onChange]);\n\n const addGroup = useCallback(() => {\n const childConj = group.conjunction === \"and\" ? \"or\" : \"and\";\n onChange({ ...group, children: [...group.children, createEmptyGroup(childConj)] });\n }, [group, onChange]);\n\n const updateChild = useCallback(\n (childId: string, updated: FilterNode) => {\n onChange({ ...group, children: group.children.map((c) => (c.id === childId ? updated : c)) });\n },\n [group, onChange],\n );\n\n const removeChild = useCallback(\n (childId: string) => {\n onChange({ ...group, children: group.children.filter((c) => c.id !== childId) });\n },\n [group, onChange],\n );\n\n return (\n <div className={depth > 0 ? \"border-muted-foreground/20 ml-1 border-l-2 pl-3\" : undefined}>\n <div className=\"mb-2 flex items-center gap-1.5\">\n <span className=\"text-muted-foreground text-xs\">Match</span>\n <Button\n variant=\"outline\"\n size=\"sm\"\n className=\"h-6 px-2 text-xs font-medium\"\n onClick={toggleConjunction}\n >\n {group.conjunction === \"and\" ? \"all\" : \"any\"}\n </Button>\n <span className=\"text-muted-foreground text-xs\">of:</span>\n {onRemove && (\n <Button\n variant=\"ghost\"\n size=\"icon\"\n className=\"ml-auto h-6 w-6\"\n onClick={onRemove}\n aria-label=\"Remove group\"\n >\n <RiCloseCircleLine className=\"h-3.5 w-3.5\" />\n </Button>\n )}\n </div>\n\n <div className=\"grid gap-2\">\n {group.children.map((child) => {\n if (child.type === \"condition\") {\n return (\n <FilterConditionRow\n key={child.id}\n condition={child}\n columns={filterableColumns}\n fieldTypeMap={fieldTypeMap}\n onChange={(updates) => updateChild(child.id, { ...child, ...updates })}\n onRemove={() => removeChild(child.id)}\n />\n );\n }\n return (\n <FilterGroupUI\n key={child.id}\n group={child}\n depth={depth + 1}\n fieldTypeMap={fieldTypeMap}\n filterableColumns={filterableColumns}\n onChange={(updated) => updateChild(child.id, updated)}\n onRemove={() => removeChild(child.id)}\n />\n );\n })}\n </div>\n\n <div className=\"mt-2 flex items-center gap-2\">\n <Button variant=\"ghost\" size=\"sm\" className=\"h-7 text-xs\" onClick={addCondition}>\n <RiAddLine className=\"mr-1 h-3.5 w-3.5\" /> Condition\n </Button>\n {depth < MAX_FILTER_DEPTH - 1 && (\n <Button variant=\"ghost\" size=\"sm\" className=\"h-7 text-xs\" onClick={addGroup}>\n <RiAddLine className=\"mr-1 h-3.5 w-3.5\" /> Group\n </Button>\n )}\n </div>\n </div>\n );\n});\n\nexport function SheetsControls(props: SheetsControlsProps) {\n const {\n openSearch,\n filterTree,\n setFilterTree,\n filtersOpen,\n setFiltersOpen,\n clearAllFilters,\n applyFilters,\n columnKeys,\n fieldTypeMap,\n showSelection,\n gridSelection,\n deleteSelected,\n onAddRow,\n onExport,\n canDelete = true,\n readOnlyReason,\n } = props;\n\n const filterableColumns = useMemo(() => {\n if (Object.keys(fieldTypeMap).length === 0) return columnKeys;\n return columnKeys.filter((k) => {\n const info = fieldTypeMap[k];\n if (!info) return false;\n return isFilterableType(info.gqlType, info.isArray);\n });\n }, [columnKeys, fieldTypeMap]);\n\n // ── Local filter tree (only committed on Apply) ──\n const [localTree, setLocalTree] = useState<FilterGroup>(filterTree);\n\n // Sync local state when popover opens\n useEffect(() => {\n if (filtersOpen) {\n setLocalTree(filterTree);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- only trigger on popover open/close\n }, [filtersOpen]);\n\n const handleApplyFilters = useCallback(() => {\n setFilterTree(localTree);\n applyFilters();\n }, [localTree, setFilterTree, applyFilters]);\n\n const handleClearAllFilters = useCallback(() => {\n setLocalTree(createEmptyGroup());\n clearAllFilters();\n }, [clearAllFilters]);\n\n const conditionCount = useMemo(() => countConditions(localTree), [localTree]);\n\n const selectedRowCount = useMemo(() => {\n if (!gridSelection) return 0;\n return gridSelection.rows.length;\n }, [gridSelection]);\n\n return (\n <>\n <div\n data-part-id=\"sheets-controls\"\n className=\"flex shrink-0 flex-wrap items-center justify-between gap-4 py-4\"\n >\n <div className=\"flex min-w-0 flex-wrap items-center gap-2\">\n\t\t {readOnlyReason && (\n\t\t\t<span\n\t\t\t\tclassName=\"border-border bg-muted text-muted-foreground inline-flex h-8 items-center rounded-md border px-2.5 text-xs\"\n\t\t\t\trole=\"status\"\n\t\t\t\ttitle={readOnlyReason}\n\t\t\t>\n\t\t\t\tRead-only\n\t\t\t</span>\n\t\t )}\n <Button variant=\"outline\" size=\"sm\" onClick={() => openSearch?.()}>\n <RiSearch2Line className=\"text-muted-foreground/60 -ms-1.5 size-5\" aria-hidden=\"true\" />\n Search\n </Button>\n {onAddRow && (\n <Button variant=\"outline\" size=\"sm\" aria-label=\"Add row\" onClick={() => onAddRow()}>\n <RiAddLine className=\"text-muted-foreground/60 -ms-1.5 size-5\" aria-hidden=\"true\" />\n Add row\n </Button>\n )}\n {onExport && (\n <Button variant=\"outline\" size=\"sm\" aria-label=\"Export CSV\" onClick={() => onExport()}>\n <RiDownloadLine\n className=\"text-muted-foreground/60 -ms-1.5 size-5\"\n aria-hidden=\"true\"\n />\n Export\n </Button>\n )}\n </div>\n\n <div className=\"flex items-center gap-2\">\n {showSelection && (\n <AlertDialog>\n <AlertDialogTrigger asChild>\n <Button\n\t\t\t\t variant=\"destructive-outline\"\n\t\t\t\t size=\"sm\"\n\t\t\t\t disabled={!canDelete || selectedRowCount === 0}\n\t\t\t\t title={!canDelete ? readOnlyReason ?? 'Delete is unavailable for this table.' : undefined}\n\t\t\t\t>\n <RiDeleteBin6Line className=\"-ms-1.5 size-5\" aria-hidden=\"true\" />\n Delete\n {selectedRowCount > 0 ? ` (${selectedRowCount})` : \"\"}\n </Button>\n </AlertDialogTrigger>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>Delete rows?</AlertDialogTitle>\n <AlertDialogDescription>\n This will permanently delete {selectedRowCount}{\" \"}\n {selectedRowCount === 1 ? \"row\" : \"rows\"}. This action cannot be undone.\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel>Cancel</AlertDialogCancel>\n <AlertDialogAction\n className=\"bg-destructive text-white hover:bg-destructive/90\"\n onClick={() => deleteSelected()}\n >\n Delete\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n )}\n <Popover open={filtersOpen} onOpenChange={setFiltersOpen}>\n <PopoverTrigger asChild>\n <Button variant=\"outline\" size=\"sm\" className=\"relative\">\n <RiFilter3Line\n className=\"text-muted-foreground/60 -ms-1.5 size-5\"\n aria-hidden=\"true\"\n />\n Filters\n {countConditions(filterTree) > 0 && (\n <span\n className=\"border-border/60 bg-background text-muted-foreground/70 ms-2 -me-1 inline-flex h-5\n\t\t\t\t\t\t\t\t\t\t\tmax-h-full items-center rounded border px-1 font-[inherit] text-[0.625rem] font-medium\"\n >\n {countConditions(filterTree)}\n </span>\n )}\n </Button>\n </PopoverTrigger>\n <PopoverContent\n className=\"w-auto min-w-[28rem] max-h-[32rem] overflow-auto p-4\"\n align=\"end\"\n >\n <div className=\"grid gap-4\">\n <div className=\"space-y-2\">\n <h4 className=\"leading-none font-medium\">Filters</h4>\n </div>\n <FilterGroupUI\n group={localTree}\n depth={0}\n fieldTypeMap={fieldTypeMap}\n filterableColumns={filterableColumns}\n onChange={setLocalTree}\n />\n <div className=\"flex items-center justify-end gap-2 border-t pt-2\">\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={handleClearAllFilters}\n disabled={conditionCount === 0}\n >\n Clear all\n </Button>\n <Button size=\"sm\" onClick={handleApplyFilters}>\n Apply\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n </div>\n </div>\n </>\n );\n}\n","export type OperatorValueType = 'string' | 'number' | 'date' | 'datetime' | 'interval' | 'key' | 'none';\n\nexport interface FilterOperator {\n\toperator: string;\n\tlabel: string;\n\tvalueType: OperatorValueType;\n}\n\nconst TEXT_OPERATORS: FilterOperator[] = [\n\t{ operator: 'includesInsensitive', label: 'contains', valueType: 'string' },\n\t{ operator: 'equalTo', label: 'equals', valueType: 'string' },\n\t{ operator: 'notEqualTo', label: 'not equals', valueType: 'string' },\n\t{ operator: 'startsWithInsensitive', label: 'starts with', valueType: 'string' },\n\t{ operator: 'endsWithInsensitive', label: 'ends with', valueType: 'string' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst NUMERIC_OPERATORS: FilterOperator[] = [\n\t{ operator: 'equalTo', label: '=', valueType: 'number' },\n\t{ operator: 'notEqualTo', label: '\\u2260', valueType: 'number' },\n\t{ operator: 'greaterThan', label: '>', valueType: 'number' },\n\t{ operator: 'greaterThanOrEqualTo', label: '\\u2265', valueType: 'number' },\n\t{ operator: 'lessThan', label: '<', valueType: 'number' },\n\t{ operator: 'lessThanOrEqualTo', label: '\\u2264', valueType: 'number' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst BOOLEAN_OPERATORS: FilterOperator[] = [\n\t{ operator: 'equalTo:true', label: 'is true', valueType: 'none' },\n\t{ operator: 'equalTo:false', label: 'is false', valueType: 'none' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nfunction makeDateOperators(valueType: 'date' | 'datetime'): FilterOperator[] {\n\treturn [\n\t\t{ operator: 'equalTo', label: 'equals', valueType },\n\t\t{ operator: 'lessThan', label: 'before', valueType },\n\t\t{ operator: 'lessThanOrEqualTo', label: 'on or before', valueType },\n\t\t{ operator: 'greaterThan', label: 'after', valueType },\n\t\t{ operator: 'greaterThanOrEqualTo', label: 'on or after', valueType },\n\t\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n\t];\n}\n\nconst DATE_OPERATORS = makeDateOperators('date');\nconst DATETIME_OPERATORS = makeDateOperators('datetime');\n\nconst UUID_OPERATORS: FilterOperator[] = [\n\t{ operator: 'equalTo', label: 'equals', valueType: 'string' },\n\t{ operator: 'notEqualTo', label: 'not equals', valueType: 'string' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst INET_OPERATORS: FilterOperator[] = [\n\t{ operator: 'equalTo', label: 'equals', valueType: 'string' },\n\t{ operator: 'notEqualTo', label: 'not equals', valueType: 'string' },\n\t{ operator: 'contains', label: 'contains', valueType: 'string' },\n\t{ operator: 'containedBy', label: 'contained by', valueType: 'string' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst JSON_OPERATORS: FilterOperator[] = [\n\t{ operator: 'containsKey', label: 'has key', valueType: 'key' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst INTERVAL_OPERATORS: FilterOperator[] = [\n\t{ operator: 'equalTo', label: '=', valueType: 'interval' },\n\t{ operator: 'notEqualTo', label: '\\u2260', valueType: 'interval' },\n\t{ operator: 'greaterThan', label: '>', valueType: 'interval' },\n\t{ operator: 'greaterThanOrEqualTo', label: '\\u2265', valueType: 'interval' },\n\t{ operator: 'lessThan', label: '<', valueType: 'interval' },\n\t{ operator: 'lessThanOrEqualTo', label: '\\u2264', valueType: 'interval' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst ENUM_OPERATORS: FilterOperator[] = [\n\t{ operator: 'equalTo', label: 'equals', valueType: 'string' },\n\t{ operator: 'notEqualTo', label: 'not equals', valueType: 'string' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst GQL_TYPE_OPERATORS: Record<string, FilterOperator[]> = {\n\tString: TEXT_OPERATORS,\n\tInt: NUMERIC_OPERATORS,\n\tFloat: NUMERIC_OPERATORS,\n\tBigFloat: NUMERIC_OPERATORS,\n\tBigInt: NUMERIC_OPERATORS,\n\tBoolean: BOOLEAN_OPERATORS,\n\tDate: DATE_OPERATORS,\n\tDatetime: DATETIME_OPERATORS,\n\tUUID: UUID_OPERATORS,\n\tInternetAddress: INET_OPERATORS,\n\tJSON: JSON_OPERATORS,\n\tInterval: INTERVAL_OPERATORS,\n\tBitString: ENUM_OPERATORS,\n};\n\nconst UNFILTERABLE_TYPES = new Set(['GeoJSON', 'FullText']);\n\n/** Get available filter operators for a given gqlType. Returns empty array for unfilterable types. */\nexport function getOperatorsForGqlType(gqlType: string | null | undefined, isArray: boolean): FilterOperator[] {\n\tif (!gqlType || isArray || UNFILTERABLE_TYPES.has(gqlType)) return [];\n\treturn GQL_TYPE_OPERATORS[gqlType] ?? [];\n}\n\n/** Whether a field type can be filtered at all. */\nexport function isFilterableType(gqlType: string | null | undefined, isArray: boolean): boolean {\n\tif (!gqlType || isArray || UNFILTERABLE_TYPES.has(gqlType)) return false;\n\treturn gqlType in GQL_TYPE_OPERATORS;\n}\n\n/** Get the default (first) operator for a gqlType. */\nexport function getDefaultOperator(gqlType: string | null | undefined, isArray: boolean): string | undefined {\n\tconst ops = getOperatorsForGqlType(gqlType, isArray);\n\treturn ops[0]?.operator;\n}\n\n/** Whether an operator encodes its value and needs no user input. */\nexport function isValuelessOperator(operator: string): boolean {\n\treturn operator === 'isNull' || operator === 'equalTo:true' || operator === 'equalTo:false';\n}\n","/**\n * The right-click CONTEXT MENU (Stage B) — the showcase of the command layer: a menu is just\n * another EVENT SOURCE that resolves to named commands and runs through the SAME `dispatch`\n * pipeline as keys / clicks. Rendered ONCE at the grid level (never per-cell, so the per-cell\n * memo is untouched); the cell host calls `open(col, row, clientX, clientY)` on `onContextMenu`.\n *\n * Anchoring: Base UI's Menu anchors to its Trigger. We render a 0×0 FIXED trigger at the pointer\n * coordinates and toggle the controlled `open`, so the popup floats at the right-clicked cell.\n *\n * The ITEM MODEL is a pure builder (`buildContextMenuItems`) so the action→command mapping +\n * disabled gating is unit-testable WITHOUT the Base-UI popup (which needs a real layout env). The\n * component maps the model to <DropdownMenuItem>s. \"Delete row(s)\" is the one destructive action —\n * its `run` requests the SAME AlertDialog confirm the toolbar Delete uses.\n */\nimport { useState, type ReactNode } from 'react';\nimport { RiAddLine, RiClipboardLine, RiDeleteBin6Line, RiEraserLine, RiScissorsLine, RiFileCopyLine } from '@remixicon/react';\n\nimport {\n\tAlertDialog,\n\tAlertDialogAction,\n\tAlertDialogCancel,\n\tAlertDialogContent,\n\tAlertDialogDescription,\n\tAlertDialogFooter,\n\tAlertDialogHeader,\n\tAlertDialogTitle,\n} from '@constructive-io/ui/alert-dialog';\nimport {\n\tDropdownMenu,\n\tDropdownMenuContent,\n\tDropdownMenuItem,\n\tDropdownMenuSeparator,\n\tDropdownMenuShortcut,\n\tDropdownMenuTrigger,\n} from '@constructive-io/ui/dropdown-menu';\n\n/** Where the menu is anchored + the cell it acts on. `null` = closed. */\nexport interface ContextMenuState {\n\tclientX: number;\n\tclientY: number;\n}\n\n/** One row of the menu (or a separator). `run` fires on click; `disabled` greys it out. */\nexport interface ContextMenuItem {\n\tkey: string;\n\tseparator?: boolean;\n\tlabel?: string;\n\ticon?: ReactNode;\n\tshortcut?: string;\n\tdestructive?: boolean;\n\tdisabled?: boolean;\n\trun?: () => void;\n}\n\nexport interface BuildContextMenuItemsArgs {\n\t/** Dispatch a command id through the grid's stable dispatch pipeline. */\n\tonAction: (commandId: string) => void;\n\t/** True when the command's `canRun` passes against the latched context. */\n\tisEnabled: (commandId: string) => boolean;\n\t/** Append a draft row (the toolbar Add-row path). */\n\tonAddRow: () => void;\n\t/** Open the destructive delete confirm (the AlertDialog). */\n\trequestDelete: () => void;\n\t/** Count of currently selected rows — gates Delete + drives its label. */\n\tselectedRowCount: number;\n\tcanAddRows?: boolean;\n\tcanDeleteRows?: boolean;\n}\n\n/**\n * Pure menu model — the single source of truth for the items, their command mapping, and their\n * disabled state. Tested directly (no DOM). Clipboard / clear items dispatch their command id via\n * `onAction` and are disabled when `isEnabled(id)` is false; Add row / Delete use dedicated paths.\n */\nexport function buildContextMenuItems({\n\tonAction,\n\tisEnabled,\n\tonAddRow,\n\trequestDelete,\n\tselectedRowCount,\n\tcanAddRows = true,\n\tcanDeleteRows = true,\n}: BuildContextMenuItemsArgs): ContextMenuItem[] {\n\tconst cmd = (key: string, commandId: string, label: string, icon: ReactNode, shortcut?: string): ContextMenuItem => ({\n\t\tkey,\n\t\tlabel,\n\t\ticon,\n\t\tshortcut,\n\t\tdisabled: !isEnabled(commandId),\n\t\trun: () => onAction(commandId),\n\t});\n\treturn [\n\t\tcmd('copy', 'clipboard.copy', 'Copy', <RiFileCopyLine className='size-4' aria-hidden='true' />, '⌘C'),\n\t\tcmd('cut', 'clipboard.cut', 'Cut', <RiScissorsLine className='size-4' aria-hidden='true' />, '⌘X'),\n\t\tcmd('paste', 'clipboard.paste', 'Paste', <RiClipboardLine className='size-4' aria-hidden='true' />, '⌘V'),\n\t\tcmd('clear', 'cell.clear', 'Clear', <RiEraserLine className='size-4' aria-hidden='true' />),\n\t\t{ key: 'sep', separator: true },\n\t\t{\n\t\t\tkey: 'add-row',\n\t\t\tlabel: 'Add row',\n\t\t\ticon: <RiAddLine className='size-4' aria-hidden='true' />,\n\t\t\tdisabled: !canAddRows,\n\t\t\trun: onAddRow,\n\t\t},\n\t\t{\n\t\t\tkey: 'delete-rows',\n\t\t\tlabel: selectedRowCount > 1 ? `Delete ${selectedRowCount} rows` : 'Delete row',\n\t\t\ticon: <RiDeleteBin6Line className='size-4' aria-hidden='true' />,\n\t\t\tdestructive: true,\n\t\t\tdisabled: !canDeleteRows || selectedRowCount === 0,\n\t\t\trun: requestDelete,\n\t\t},\n\t];\n}\n\nexport interface SheetsContextMenuProps {\n\t/** Open anchor + position; `null` keeps the menu closed. */\n\tstate: ContextMenuState | null;\n\t/** Close the menu (clears `state`). */\n\tonClose: () => void;\n\t/** Dispatch a command id through the grid's stable dispatch pipeline. */\n\tonAction: (commandId: string) => void;\n\t/** True when the command's `canRun` passes against the latched context. */\n\tisEnabled: (commandId: string) => boolean;\n\t/** Append a draft row (the toolbar Add-row path). */\n\tonAddRow: () => void;\n\t/** Delete the selected row(s) (the toolbar deleteSelected path) — guarded by the AlertDialog. */\n\tonDeleteRows: () => void;\n\t/** Count of currently selected rows — drives the destructive dialog copy. */\n\tselectedRowCount: number;\n\tcanAddRows?: boolean;\n\tcanDeleteRows?: boolean;\n}\n\nexport function SheetsContextMenu({\n\tstate,\n\tonClose,\n\tonAction,\n\tisEnabled,\n\tonAddRow,\n\tonDeleteRows,\n\tselectedRowCount,\n\tcanAddRows = true,\n\tcanDeleteRows = true,\n}: SheetsContextMenuProps) {\n\tconst [confirmDelete, setConfirmDelete] = useState(false);\n\tconst open = state !== null;\n\n\tconst items = buildContextMenuItems({\n\t\tonAction,\n\t\tisEnabled,\n\t\tonAddRow,\n\t\trequestDelete: () => setConfirmDelete(true),\n\t\tselectedRowCount,\n\t\tcanAddRows,\n\t\tcanDeleteRows,\n\t});\n\n\treturn (\n\t\t<>\n\t\t\t<DropdownMenu open={open} onOpenChange={(next) => !next && onClose()}>\n\t\t\t\t{/* 0×0 fixed anchor at the pointer — the menu floats from here. */}\n\t\t\t\t<DropdownMenuTrigger\n\t\t\t\t\taria-hidden\n\t\t\t\t\ttabIndex={-1}\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\tposition: 'fixed',\n\t\t\t\t\t\tleft: state?.clientX ?? 0,\n\t\t\t\t\t\ttop: state?.clientY ?? 0,\n\t\t\t\t\t\twidth: 0,\n\t\t\t\t\t\theight: 0,\n\t\t\t\t\t}}\n\t\t\t\t/>\n\t\t\t\t<DropdownMenuContent align='start'>\n\t\t\t\t\t{items.map((item) =>\n\t\t\t\t\t\titem.separator ? (\n\t\t\t\t\t\t\t<DropdownMenuSeparator key={item.key} />\n\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t<DropdownMenuItem\n\t\t\t\t\t\t\t\tkey={item.key}\n\t\t\t\t\t\t\t\tvariant={item.destructive ? 'destructive' : 'default'}\n\t\t\t\t\t\t\t\tdisabled={item.disabled}\n\t\t\t\t\t\t\t\tonClick={() => {\n\t\t\t\t\t\t\t\t\t// Run then close — a menu pick is a one-shot (the popup dismisses).\n\t\t\t\t\t\t\t\t\titem.run?.();\n\t\t\t\t\t\t\t\t\tonClose();\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{item.icon}\n\t\t\t\t\t\t\t\t{item.label}\n\t\t\t\t\t\t\t\t{item.shortcut && <DropdownMenuShortcut>{item.shortcut}</DropdownMenuShortcut>}\n\t\t\t\t\t\t\t</DropdownMenuItem>\n\t\t\t\t\t\t),\n\t\t\t\t\t)}\n\t\t\t\t</DropdownMenuContent>\n\t\t\t</DropdownMenu>\n\n\t\t\t{/* Destructive confirm — mirrors the toolbar Delete AlertDialog. Driven open after the\n\t\t\t menu closes so the two overlays never fight for focus. */}\n\t\t\t<AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>\n\t\t\t\t<AlertDialogContent>\n\t\t\t\t\t<AlertDialogHeader>\n\t\t\t\t\t\t<AlertDialogTitle>Delete rows?</AlertDialogTitle>\n\t\t\t\t\t\t<AlertDialogDescription>\n\t\t\t\t\t\t\tThis will permanently delete {selectedRowCount} {selectedRowCount === 1 ? 'row' : 'rows'}. This action cannot be\n\t\t\t\t\t\t\tundone.\n\t\t\t\t\t\t</AlertDialogDescription>\n\t\t\t\t\t</AlertDialogHeader>\n\t\t\t\t\t<AlertDialogFooter>\n\t\t\t\t\t\t<AlertDialogCancel>Cancel</AlertDialogCancel>\n\t\t\t\t\t\t<AlertDialogAction\n\t\t\t\t\t\t\tclassName='bg-destructive text-white hover:bg-destructive/90'\n\t\t\t\t\t\t\tonClick={() => {\n\t\t\t\t\t\t\t\tonDeleteRows();\n\t\t\t\t\t\t\t\tsetConfirmDelete(false);\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\tDelete\n\t\t\t\t\t\t</AlertDialogAction>\n\t\t\t\t\t</AlertDialogFooter>\n\t\t\t\t</AlertDialogContent>\n\t\t\t</AlertDialog>\n\t\t</>\n\t);\n}\n","'use client';\n\nimport { createContext, useCallback, useContext, useEffect, useMemo, useReducer, useRef } from 'react';\n\nimport {\n\tcreateInitialState,\n\tfeedbackReducer,\n\tgenerateOperationId,\n\tgetDefaultDismissDuration,\n\ttype FeedbackState,\n\ttype OperationFeedback,\n} from './feedback-reducer';\n\ninterface FeedbackContextValue {\n\tstate: FeedbackState;\n\n\t// Operation feedback actions\n\tstartOperation: (type: OperationFeedback['type'], total: number) => string;\n\tupdateOperationProgress: (id: string, completed: number, failed: number) => void;\n\tcompleteOperation: (\n\t\tid: string,\n\t\tstatus: 'success' | 'partial' | 'error',\n\t\tmessage: string,\n\t\tdismissAfter?: number,\n\t) => void;\n\tclearOperationFeedback: () => void;\n}\n\nconst FeedbackContext = createContext<FeedbackContextValue | null>(null);\n\ninterface FeedbackProviderProps {\n\tchildren: React.ReactNode;\n}\n\nexport function FeedbackProvider({ children }: FeedbackProviderProps) {\n\tconst [state, dispatch] = useReducer(feedbackReducer, undefined, createInitialState);\n\n\t// Track timeout for auto-clearing operation feedback\n\tconst operationTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n\t// Cleanup timeout on unmount\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tif (operationTimeoutRef.current) {\n\t\t\t\tclearTimeout(operationTimeoutRef.current);\n\t\t\t}\n\t\t};\n\t}, []);\n\n\t// Operation feedback actions\n\tconst startOperation = useCallback((type: OperationFeedback['type'], total: number): string => {\n\t\t// Clear any pending operation timeout\n\t\tif (operationTimeoutRef.current) {\n\t\t\tclearTimeout(operationTimeoutRef.current);\n\t\t\toperationTimeoutRef.current = null;\n\t\t}\n\t\tconst id = generateOperationId();\n\t\tdispatch({ type: 'OPERATION_START', operationType: type, total, id });\n\t\treturn id;\n\t}, []);\n\n\tconst updateOperationProgress = useCallback((id: string, completed: number, failed: number) => {\n\t\tdispatch({ type: 'OPERATION_PROGRESS', id, completed, failed });\n\t}, []);\n\n\tconst completeOperation = useCallback(\n\t\t(id: string, status: 'success' | 'partial' | 'error', message: string, dismissAfter?: number) => {\n\t\t\tconst duration = dismissAfter ?? getDefaultDismissDuration(status);\n\t\t\tdispatch({ type: 'OPERATION_COMPLETE', id, status, message, dismissAfter: duration });\n\n\t\t\t// Auto-dismiss if duration > 0\n\t\t\tif (duration > 0) {\n\t\t\t\toperationTimeoutRef.current = setTimeout(() => {\n\t\t\t\t\tdispatch({ type: 'OPERATION_CLEAR' });\n\t\t\t\t\toperationTimeoutRef.current = null;\n\t\t\t\t}, duration);\n\t\t\t}\n\t\t},\n\t\t[],\n\t);\n\n\tconst clearOperationFeedback = useCallback(() => {\n\t\tif (operationTimeoutRef.current) {\n\t\t\tclearTimeout(operationTimeoutRef.current);\n\t\t\toperationTimeoutRef.current = null;\n\t\t}\n\t\tdispatch({ type: 'OPERATION_CLEAR' });\n\t}, []);\n\n\tconst value = useMemo<FeedbackContextValue>(\n\t\t() => ({\n\t\t\tstate,\n\t\t\tstartOperation,\n\t\t\tupdateOperationProgress,\n\t\t\tcompleteOperation,\n\t\t\tclearOperationFeedback,\n\t\t}),\n\t\t[state, startOperation, updateOperationProgress, completeOperation, clearOperationFeedback],\n\t);\n\n\treturn <FeedbackContext.Provider value={value}>{children}</FeedbackContext.Provider>;\n}\n\nexport function useFeedback(): FeedbackContextValue {\n\tconst context = useContext(FeedbackContext);\n\tif (!context) {\n\t\tthrow new Error('useFeedback must be used within a FeedbackProvider');\n\t}\n\treturn context;\n}\n\n/**\n * Hook for accessing only operation feedback - useful for dock status bar\n */\nexport function useOperationFeedback(): OperationFeedback | null {\n\tconst { state } = useFeedback();\n\treturn state.operation;\n}\n","/**\n * Grid Feedback Reducer\n *\n * Manages transient UI feedback state for data grid bulk operations.\n * Uses vanilla React (useReducer) instead of Zustand since this state is:\n * - Local to the data grid component tree\n * - Ephemeral (no persistence needed)\n * - Automatically cleaned up on unmount\n */\n\nexport type OperationStatus = 'idle' | 'pending' | 'success' | 'partial' | 'error';\n\nexport interface OperationFeedback {\n\tid: string;\n\ttype: 'delete' | 'submit' | 'update';\n\tstatus: OperationStatus;\n\tmessage: string;\n\ttotal: number;\n\tcompleted: number;\n\tfailed: number;\n\ttimestamp: number;\n\t/** Auto-dismiss duration in ms. 0 = persistent until manually cleared. */\n\tdismissAfter: number;\n}\n\nexport interface FeedbackState {\n\t/** Current bulk operation feedback (shown in floating status) */\n\toperation: OperationFeedback | null;\n}\n\n// Action types\ntype FeedbackAction =\n\t| { type: 'OPERATION_START'; operationType: OperationFeedback['type']; total: number; id: string }\n\t| { type: 'OPERATION_PROGRESS'; id: string; completed: number; failed: number }\n\t| {\n\t\t\ttype: 'OPERATION_COMPLETE';\n\t\t\tid: string;\n\t\t\tstatus: 'success' | 'partial' | 'error';\n\t\t\tmessage: string;\n\t\t\tdismissAfter: number;\n\t }\n\t| { type: 'OPERATION_CLEAR' };\n\n// Duration constants\nexport const FEEDBACK_DURATIONS = {\n\t/** Success operation message duration (ms) */\n\tOPERATION_SUCCESS: 3000,\n\t/** Error operation message - longer for reading (ms) */\n\tOPERATION_ERROR: 5000,\n\t/** Partial success duration (ms) */\n\tOPERATION_PARTIAL: 4000,\n} as const;\n\nexport function createInitialState(): FeedbackState {\n\treturn {\n\t\toperation: null,\n\t};\n}\n\nexport function feedbackReducer(state: FeedbackState, action: FeedbackAction): FeedbackState {\n\tswitch (action.type) {\n\t\tcase 'OPERATION_START': {\n\t\t\tconst typeLabels: Record<OperationFeedback['type'], string> = {\n\t\t\t\tdelete: 'Deleting',\n\t\t\t\tsubmit: 'Submitting',\n\t\t\t\tupdate: 'Updating',\n\t\t\t};\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\toperation: {\n\t\t\t\t\tid: action.id,\n\t\t\t\t\ttype: action.operationType,\n\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\tmessage: `${typeLabels[action.operationType]} ${action.total} ${action.total === 1 ? 'row' : 'rows'}...`,\n\t\t\t\t\ttotal: action.total,\n\t\t\t\t\tcompleted: 0,\n\t\t\t\t\tfailed: 0,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\tdismissAfter: 0,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tcase 'OPERATION_PROGRESS': {\n\t\t\tif (!state.operation || state.operation.id !== action.id) {\n\t\t\t\treturn state;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\toperation: {\n\t\t\t\t\t...state.operation,\n\t\t\t\t\tcompleted: action.completed,\n\t\t\t\t\tfailed: action.failed,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tcase 'OPERATION_COMPLETE': {\n\t\t\tif (!state.operation || state.operation.id !== action.id) {\n\t\t\t\treturn state;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\toperation: {\n\t\t\t\t\t...state.operation,\n\t\t\t\t\tstatus: action.status,\n\t\t\t\t\tmessage: action.message,\n\t\t\t\t\tdismissAfter: action.dismissAfter,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tcase 'OPERATION_CLEAR': {\n\t\t\treturn { ...state, operation: null };\n\t\t}\n\n\t\tdefault:\n\t\t\treturn state;\n\t}\n}\n\n// Helper to generate operation IDs\nexport function generateOperationId(): string {\n\treturn `op_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n}\n\n// Helper to get dismiss duration based on status\nexport function getDefaultDismissDuration(status: 'success' | 'partial' | 'error'): number {\n\tswitch (status) {\n\t\tcase 'success':\n\t\t\treturn FEEDBACK_DURATIONS.OPERATION_SUCCESS;\n\t\tcase 'partial':\n\t\t\treturn FEEDBACK_DURATIONS.OPERATION_PARTIAL;\n\t\tcase 'error':\n\t\t\treturn FEEDBACK_DURATIONS.OPERATION_ERROR;\n\t}\n}\n","'use client';\n\nimport { useCallback } from 'react';\nimport { RiCheckLine, RiCloseLine, RiErrorWarningLine, RiLoader4Line } from '@remixicon/react';\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { springs } from '../../utils/motion-config';\nimport { cn } from '../../utils/cn';\nimport { Button } from '@constructive-io/ui/button';\n\nimport { useOperationFeedback, useFeedback } from './feedback-context';\nimport type { OperationFeedback } from './feedback-reducer';\n\ninterface DockStatusBarProps {\n\tclassName?: string;\n\t/** Called when user clicks retry on a failed/partial operation */\n\tonRetry?: () => void;\n}\n\n/**\n * Inline status bar that appears in the floating dock during bulk operations.\n * Replaces toast notifications for delete, submit, and batch update operations.\n *\n * Shows:\n * - Progress spinner + message during pending operations\n * - Success checkmark + message (auto-dismisses)\n * - Error/partial warning + message with optional retry\n */\nexport function DockStatusBar({ className, onRetry }: DockStatusBarProps) {\n\tconst operation = useOperationFeedback();\n\tconst { clearOperationFeedback } = useFeedback();\n\n\tconst handleDismiss = useCallback(() => {\n\t\tclearOperationFeedback();\n\t}, [clearOperationFeedback]);\n\n\tif (!operation) {\n\t\treturn null;\n\t}\n\n\treturn (\n\t\t<AnimatePresence mode='wait'>\n\t\t\t<motion.div\n\t\t\t\tkey={operation.id}\n\t\t\t\tinitial={{ opacity: 0, x: 20 }}\n\t\t\t\tanimate={{ opacity: 1, x: 0 }}\n\t\t\t\texit={{ opacity: 0, x: -20 }}\n\t\t\t\ttransition={springs.snappy}\n\t\t\t\tclassName={cn('flex items-center gap-2', className)}\n\t\t\t>\n\t\t\t\t<StatusIcon status={operation.status} />\n\t\t\t\t<span className='text-sm font-medium'>{operation.message}</span>\n\n\t\t\t\t{/* Retry button for errors/partial failures */}\n\t\t\t\t{(operation.status === 'error' || operation.status === 'partial') && onRetry && (\n\t\t\t\t\t<Button variant='ghost' size='sm' className='h-7 px-2 text-xs' onClick={onRetry}>\n\t\t\t\t\t\tRetry\n\t\t\t\t\t</Button>\n\t\t\t\t)}\n\n\t\t\t\t{/* Dismiss button for completed operations */}\n\t\t\t\t{operation.status !== 'pending' && (\n\t\t\t\t\t<Button\n\t\t\t\t\t\tvariant='ghost'\n\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\tclassName='text-muted-foreground hover:text-foreground h-7 w-7 p-0'\n\t\t\t\t\t\tonClick={handleDismiss}\n\t\t\t\t\t\taria-label='Dismiss'\n\t\t\t\t\t>\n\t\t\t\t\t\t<RiCloseLine className='h-4 w-4' />\n\t\t\t\t\t</Button>\n\t\t\t\t)}\n\t\t\t</motion.div>\n\t\t</AnimatePresence>\n\t);\n}\n\nfunction StatusIcon({ status }: { status: OperationFeedback['status'] }) {\n\tswitch (status) {\n\t\tcase 'pending':\n\t\t\treturn <RiLoader4Line className='text-muted-foreground h-4 w-4 animate-spin' />;\n\t\tcase 'success':\n\t\t\treturn <RiCheckLine className='h-4 w-4 text-emerald-500' />;\n\t\tcase 'partial':\n\t\t\treturn <RiErrorWarningLine className='h-4 w-4 text-amber-500' />;\n\t\tcase 'error':\n\t\t\treturn <RiErrorWarningLine className='h-4 w-4 text-red-500' />;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Compact variant for space-constrained layouts.\n * Shows only icon + abbreviated message.\n */\nexport function DockStatusBarCompact({ className }: { className?: string }) {\n\tconst operation = useOperationFeedback();\n\tconst { clearOperationFeedback } = useFeedback();\n\n\tif (!operation) {\n\t\treturn null;\n\t}\n\n\tconst shortMessage = getShortMessage(operation);\n\n\treturn (\n\t\t<AnimatePresence mode='wait'>\n\t\t\t<motion.button\n\t\t\t\tkey={operation.id}\n\t\t\t\tinitial={{ opacity: 0, scale: 0.9 }}\n\t\t\t\tanimate={{ opacity: 1, scale: 1 }}\n\t\t\t\texit={{ opacity: 0, scale: 0.9 }}\n\t\t\t\ttransition={springs.snappy}\n\t\t\t\tclassName={cn(\n\t\t\t\t\t'flex items-center gap-1.5 rounded-full px-2.5 py-1',\n\t\t\t\t\toperation.status === 'pending' && 'bg-muted',\n\t\t\t\t\toperation.status === 'success' && 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',\n\t\t\t\t\toperation.status === 'partial' && 'bg-amber-500/10 text-amber-600 dark:text-amber-400',\n\t\t\t\t\toperation.status === 'error' && 'bg-red-500/10 text-red-600 dark:text-red-400',\n\t\t\t\t\tclassName,\n\t\t\t\t)}\n\t\t\t\tonClick={operation.status !== 'pending' ? clearOperationFeedback : undefined}\n\t\t\t\tdisabled={operation.status === 'pending'}\n\t\t\t>\n\t\t\t\t<StatusIcon status={operation.status} />\n\t\t\t\t<span className='text-xs font-medium'>{shortMessage}</span>\n\t\t\t</motion.button>\n\t\t</AnimatePresence>\n\t);\n}\n\nfunction getShortMessage(operation: OperationFeedback): string {\n\tif (operation.status === 'pending') {\n\t\treturn `${operation.completed}/${operation.total}`;\n\t}\n\tif (operation.status === 'success') {\n\t\treturn `${operation.total} done`;\n\t}\n\tif (operation.status === 'partial') {\n\t\treturn `${operation.failed} failed`;\n\t}\n\treturn 'Failed';\n}\n","import type { Transition } from 'motion/react';\n\n/**\n * Shared motion configuration for consistent animations across the app.\n * Based on practical animation tips from https://emilkowal.ski/ui/7-practical-animation-tips\n *\n * Key principles:\n * 1. Keep UI animations under 300ms\n * 2. Never animate from scale(0) - use 0.9+ for natural feel\n * 3. Use custom easing curves for more impactful animations\n * 4. Make animations origin-aware when possible\n * 5. Use blur to smooth transitions when needed\n */\n\n// =============================================================================\n// Easing Curves\n// =============================================================================\n\n/**\n * Standard easing curves for UI animations.\n * Reference: https://easings.co/\n */\nexport const easings = {\n\t/** Smooth deceleration - good for elements entering the screen */\n\teaseOut: [0.25, 0.1, 0.25, 1] as const,\n\n\t/** Smooth acceleration - good for elements leaving the screen */\n\teaseIn: [0.42, 0, 1, 1] as const,\n\n\t/** Smooth both ways - good for hover states and toggles */\n\teaseInOut: [0.42, 0, 0.58, 1] as const,\n\n\t/** Snappy entrance with soft landing - great for modals/dialogs */\n\tsnappy: [0.2, 0, 0, 1] as const,\n\n\t/** Bouncy feel - use sparingly for playful interactions */\n\tbounce: [0.34, 1.56, 0.64, 1] as const,\n\n\t/** Quick start, gradual stop - good for quick feedback */\n\temphasized: [0.4, 0, 0.2, 1] as const,\n\n\t/** Physical feel for exit animations */\n\tphysicalExit: [0.4, 0, 0.6, 1] as const,\n} as const;\n\n// =============================================================================\n// Duration Presets\n// =============================================================================\n\n/**\n * Duration presets in seconds.\n * Rule: UI animations should be under 300ms (0.3s)\n */\nexport const durations = {\n\t/** Instant feedback (button press, toggle) */\n\tinstant: 0.1,\n\n\t/** Quick transitions (tooltips, small elements) */\n\tfast: 0.15,\n\n\t/** Standard UI transitions (modals, panels) */\n\tnormal: 0.2,\n\n\t/** Deliberate animations (page transitions, complex reveals) */\n\tslow: 0.3,\n\n\t/** Maximum for UI - use rarely */\n\tdeliberate: 0.4,\n} as const;\n\n// =============================================================================\n// Spring Presets\n// =============================================================================\n\n/**\n * Spring configurations for physics-based animations.\n * These create more natural, organic motion.\n */\nexport const springs = {\n\t/** Snappy spring - good for quick interactions */\n\tsnappy: {\n\t\ttype: 'spring' as const,\n\t\tstiffness: 400,\n\t\tdamping: 30,\n\t\tmass: 0.8,\n\t},\n\n\t/** Bouncy spring - good for playful elements */\n\tbouncy: {\n\t\ttype: 'spring' as const,\n\t\tstiffness: 300,\n\t\tdamping: 20,\n\t\tmass: 0.6,\n\t},\n\n\t/** Gentle spring - good for large elements */\n\tgentle: {\n\t\ttype: 'spring' as const,\n\t\tstiffness: 150,\n\t\tdamping: 25,\n\t\tmass: 1,\n\t},\n\n\t/** Stiff spring - good for precise movements */\n\tstiff: {\n\t\ttype: 'spring' as const,\n\t\tstiffness: 500,\n\t\tdamping: 35,\n\t\tmass: 0.5,\n\t},\n\n\t/** Panel/sheet animations */\n\tpanel: {\n\t\ttype: 'spring' as const,\n\t\tstiffness: 150,\n\t\tdamping: 25,\n\t},\n} as const;\n\n// =============================================================================\n// Transition Presets\n// =============================================================================\n\n/**\n * Pre-configured transitions for common animation patterns.\n */\nexport const transitions = {\n\t/** Fast fade for overlays and simple elements */\n\tfade: {\n\t\tduration: durations.fast,\n\t\tease: easings.easeOut,\n\t} satisfies Transition,\n\n\t/** Standard enter/exit for UI elements */\n\tenterExit: {\n\t\tduration: durations.normal,\n\t\tease: easings.easeOut,\n\t} satisfies Transition,\n\n\t/** Snappy transition for interactive elements */\n\tsnappy: {\n\t\tduration: durations.fast,\n\t\tease: easings.snappy,\n\t} satisfies Transition,\n\n\t/** Panel slide transition */\n\tpanel: {\n\t\ttype: 'spring',\n\t\tstiffness: 150,\n\t\tdamping: 25,\n\t} satisfies Transition,\n\n\t/** Exit transition with physical feel */\n\texit: {\n\t\ttype: 'tween',\n\t\tduration: durations.normal,\n\t\tease: easings.physicalExit,\n\t} satisfies Transition,\n\n\t/** Layout animations */\n\tlayout: {\n\t\ttype: 'spring',\n\t\tstiffness: 300,\n\t\tdamping: 30,\n\t} satisfies Transition,\n} as const;\n\n// =============================================================================\n// Animation Variants\n// =============================================================================\n\n/**\n * Common animation variants for AnimatePresence patterns.\n * Follows the rule: never animate from scale(0), use 0.9+ instead.\n */\nexport const variants = {\n\t/** Fade with subtle scale - good for modals, cards */\n\tfadeScale: {\n\t\tinitial: { opacity: 0, scale: 0.95 },\n\t\tanimate: { opacity: 1, scale: 1 },\n\t\texit: { opacity: 0, scale: 0.95 },\n\t},\n\n\t/** Fade with subtle slide up - good for content reveals */\n\tfadeSlideUp: {\n\t\tinitial: { opacity: 0, y: 8 },\n\t\tanimate: { opacity: 1, y: 0 },\n\t\texit: { opacity: 0, y: -8 },\n\t},\n\n\t/** Fade with subtle slide down - good for dropdowns */\n\tfadeSlideDown: {\n\t\tinitial: { opacity: 0, y: -8 },\n\t\tanimate: { opacity: 1, y: 0 },\n\t\texit: { opacity: 0, y: 8 },\n\t},\n\n\t/** Simple fade - for overlays */\n\tfade: {\n\t\tinitial: { opacity: 0 },\n\t\tanimate: { opacity: 1 },\n\t\texit: { opacity: 0 },\n\t},\n\n\t/** Dock/floating element - scales from bottom */\n\tfloatUp: {\n\t\tinitial: { opacity: 0, y: 8, scale: 0.98 },\n\t\tanimate: { opacity: 1, y: 0, scale: 1 },\n\t\texit: { opacity: 0, y: 8, scale: 0.98 },\n\t},\n} as const;\n\n// =============================================================================\n// Convenience Aliases (from original template)\n// =============================================================================\n\nexport const MOTION_SPRING = springs.stiff;\nexport const MOTION_DURATION = { duration: durations.normal };\n","'use client';\n\nimport { useCallback } from 'react';\nimport { RiCheckLine, RiCloseLine, RiErrorWarningLine, RiLoader4Line } from '@remixicon/react';\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { springs } from '../../utils/motion-config';\nimport { cn } from '../../utils/cn';\n\nimport { useOperationFeedback, useFeedback } from './feedback-context';\nimport type { OperationFeedback } from './feedback-reducer';\n\ninterface FloatingStatusProps {\n\tclassName?: string;\n}\n\n/**\n * Standalone floating status indicator for bulk operations.\n * Shows independently of row selection, positioned at bottom-center of grid.\n */\nexport function FloatingStatus({ className }: FloatingStatusProps) {\n\tconst operation = useOperationFeedback();\n\tconst { clearOperationFeedback } = useFeedback();\n\n\tconst handleDismiss = useCallback(() => {\n\t\tclearOperationFeedback();\n\t}, [clearOperationFeedback]);\n\n\treturn (\n\t\t<AnimatePresence>\n\t\t\t{operation && (\n\t\t\t\t<motion.div\n\t\t\t\t\tkey={operation.id}\n\t\t\t\t\tinitial={{ opacity: 0, y: 20, scale: 0.95 }}\n\t\t\t\t\tanimate={{ opacity: 1, y: 0, scale: 1 }}\n\t\t\t\t\texit={{ opacity: 0, y: 10, scale: 0.95 }}\n\t\t\t\t\ttransition={springs.snappy}\n\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t'bg-background pointer-events-auto flex items-center gap-3 rounded-full border px-4 py-2 shadow-lg',\n\t\t\t\t\t\tclassName,\n\t\t\t\t\t)}\n\t\t\t\t>\n\t\t\t\t\t<StatusIcon status={operation.status} />\n\t\t\t\t\t<span className='text-sm font-medium'>{operation.message}</span>\n\n\t\t\t\t\t{/* Dismiss button for completed operations */}\n\t\t\t\t\t{operation.status !== 'pending' && (\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\ttype='button'\n\t\t\t\t\t\t\tclassName='text-muted-foreground hover:text-foreground -mr-1 rounded-full p-1 transition-colors'\n\t\t\t\t\t\t\tonClick={handleDismiss}\n\t\t\t\t\t\t\taria-label='Dismiss'\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<RiCloseLine className='h-4 w-4' />\n\t\t\t\t\t\t</button>\n\t\t\t\t\t)}\n\t\t\t\t</motion.div>\n\t\t\t)}\n\t\t</AnimatePresence>\n\t);\n}\n\nfunction StatusIcon({ status }: { status: OperationFeedback['status'] }) {\n\tconst baseClass = 'h-4 w-4';\n\n\tswitch (status) {\n\t\tcase 'pending':\n\t\t\treturn <RiLoader4Line className={cn(baseClass, 'text-muted-foreground animate-spin')} />;\n\t\tcase 'success':\n\t\t\treturn <RiCheckLine className={cn(baseClass, 'text-emerald-500')} />;\n\t\tcase 'partial':\n\t\t\treturn <RiErrorWarningLine className={cn(baseClass, 'text-amber-500')} />;\n\t\tcase 'error':\n\t\t\treturn <RiErrorWarningLine className={cn(baseClass, 'text-red-500')} />;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n","'use client';\n\nimport { Component, type ErrorInfo, type ReactNode } from 'react';\n\nimport { sheetsLogger } from '../../utils/sheets-logger';\nimport { SheetsErrorState } from './sheets-error-state';\n\ninterface SheetsErrorBoundaryProps {\n\tchildren: ReactNode;\n\t/** Called when a render error is caught. Mirrors SheetsConfig.onError. */\n\tonError?: (error: unknown, ctx?: { source?: 'grid' | 'editor' | 'mutation' | 'upload'; tableName?: string }) => void;\n\t/** Custom fallback. Receives the error and a reset callback to retry rendering. */\n\tfallback?: (error: unknown, reset: () => void) => ReactNode;\n}\n\ninterface SheetsErrorBoundaryState {\n\terror: unknown;\n}\n\n/**\n * Render-error boundary for the grid subtree. Catches exceptions thrown during\n * render of the DataEditor and editors, logs them through the injectable logger,\n * forwards them to the host via onError, and shows a recoverable error state.\n */\nexport class SheetsErrorBoundary extends Component<SheetsErrorBoundaryProps, SheetsErrorBoundaryState> {\n\tstate: SheetsErrorBoundaryState = { error: null };\n\n\tstatic getDerivedStateFromError(error: unknown): SheetsErrorBoundaryState {\n\t\treturn { error };\n\t}\n\n\tcomponentDidCatch(error: unknown, info: ErrorInfo): void {\n\t\tsheetsLogger().error('[sheets] render error', { error, componentStack: info.componentStack });\n\t\tthis.props.onError?.(error, { source: 'grid' });\n\t}\n\n\treset = (): void => {\n\t\tthis.setState({ error: null });\n\t};\n\n\trender(): ReactNode {\n\t\tconst { error } = this.state;\n\t\tif (error != null) {\n\t\t\treturn this.props.fallback?.(error, this.reset) ?? <SheetsErrorState error={error} onRetry={this.reset} />;\n\t\t}\n\t\treturn this.props.children;\n\t}\n}\n","'use client';\n\nimport { RiAddLine, RiErrorWarningLine, RiInboxLine } from '@remixicon/react';\n\nimport { Button } from '@constructive-io/ui/button';\nimport { cn } from '../../utils/cn';\n\nfunction getErrorMessage(error: unknown): string {\n\tif (error instanceof Error) return error.message;\n\tif (typeof error === 'string') return error;\n\treturn 'Something went wrong while loading this table.';\n}\n\ninterface SheetsStateShellProps {\n\tclassName?: string;\n\tchildren: React.ReactNode;\n}\n\n/** Centered, full-size container shared by the error/empty/loading states. */\nfunction SheetsStateShell({ className, children }: SheetsStateShellProps) {\n\treturn (\n\t\t<div\n\t\t\tclassName={cn(\n\t\t\t\t'bg-background flex h-full min-h-0 flex-1 flex-col items-center justify-center gap-3 rounded-lg border p-8 text-center',\n\t\t\t\tclassName,\n\t\t\t)}\n\t\t>\n\t\t\t{children}\n\t\t</div>\n\t);\n}\n\ninterface SheetsErrorStateProps {\n\terror: unknown;\n\tonRetry?: () => void;\n}\n\n/** Shown when the table data (or its metadata) fails to load. */\nexport function SheetsErrorState({ error, onRetry }: SheetsErrorStateProps) {\n\treturn (\n\t\t<SheetsStateShell>\n\t\t\t<RiErrorWarningLine className='text-destructive h-8 w-8' />\n\t\t\t<div className='space-y-1'>\n\t\t\t\t<p className='text-foreground text-sm font-medium'>Failed to load data</p>\n\t\t\t\t<p className='text-muted-foreground max-w-md text-sm'>{getErrorMessage(error)}</p>\n\t\t\t</div>\n\t\t\t{onRetry && (\n\t\t\t\t<Button variant='outline' size='sm' onClick={onRetry}>\n\t\t\t\t\tRetry\n\t\t\t\t</Button>\n\t\t\t)}\n\t\t</SheetsStateShell>\n\t);\n}\n\ninterface SheetsEmptyStateProps {\n\ttableName?: string;\n\tonAddRow?: () => void;\n\treadOnlyReason?: string | null;\n}\n\n/** Shown when the table loaded successfully but has no rows. */\nexport function SheetsEmptyState({ tableName, onAddRow, readOnlyReason }: SheetsEmptyStateProps) {\n\treturn (\n\t\t<SheetsStateShell>\n\t\t\t<RiInboxLine className='text-muted-foreground h-8 w-8' />\n\t\t\t<div className='space-y-1'>\n\t\t\t\t<p className='text-foreground text-sm font-medium'>No rows yet</p>\n\t\t\t\t<p className='text-muted-foreground max-w-md text-sm'>\n\t\t\t\t\t{readOnlyReason ?? (tableName ? `The \"${tableName}\" table is empty.` : 'This table is empty.')}\n\t\t\t\t</p>\n\t\t\t</div>\n\t\t\t{onAddRow && (\n\t\t\t\t<Button variant='outline' size='sm' onClick={onAddRow}>\n\t\t\t\t\t<RiAddLine className='h-4 w-4' />\n\t\t\t\t\t<span className='ms-1'>Add row</span>\n\t\t\t\t</Button>\n\t\t\t)}\n\t\t</SheetsStateShell>\n\t);\n}\n\n/** Column-width hints (px) for the skeleton bars — varied so it reads as a real table. */\nconst SKELETON_COLS = [120, 88, 152, 64, 108, 132, 80];\nconst SKELETON_ROWS = 12;\n\n/**\n * Shown during the initial data load. A STRUCTURAL skeleton of the grid (baseline-ui:\n * prefer skeletons over spinners) — mirrors the real grid's 40px header + 44px rows +\n * horizontal hairlines so the load→loaded swap doesn't jump. Pulse is motion-safe only.\n */\nexport function SheetsLoadingState() {\n\treturn (\n\t\t<div\n\t\t\tclassName='bg-background flex h-full min-h-0 flex-1 flex-col overflow-hidden rounded-lg border'\n\t\t\trole='status'\n\t\t\taria-busy='true'\n\t\t\taria-label='Loading data'\n\t\t>\n\t\t\t<div className='flex shrink-0 items-center gap-6 border-b px-3' style={{ height: 40 }}>\n\t\t\t\t{SKELETON_COLS.map((w, i) => (\n\t\t\t\t\t<div key={i} className='bg-muted h-2.5 shrink-0 rounded-sm' style={{ width: Math.round(w * 0.7) }} />\n\t\t\t\t))}\n\t\t\t</div>\n\t\t\t{Array.from({ length: SKELETON_ROWS }).map((_, r) => (\n\t\t\t\t<div key={r} className='flex shrink-0 items-center gap-6 border-b px-3' style={{ height: 44 }}>\n\t\t\t\t\t{SKELETON_COLS.map((w, i) => (\n\t\t\t\t\t\t<div key={i} className='bg-muted/60 h-3 shrink-0 rounded-sm motion-safe:animate-pulse' style={{ width: w }} />\n\t\t\t\t\t))}\n\t\t\t\t</div>\n\t\t\t))}\n\t\t</div>\n\t);\n}\n","import { RiArrowLeftSLine, RiArrowRightSLine, RiSkipBackLine, RiSkipForwardLine } from '@remixicon/react';\n\nimport { Button } from '@constructive-io/ui/button';\nimport { Pagination, PaginationContent, PaginationItem } from '@constructive-io/ui/pagination';\n\nexport interface SheetsPaginationProps {\n\tpageIndex: number;\n\tpageSize: number;\n\ttotalCount: number;\n\ttotalPages: number;\n\tsetPageIndex: React.Dispatch<React.SetStateAction<number>>;\n}\n\nexport function SheetsPagination(props: SheetsPaginationProps) {\n\tconst { pageIndex, pageSize, totalCount, totalPages, setPageIndex } = props;\n\n\treturn (\n\t\t<div\n\t\t\tdata-part-id='sheets-pagination'\n\t\t\tclassName='flex shrink-0 flex-col items-start justify-between gap-3 pt-4 sm:flex-row sm:items-center'\n\t\t>\n\t\t\t<p className='text-muted-foreground flex-1 text-sm whitespace-nowrap' aria-live='polite'>\n\t\t\t\tShowing <span className='text-foreground'>{(pageIndex * pageSize + 1).toLocaleString()}</span> to\n\t\t\t\t<span className='text-foreground'>\n\t\t\t\t\t{' '}\n\t\t\t\t\t{Math.min((pageIndex + 1) * pageSize, totalCount).toLocaleString()}\n\t\t\t\t</span> of <span className='text-foreground'>{totalCount.toLocaleString()}</span> results\n\t\t\t</p>\n\t\t\t<Pagination className='w-auto'>\n\t\t\t\t<PaginationContent className='gap-2'>\n\t\t\t\t\t<PaginationItem>\n\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\tvariant='secondary'\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\tonClick={() => setPageIndex(0)}\n\t\t\t\t\t\t\tdisabled={pageIndex === 0}\n\t\t\t\t\t\t\taria-label='Go to first page'\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<RiSkipBackLine size={16} />\n\t\t\t\t\t\t\t<span className='ml-1 hidden sm:inline'>First</span>\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</PaginationItem>\n\t\t\t\t\t<PaginationItem>\n\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\tvariant='secondary'\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\tonClick={() => setPageIndex((p) => Math.max(0, p - 1))}\n\t\t\t\t\t\t\tdisabled={pageIndex === 0}\n\t\t\t\t\t\t\taria-label='Go to previous page'\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<RiArrowLeftSLine size={16} />\n\t\t\t\t\t\t\t<span className='ml-1'>Previous</span>\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</PaginationItem>\n\t\t\t\t\t<PaginationItem>\n\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\tvariant='secondary'\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\tonClick={() => setPageIndex((p) => Math.min(totalPages - 1, p + 1))}\n\t\t\t\t\t\t\tdisabled={pageIndex >= totalPages - 1}\n\t\t\t\t\t\t\taria-label='Go to next page'\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span className='mr-1'>Next</span>\n\t\t\t\t\t\t\t<RiArrowRightSLine size={16} />\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</PaginationItem>\n\t\t\t\t\t<PaginationItem>\n\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\tvariant='secondary'\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\tonClick={() => setPageIndex(totalPages - 1)}\n\t\t\t\t\t\t\tdisabled={pageIndex >= totalPages - 1}\n\t\t\t\t\t\t\taria-label='Go to last page'\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span className='mr-1 hidden sm:inline'>Last</span>\n\t\t\t\t\t\t\t<RiSkipForwardLine size={16} />\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</PaginationItem>\n\t\t\t\t</PaginationContent>\n\t\t\t</Pagination>\n\t\t</div>\n\t);\n}\n","/**\n * useSheets — headless grid assembly hook.\n *\n * Computes the data/state bindings the default {@link Sheets} component renders\n * with the native TanStack DOM grid: columns, the native cell-content resolver,\n * value-commit helpers, and the draft / selection / pagination APIs. The built-in\n * {@link Sheets} component is a thin consumer of this hook.\n *\n * The STABLE headless surface is {@link UseSheetsResult}. A handful of additional\n * fields under the `_shell` group are returned only so the built-in `<Sheets>`\n * chrome (toolbar, pagination, dock) can render; they are intentionally NOT part\n * of the supported headless contract and may change.\n */\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\n\nimport type { SheetsSelection } from '../selection/selection-model';\nimport type { RelationInfo } from '../store/relation-info-slice';\n\nimport { useDataGridColumns, type RelationGridColumn } from '../hooks/use-relation-columns';\nimport { useSheetsContext } from '../context/sheets-context';\nimport { useSheetsStore } from '../store/sheets-store';\nimport { sheetsLogger } from '../utils/sheets-logger';\nimport { computeDraftMetaSignature } from '../store/draft-rows-slice';\nimport { toast } from '@constructive-io/ui/toast';\nimport type { DataGridProps, SheetsEvent } from './sheets.types';\nimport { attachDraftMeta, getDraftMeta, type SheetsRow } from './row-model';\n\nimport { createCellTypeRegistry, type CellTypeRegistry } from '../cell-types/cell-type-registry';\nimport { createSheetsCell } from '../cell-model/create-sheets-cell';\nimport { compileSlots } from '../cell-model/cell-slots';\nimport { DRAFT_ACTION_COLUMN_KEY } from './sheets.constants';\nimport { countConditions } from './sheets.controls';\nimport { useFeedback } from './feedback';\nimport {\n\tbuildWhereFromFilters,\n\tcreateHeaderClickHandler,\n\tmapFromFieldMetaMap,\n\tmapFromRelationInfoMap,\n\tnormalizeServerRow,\n} from './sheets.utils';\nimport { useSheetsMeta } from '../hooks/use-sheets-meta';\nimport type { DraftSubmitResult } from './draft-types';\nimport { useCellEditing } from './hooks/use-cell-editing';\nimport { useBatchCommit, type CellWrite, type CommitCellsOptions, type CommitCellsResult } from './hooks/use-batch-commit';\nimport { useUndoRedo } from './hooks/use-undo-redo';\nimport { useDraftRows } from './hooks/use-draft-rows';\nimport { useDraftSubmission } from './hooks/use-draft-submission';\nimport { useSheetsContent, type SheetsCellResolution } from '../grid-dom/use-sheets-content';\nimport { useGridOperations } from './hooks/use-grid-operations';\nimport { useGridSelectionState } from './hooks/use-grid-selection';\nimport { useGridState } from './hooks/use-grid-state';\nimport { useInfiniteGridData, type VisibleRowRange } from './hooks/use-infinite-grid-data';\nimport { useDataLoading } from './hooks/use-load-grid';\nimport {\n\tcanRunSheetsMutation,\n\tgetSheetsWriteCapability,\n\tresolveSheetsRowIdentity,\n\tsheetsRowKey,\n\ttype SheetsRowIdentifier,\n} from '../row-identity';\n\nconst EMPTY_RELATION_INFO_BY_FIELD = new Map<string, RelationInfo>();\n\n/** Draft-row bindings for a headless shell. */\nexport interface SheetsDraftBindings {\n\t/** Whether any client-side draft rows exist. */\n\thasDrafts: boolean;\n\t/** Append a new draft row. Returns the new row index. */\n\tappendRow: () => Promise<number | undefined>;\n\t/** Submit all pending draft rows. */\n\tsubmitDrafts: () => Promise<void>;\n\t/** Delete the currently selected rows (draft + server). */\n\tdeleteSelected: () => Promise<void>;\n}\n\n/**\n * Selection bindings for a headless shell.\n *\n * The selection value is the native {@link SheetsSelection} (RangeSet-backed `rows`).\n */\nexport interface SheetsSelectionBindings {\n\t/** Current native grid selection. */\n\tgridSelection: SheetsSelection | undefined;\n\t/** Setter. */\n\tsetGridSelection: (selection: SheetsSelection | undefined) => void;\n\t/** Park the active cell on `[col, row]` (preserves row/column selection). */\n\tsetActiveCell: (col: number, row: number) => void;\n\t/** Move the active cell by `[dCol, dRow]`, clamped to grid bounds. */\n\tmoveActive: (dCol: number, dRow: number, colCount: number, rowCount: number) => void;\n}\n\n/** Pagination bindings for a headless shell (paginated mode). */\nexport interface SheetsPaginationBindings {\n\t/** Current zero-based page index. */\n\tpageIndex: number;\n\t/** Total page count (>= 1). */\n\tpageCount: number;\n\t/** Set the page index (emits a `page:change` event). */\n\tsetPageIndex: (updater: number | ((prev: number) => number)) => void;\n}\n\n/**\n * Stable headless surface returned by {@link useSheets}. (The hook also returns a\n * few `_shell`-grouped extras consumed only by the built-in {@link Sheets} chrome —\n * those are not part of this supported contract.)\n */\nexport interface UseSheetsResult {\n\t/** Native column descriptors (key/title/width). */\n\tcolumns: RelationGridColumn[];\n\t/** Number of rows to render. */\n\trowCount: number;\n\t/** Draft-row bindings. */\n\tdraft: SheetsDraftBindings;\n\t/** Selection bindings. */\n\tselection: SheetsSelectionBindings;\n\t/** Pagination bindings. */\n\tpagination: SheetsPaginationBindings;\n\t/** True only during the very first load (refetches keep previous data). */\n\tisInitialLoading: boolean;\n\t/** Data-load error, if any. */\n\tdataError: Error | null;\n\t/** Whether the initial load has completed (success). */\n\thasCompletedInitialLoad: boolean;\n\t/** True when loaded, no server rows, no drafts, and no active filter. */\n\tisEmpty: boolean;\n\t/** Refetch the underlying data (mode-aware: infinite vs paginated). */\n\trefetch: () => void;\n}\n\n/**\n * Internal bindings consumed only by the built-in {@link Sheets} chrome\n * (toolbar, dock, pagination chrome). NOT a supported part of the headless contract.\n */\nexport interface SheetsShellBindings {\n\tcombinedRows: SheetsRow[];\n\tcolumnKeys: string[];\n\ttotalCount: number;\n\tserverRowCount: number;\n\tdraftRowCount: number;\n\tinfiniteScroll: boolean;\n\tfilterTree: ReturnType<typeof useGridState>['state']['filterTree'];\n\tfiltersOpen: boolean;\n\tsetFilterTree: ReturnType<typeof useGridState>['actions']['setFilterTree'];\n\tsetFiltersOpen: ReturnType<typeof useGridState>['actions']['setFiltersOpen'];\n\tclearAllFilters: ReturnType<typeof useGridState>['actions']['clearAllFilters'];\n\tapplyFilters: () => void;\n\tfieldTypeMap: Record<string, { gqlType: string; isArray: boolean }>;\n\tsetGridSelectionForControls: (selection: SheetsSelection | null) => void;\n\t/** Header sort toggle (colIndex → toggleSorting on the sortable column). */\n\tonHeaderClicked: (colIndex: number) => void;\n\t/** Prefetch the rows in an inclusive visible window (native range, infinite mode). */\n\tonVisibleRegionChanged: (range: VisibleRowRange) => void;\n\t/** @internal Sort state mirror ({ id, desc }) — the DOM header reads this for its caret. NOT a stable API. */\n\tsorting: ReturnType<typeof useGridState>['state']['sorting'];\n\t/** @internal Committed column widths (id → px) — the DOM grid maps these to v9 columnSizing. NOT a stable API. */\n\tcolumnWidths: ReturnType<typeof useGridState>['state']['columnWidths'];\n\t/** @internal Commit a column width (id, px) — the DOM resize handle drives this directly. NOT a stable API. */\n\tresizeColumn: ReturnType<typeof useGridState>['actions']['resizeColumn'];\n\tfrozenCount: number;\n\tselectedRowCount: number;\n\tcanCreate: boolean;\n\tcanUpdate: boolean;\n\tcanDelete: boolean;\n\t/** Human-readable reason shown when `_meta` proves the whole table is read-only. */\n\treadOnlyReason: string | null;\n\t/** Stable identity for selection, TanStack rows, and editor instances. */\n\tgetRowId: (row: SheetsRow | null | undefined, index: number) => string;\n\tisSubmittingDrafts: boolean;\n\tsubmitDraftButtonDisabled: boolean;\n\tsubmitDraftLabel: string;\n\t/** @internal Native DOM content resolver for the TanStack DOM grid. NOT a stable API. */\n\tgetSheetsCellContent: (rowIndex: number, colKey: string) => SheetsCellResolution;\n\t/** @internal Per-instance cell-type registry (consumer overrides over built-ins). NOT a stable API. */\n\tcellRegistry: CellTypeRegistry;\n\t/** @internal Native value-commit for the TanStack DOM portal editors. NOT a stable API. */\n\tcommitCellValue: (rowIndex: number, colKey: string, nextValue: unknown) => void;\n\t/** @internal Batched server-row value commit (paste/fill/bulk + the single cell). NOT a stable API. */\n\tcommitCells: (writes: CellWrite[], opts?: CommitCellsOptions) => Promise<CommitCellsResult>;\n\t/** @internal Native MULTI-field patch-commit for self-committing DOM portal editors (relation/image). NOT a stable API. */\n\tcommitCellPatch: (rowIndex: number, patch: Record<string, unknown>) => void;\n\t/** @internal Submit a client-side draft row for a self-committing DOM portal editor. NOT a stable API. */\n\tsubmitDraftRow: (draftRowId: string) => Promise<DraftSubmitResult>;\n\t/** @internal Invalidate cached grid data after a self-committing DOM portal editor mutates out-of-band. NOT a stable API. */\n\tinvalidateData: () => void;\n\t/** @internal Undo the last recorded server-row value write. NOT a stable API. */\n\tundo: () => Promise<void>;\n\t/** @internal Redo the last undone server-row value write. NOT a stable API. */\n\tredo: () => Promise<void>;\n\t/** @internal Whether an undo is available. NOT a stable API. */\n\tcanUndo: boolean;\n\t/** @internal Whether a redo is available. NOT a stable API. */\n\tcanRedo: boolean;\n\t/** @internal Observational event emitter (analytics/telemetry) — threaded into the command context. NOT a stable API. */\n\temit: (type: SheetsEvent['type'], meta?: Record<string, unknown>) => void;\n}\n\nexport type UseSheetsInternalResult<TRow extends SheetsRow = SheetsRow> = UseSheetsResult & {\n\t/** @internal Bindings for the built-in <Sheets> chrome — not a stable API. */\n\t_shell: SheetsShellBindings;\n};\n\n/**\n * Headless grid hook — returns the data/state bindings the built-in {@link Sheets}\n * component renders with the native DOM grid.\n *\n * Preconditions:\n * - You MUST render inside a `<FeedbackProvider>` (exported from this package) —\n * the hook uses the bulk-operation feedback context and throws without it.\n *\n * NOTE: the generic `TRow` flows through {@link DataGridProps}'s row callbacks\n * (e.g. `onRowSelect`). It does not retype the cell bindings, which operate on\n * the dynamic schema-derived row shape.\n */\nexport function useSheets<TRow extends SheetsRow = SheetsRow>(\n\tprops: DataGridProps<TRow>,\n): UseSheetsInternalResult<TRow> {\n\tconst {\n\t\ttableName,\n\t\tpageSize = 100,\n\t\tonRowSelect,\n\t\tonCellEdit,\n\t\trelationChipLimit,\n\t\trelationLabelMaxLength,\n\t\tinfiniteScroll = false,\n\t\tcellTypes,\n\t\tcellSlots,\n\t\tonEvent,\n\t} = props;\n\n\t// Get feedback context for bulk operation status indicators\n\tconst { startOperation, updateOperationProgress, completeOperation, clearOperationFeedback } = useFeedback();\n\n\t// Keep the latest onEvent in a ref so firing events never depends on (or churns)\n\t// the callbacks/effects below — purely observational, no behavioral coupling.\n\tconst onEventRef = useRef(onEvent);\n\tonEventRef.current = onEvent;\n\tconst emit = useCallback((type: SheetsEvent['type'], meta?: Record<string, unknown>) => {\n\t\tonEventRef.current?.({ type, tableName, at: Date.now(), meta });\n\t}, [tableName]);\n\n\tconst { config } = useSheetsContext();\n\n\t// Per-instance cell-type registry: consumer overrides (provider plugins, then\n\t// per-instance cellTypes) layered over the built-in native engine. With no consumer\n\t// cell types this delegates 1:1 to createSheetsCell.\n\tconst cellRegistry = useMemo(\n\t\t() =>\n\t\t\tcreateCellTypeRegistry(\n\t\t\t\t// Compiled cell-component slots go LAST so they win over plugins + cellTypes.\n\t\t\t\t[...(config.plugins ?? []).flatMap((p) => p.cellTypes), ...(cellTypes ?? []), ...compileSlots(cellSlots)],\n\t\t\t\t{\n\t\t\t\t\t// Native display builtin: the SheetsCell dispatcher.\n\t\t\t\t\ttoSheetsCell: (value, ctx) => createSheetsCell(value, ctx.metadata),\n\t\t\t\t},\n\t\t\t),\n\t\t[config.plugins, cellTypes, cellSlots],\n\t);\n\n\tconst tableKey = useMemo(() => {\n\t\tif (config.databaseId) return `${config.databaseId}::${tableName}`;\n\t\treturn `default::${tableName}`;\n\t}, [config.databaseId, tableName]);\n\n\t// Clear stale operation feedback when switching tables\n\tuseEffect(() => {\n\t\tclearOperationFeedback();\n\t}, [tableName, clearOperationFeedback]);\n\n\t// Centralized state management\n\tconst { state: gridState, actions: gridActions } = useGridState();\n\n\t// Build orderBy from grid state\n\tconst orderByClause = useMemo(\n\t\t() =>\n\t\t\tgridState.sorting.id\n\t\t\t\t? [{ field: gridState.sorting.id, direction: gridState.sorting.desc ? ('desc' as const) : ('asc' as const) }]\n\t\t\t\t: undefined,\n\t\t[gridState.sorting],\n\t);\n\n\t// ============== FILTER / SEARCH → WHERE CLAUSE ==============\n\t// Fetch meta independently so we can build the where clause before data hooks run\n\tconst { data: filterMeta } = useSheetsMeta();\n\tconst filterTableMeta = useMemo(\n\t\t() => filterMeta?._meta?.tables?.find((t) => t?.name === tableName) ?? null,\n\t\t[filterMeta, tableName],\n\t);\n\n\tconst effectiveWhere = useMemo(\n\t\t() => buildWhereFromFilters(gridState.filterTree, filterTableMeta),\n\t\t[gridState.filterTree, filterTableMeta],\n\t);\n\n\t// Reset to page 0 when filters change (paginated mode)\n\tconst prevWhereRef = useRef(effectiveWhere);\n\tuseEffect(() => {\n\t\tif (prevWhereRef.current !== effectiveWhere) {\n\t\t\tprevWhereRef.current = effectiveWhere;\n\t\t\tif (!infiniteScroll) {\n\t\t\t\tgridActions.setPageIndex(0);\n\t\t\t}\n\t\t}\n\t}, [effectiveWhere, infiniteScroll, gridActions]);\n\n\t// ============== INFINITE SCROLL MODE ==============\n\tconst infiniteGridData = useInfiniteGridData({\n\t\ttableName,\n\t\tpageSize,\n\t\torderBy: orderByClause,\n\t\twhere: effectiveWhere,\n\t\tenabled: infiniteScroll,\n\t});\n\n\t// ============== PAGINATED MODE ==============\n\tconst initialQueryOptions = useMemo(\n\t\t() => ({\n\t\t\tlimit: pageSize,\n\t\t\toffset: gridState.pageIndex * pageSize,\n\t\t\torderBy: orderByClause,\n\t\t\twhere: effectiveWhere,\n\t\t}),\n\t\t[pageSize, gridState.pageIndex, orderByClause, effectiveWhere],\n\t);\n\n\t// In infinite scroll mode we still use mutations from useDataLoading,\n\t// but disable row/count queries to avoid duplicate fetching.\n\tconst dataLoadingResult = useDataLoading({\n\t\ttableName,\n\t\tqueryOptions: initialQueryOptions,\n\t\tenabled: !infiniteScroll,\n\t});\n\n\t// ============== UNIFIED DATA ACCESS ==============\n\t// Choose data source based on mode\n\tconst {\n\t\tserverData,\n\t\ttotalCount,\n\t\ttableMeta,\n\t\tfieldMetaMap,\n\t\tallRelationFields,\n\t\thasCompletedInitialLoad,\n\t\tdataError,\n\t\tisInitialLoading,\n\t} = useMemo(() => {\n\t\tif (infiniteScroll) {\n\t\t\treturn {\n\t\t\t\tserverData: [] as any[], // Not used directly in infinite mode\n\t\t\t\ttotalCount: infiniteGridData.totalCount,\n\t\t\t\ttableMeta: infiniteGridData.tableMeta,\n\t\t\t\tfieldMetaMap: infiniteGridData.fieldMetaMap,\n\t\t\t\tallRelationFields: infiniteGridData.allRelationFields,\n\t\t\t\thasCompletedInitialLoad: infiniteGridData.hasInitialData,\n\t\t\t\tdataError: infiniteGridData.error,\n\t\t\t\t// Only the first load (no rows yet) should show the loading screen; refetches keep previous data.\n\t\t\t\tisInitialLoading: infiniteGridData.isLoading && !infiniteGridData.hasInitialData,\n\t\t\t};\n\t\t}\n\t\tconst ctx = dataLoadingResult.contextValue;\n\t\tconst rows = ctx.data || [];\n\t\treturn {\n\t\t\tserverData: rows,\n\t\t\ttotalCount: ctx.totalCount,\n\t\t\ttableMeta: ctx.tableMeta,\n\t\t\tfieldMetaMap: ctx.fieldMetaMap,\n\t\t\tallRelationFields: ctx.allRelationFields,\n\t\t\thasCompletedInitialLoad: !ctx.isLoading,\n\t\t\tdataError: ctx.error,\n\t\t\t// isLoading is true only until the active scope receives its first result.\n\t\t\tisInitialLoading: ctx.isLoading && rows.length === 0,\n\t\t};\n\t}, [infiniteScroll, infiniteGridData, dataLoadingResult.contextValue]);\n\n\tconst writeCapability = useMemo(() => getSheetsWriteCapability(tableMeta), [tableMeta]);\n\tconst canCreate = canRunSheetsMutation(writeCapability, 'create');\n\tconst canUpdate = canRunSheetsMutation(writeCapability, 'update');\n\tconst canDelete = canRunSheetsMutation(writeCapability, 'delete');\n\tconst primaryKeyFields = useMemo(\n\t\t() => new Set(writeCapability?.status === 'mutable' ? writeCapability.primaryKeyFields : []),\n\t\t[writeCapability],\n\t);\n\tconst supportsScalarSelfCommit =\n\t\twriteCapability?.status === 'mutable' &&\n\t\twriteCapability.primaryKeyFields.length === 1 &&\n\t\twriteCapability.primaryKeyFields[0] === 'id';\n\tconst readOnlyReason = writeCapability?.status === 'read-only'\n\t\t? 'This table is read-only because it has no primary key.'\n\t\t: null;\n\tconst getRowIdentifier = useCallback(\n\t\t(row: Readonly<Record<string, unknown>>): SheetsRowIdentifier | null => {\n\t\t\tif (!tableMeta) return null;\n\t\t\tconst resolution = resolveSheetsRowIdentity(tableMeta, row);\n\t\t\treturn resolution.status === 'identified' ? resolution.identifier : null;\n\t\t},\n\t\t[tableMeta],\n\t);\n\tconst getRowId = useCallback(\n\t\t(row: SheetsRow | null | undefined, index: number): string => {\n\t\t\tconst draftMeta = getDraftMeta(row);\n\t\t\tif (draftMeta) return draftMeta.draftRowId;\n\t\t\tif (row && tableMeta) return sheetsRowKey(tableMeta, row, index);\n\t\t\treturn `${tableMeta?.schemaName ?? ''}:${tableName}:row:${index}`;\n\t\t},\n\t\t[tableMeta, tableName],\n\t);\n\n\t// Emit load:success / load:error once per transition. Tracked via a ref so we\n\t// don't re-fire on unrelated re-renders.\n\tconst lastLoadEmitRef = useRef<'success' | 'error' | null>(null);\n\tuseEffect(() => {\n\t\tif (dataError) {\n\t\t\tif (lastLoadEmitRef.current !== 'error') {\n\t\t\t\tlastLoadEmitRef.current = 'error';\n\t\t\t\temit('load:error', { error: dataError });\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (hasCompletedInitialLoad && lastLoadEmitRef.current !== 'success') {\n\t\t\tlastLoadEmitRef.current = 'success';\n\t\t\temit('load:success', { totalCount });\n\t\t}\n\t}, [dataError, hasCompletedInitialLoad, totalCount, emit]);\n\n\t// Get CRUD operations (only available in paginated mode for now)\n\tconst { update, create, delete: deleteRow } = dataLoadingResult.contextValue;\n\n\tconst relationFieldNames = useMemo(() => new Set(allRelationFields), [allRelationFields]);\n\n\tconst normalizedServerData = useMemo(() => {\n\t\tif (infiniteScroll) return [] as any[]; // Not used in infinite mode\n\t\tif (!Array.isArray(serverData) || serverData.length === 0 || relationFieldNames.size === 0) {\n\t\t\treturn serverData as any[];\n\t\t}\n\t\treturn (serverData as any[]).map((row) => normalizeServerRow(row, relationFieldNames));\n\t}, [infiniteScroll, serverData, relationFieldNames]);\n\n\tconst {\n\t\tdraftRowsTable,\n\t\tdraftRows,\n\t\thasDraftRows,\n\t\tcombinedRows: paginatedCombinedRows,\n\t\tdraftRowIndices: paginatedDraftRowIndices,\n\t\tcreateDraftRow,\n\t\tupdateDraftCell,\n\t\tremoveDraftRow,\n\t\tsyncDraftRowsWithMeta,\n\t\tsetDraftRowStatus,\n\t} = useDraftRows({\n\t\ttableKey,\n\t\tserverRows: normalizedServerData as any[],\n\t\thasCompletedInitialLoad,\n\t});\n\n\tconst serverRowCount = infiniteScroll ? totalCount : normalizedServerData.length;\n\n\tconst draftDataRows = useMemo(() => {\n\t\tif (!draftRows.length) return [] as SheetsRow[];\n\t\treturn draftRows.map((draft) => {\n\t\t\tconst row = { ...draft.values } as SheetsRow;\n\t\t\treturn attachDraftMeta(row, {\n\t\t\t\tisDraft: true,\n\t\t\t\tdraftRowId: draft.id,\n\t\t\t\tstatus: draft.status,\n\t\t\t\terrors: draft.errors,\n\t\t\t});\n\t\t});\n\t}, [draftRows]);\n\n\t// ============== INFINITE SCROLL: Virtual rows array ==============\n\t// Create a proxy array for infinite scroll mode that uses getRowAtIndex and appends draft rows.\n\tconst infiniteRowsProxy = useMemo<SheetsRow[]>(() => {\n\t\tif (!infiniteScroll) return [];\n\n\t\t// Create an array-like object with a Proxy to intercept index access\n\t\tconst handler: ProxyHandler<any[]> = {\n\t\t\tget(target, prop) {\n\t\t\t\t// Handle array methods and properties\n\t\t\t\tif (prop === 'length') {\n\t\t\t\t\treturn serverRowCount + draftDataRows.length;\n\t\t\t\t}\n\t\t\t\tif (prop === Symbol.iterator) {\n\t\t\t\t\treturn function* () {\n\t\t\t\t\t\tconst len = serverRowCount + draftDataRows.length;\n\t\t\t\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\t\t\t\tif (i < serverRowCount) {\n\t\t\t\t\t\t\t\tyield infiniteGridData.getRowAtIndex(i);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tyield draftDataRows[i - serverRowCount];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\t// Handle numeric indices\n\t\t\t\tif (typeof prop === 'string' && !isNaN(Number(prop))) {\n\t\t\t\t\tconst index = Number(prop);\n\t\t\t\t\tif (index < serverRowCount) {\n\t\t\t\t\t\treturn infiniteGridData.getRowAtIndex(index);\n\t\t\t\t\t}\n\t\t\t\t\treturn draftDataRows[index - serverRowCount];\n\t\t\t\t}\n\t\t\t\t// Delegate to target for other properties\n\t\t\t\treturn Reflect.get(target, prop);\n\t\t\t},\n\t\t};\n\n\t\t// Single localized cast: the Proxy intercepts numeric index + length access to\n\t\t// surface server rows (via getRowAtIndex) and appended draft rows as SheetsRow,\n\t\t// so downstream `combinedRows[i]` reads are SheetsRow with no per-use cast.\n\t\treturn new Proxy([], handler) as unknown as SheetsRow[];\n\t}, [infiniteScroll, infiniteGridData, serverRowCount, draftDataRows]);\n\n\t// Choose the appropriate rows array based on mode\n\tconst combinedRows: SheetsRow[] = infiniteScroll ? infiniteRowsProxy : paginatedCombinedRows;\n\n\tconst draftRowIndices = useMemo(() => {\n\t\tif (!draftDataRows.length) return [] as number[];\n\t\tif (infiniteScroll) {\n\t\t\treturn draftDataRows.map((_, index) => serverRowCount + index);\n\t\t}\n\t\treturn paginatedDraftRowIndices;\n\t}, [draftDataRows, infiniteScroll, paginatedDraftRowIndices, serverRowCount]);\n\n\tconst fieldMetaByKey = useMemo(() => mapFromFieldMetaMap(fieldMetaMap), [fieldMetaMap]);\n\n\t// Build columns with actual data\n\t// In infinite scroll mode, check if we have initial data\n\tconst hasServerRows = infiniteScroll ? infiniteGridData.hasInitialData : normalizedServerData.length > 0;\n\n\tconst { columns: baseColumns, columnKeys } = useDataGridColumns(\n\t\ttableName,\n\t\thasServerRows ? combinedRows : undefined,\n\t);\n\n\tconst gridColumnKeys = useMemo(() => {\n\t\tif (!hasDraftRows) return columnKeys;\n\t\treturn [...columnKeys, DRAFT_ACTION_COLUMN_KEY];\n\t}, [columnKeys, hasDraftRows]);\n\n\t// Pagination helpers\n\tconst totalPages = Math.max(1, Math.ceil((totalCount || 0) / pageSize));\n\tuseEffect(() => {\n\t\tgridActions.resetPageIfNeeded(totalPages);\n\t}, [totalPages, gridActions]);\n\n\t// Apply custom widths and sort indicators to columns\n\tconst columns = useMemo<RelationGridColumn[]>(() => {\n\t\tconst sortedColId = gridState.sorting.id;\n\t\tconst isDesc = gridState.sorting.desc;\n\n\t\tconst mapped = baseColumns.map((col) => {\n\t\t\tconst isSorted = col.id === sortedColId;\n\t\t\t// Append sort indicator to title if this column is sorted\n\t\t\tconst sortIndicator = isSorted ? (isDesc ? ' ↓' : ' ↑') : '';\n\t\t\treturn {\n\t\t\t\t...col,\n\t\t\t\ttitle: col.title + sortIndicator,\n\t\t\t\twidth: gridState.columnWidths.get(col.id || '') ?? col.width,\n\t\t\t};\n\t\t});\n\n\t\tif (hasDraftRows) {\n\t\t\tmapped.push({\n\t\t\t\tid: DRAFT_ACTION_COLUMN_KEY,\n\t\t\t\ttitle: '',\n\t\t\t\twidth: gridState.columnWidths.get(DRAFT_ACTION_COLUMN_KEY) ?? 132,\n\t\t\t});\n\t\t}\n\n\t\treturn mapped;\n\t}, [baseColumns, gridState.columnWidths, gridState.sorting, hasDraftRows]);\n\n\t// Handle row selection\n\tuseEffect(() => {\n\t\tif (!onRowSelect || !gridState.gridSelection) return;\n\t\tconst selectedIndices = gridState.gridSelection.rows.toArray();\n\t\tconst selected = selectedIndices.map((i: number) => combinedRows[i]).filter(Boolean);\n\t\t// The grid's rows ARE the consumer's row type, so widen SheetsRow[] -> TRow[].\n\t\tonRowSelect(selected as TRow[]);\n\t}, [gridState.gridSelection, combinedRows, onRowSelect]);\n\n\t// ============== RELATION INFO (store-derived) ==============\n\t// The store owns relation metadata; ensure it for this table once and read the\n\t// per-field map. Used by the native content resolver + draft/relation routing.\n\tconst ensureRelationInfo = useSheetsStore((st) => st.ensureRelationInfo);\n\tconst relationInfoByFieldFromStore = useSheetsStore((st) =>\n\t\ttableName ? st.relationInfoMapCache[tableName] : undefined,\n\t);\n\tconst relationInfoByField = relationInfoByFieldFromStore ?? EMPTY_RELATION_INFO_BY_FIELD;\n\tuseEffect(() => {\n\t\tif (!tableName) return;\n\t\tensureRelationInfo(tableName, filterMeta);\n\t}, [tableName, filterMeta, ensureRelationInfo]);\n\n\tconst relationInfoObject = useMemo(() => mapFromRelationInfoMap(relationInfoByField), [relationInfoByField]);\n\n\t// Native DOM content resolver (mirrors the canvas getCellContent routing → SheetsCell).\n\tconst { getSheetsCell: getSheetsCellContent } = useSheetsContent({\n\t\tdata: combinedRows,\n\t\tcolumnKeys: gridColumnKeys,\n\t\tfieldMetaMap,\n\t\tregistry: cellRegistry,\n\t\ttableName,\n\t\toptions: { relationChipLimit, relationLabelMaxLength },\n\t\trelationInfoByField,\n\t\tmeta: filterMeta,\n\t\tserverRowsReadOnly: !canUpdate,\n\t\tserverReadOnlyFields: primaryKeyFields,\n\t\tgetRowIdentifier,\n\t\tsupportsScalarSelfCommit,\n\t});\n\n\tconst effectiveColumnOrder = useMemo(() => {\n\t\tif (columnKeys.length > 0) return columnKeys;\n\t\treturn Object.keys(fieldMetaByKey);\n\t}, [columnKeys, fieldMetaByKey]);\n\n\tconst metaSignature = useMemo(\n\t\t() => computeDraftMetaSignature(effectiveColumnOrder, fieldMetaByKey, relationInfoObject),\n\t\t[effectiveColumnOrder, fieldMetaByKey, relationInfoObject],\n\t);\n\n\tconst allowedColumns = useMemo(() => {\n\t\tconst tableFields = tableMeta?.fields as { name: string }[] | undefined;\n\t\treturn tableFields ? new Set(tableFields.map((field) => field.name).filter(Boolean) as string[]) : undefined;\n\t}, [tableMeta?.fields]);\n\n\tuseEffect(() => {\n\t\tif (!effectiveColumnOrder.length) return;\n\t\tsyncDraftRowsWithMeta({\n\t\t\ttableKey,\n\t\t\tcolumnOrder: effectiveColumnOrder,\n\t\t\tfieldMetaByKey,\n\t\t\trelationInfoByKey: relationInfoObject,\n\t\t\tmetaVersion: metaSignature,\n\t\t});\n\t}, [effectiveColumnOrder, fieldMetaByKey, relationInfoObject, metaSignature, syncDraftRowsWithMeta, tableKey]);\n\n\t/**\n\t * Unified optimistic update handler for overlay editors. Editors that handle\n\t * mutations internally (RelationEditor, ImageEditor, etc.) call this callback with\n\t * a patch to update the grid cache without full refetch. The DOM grid re-renders\n\t * reactively off `combinedRows`, so no surgical per-cell repaint is needed.\n\t */\n\tconst handleEditorSaveComplete = useCallback(\n\t\t(colKey: string, rowIndex: number, patch: Record<string, unknown>) => {\n\t\t\tvoid colKey;\n\t\t\tconst rowData = combinedRows[rowIndex];\n\n\t\t\t// Draft row: update draft store directly\n\t\t\tconst dm = getDraftMeta(rowData);\n\t\t\tif (dm) {\n\t\t\t\tfor (const [key, value] of Object.entries(patch)) {\n\t\t\t\t\tupdateDraftCell({ tableKey, draftRowId: dm.draftRowId, columnKey: key, value });\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Server row: update infinite scroll cache (paginated handled by React Query)\n\t\t\tif (!infiniteScroll) return;\n\n\t\t\t// Apply optimistic update to infinite scroll cache; self-heal on a cache\n\t\t\t// miss (patch targeted a not-yet-cached page) by falling back to a refetch.\n\t\t\tconst ok = infiniteGridData.updateRowAtIndex(rowIndex, patch);\n\t\t\tif (!ok) infiniteGridData.invalidate();\n\t\t},\n\t\t[combinedRows, infiniteScroll, infiniteGridData, updateDraftCell, tableKey],\n\t);\n\n\t// Ref to hold submitDraftRowForEditor - populated after useDraftSubmission\n\t// This breaks the circular dependency: editors need the function, but useDraftSubmission\n\t// needs hasDraftSelection which comes from useGridSelectionState which needs combinedRows\n\tconst submitDraftRowForEditorRef = useRef<((draftRowId: string) => Promise<DraftSubmitResult>) | null>(null);\n\n\tconst handleSubmitDraftRowForEditor = useCallback(\n\t\tasync (draftRowId: string): Promise<DraftSubmitResult> => {\n\t\t\tif (!submitDraftRowForEditorRef.current) {\n\t\t\t\treturn { createdRow: null };\n\t\t\t}\n\t\t\treturn submitDraftRowForEditorRef.current(draftRowId);\n\t\t},\n\t\t[],\n\t);\n\n\t// Memoize feedback callbacks for grid operations\n\tconst operationFeedback = useMemo(\n\t\t() => ({\n\t\t\tonStart: startOperation,\n\t\t\tonProgress: updateOperationProgress,\n\t\t\tonComplete: completeOperation,\n\t\t}),\n\t\t[startOperation, updateOperationProgress, completeOperation],\n\t);\n\n\tconst gridOpsOptions = useMemo(\n\t\t() => ({\n\t\t\tonRemoveDraftRow: (draftRowId: string) => removeDraftRow(tableKey, draftRowId),\n\t\t\tgetRowIdentifier,\n\t\t\tcanDeleteServerRows: canDelete,\n\t\t\tfeedback: operationFeedback,\n\t\t}),\n\t\t[removeDraftRow, tableKey, getRowIdentifier, canDelete, operationFeedback],\n\t);\n\n\tconst { deleteSelected: baseDeleteSelected } = useGridOperations(\n\t\tcombinedRows,\n\t\tdeleteRow,\n\t\tgridState.gridSelection,\n\t\t() => gridActions.setGridSelection(undefined),\n\t\t{\n\t\t\t...gridOpsOptions,\n\t\t\tonAfterServerDeletes: infiniteScroll ? infiniteGridData.invalidate : undefined,\n\t\t},\n\t);\n\n\t// Wrap the delete handler to emit an observational row:delete event with the\n\t// selected-row count, then delegate to the real deletion logic.\n\tconst deleteSelected = useCallback(async () => {\n\t\tconst count = gridState.gridSelection?.rows.length ?? 0;\n\t\temit('row:delete', { count });\n\t\tawait baseDeleteSelected();\n\t}, [baseDeleteSelected, emit, gridState.gridSelection]);\n\n\t// Infinite-mode optimistic cache patch, handed to `useCellEditing` so a server-row\n\t// edit flips the cell BEFORE the `update` round-trip. Snapshots the prior values for\n\t// the patched keys and returns a revert thunk replayed only if the mutation rejects.\n\t// A cache miss (unloaded page) self-heals via `invalidate()`. Paginated mode returns\n\t// undefined here — its optimism lives in the update mutation's onMutate (use-table.ts).\n\tconst applyOptimisticCellPatch = useCallback(\n\t\t(rowIndex: number, patch: Record<string, unknown>): (() => void) | void => {\n\t\t\tif (!infiniteScroll) return;\n\t\t\tconst current = infiniteGridData.getRowAtIndex(rowIndex) as Record<string, unknown> | null;\n\t\t\tconst ok = infiniteGridData.updateRowAtIndex(rowIndex, patch);\n\t\t\tif (!ok) {\n\t\t\t\tinfiniteGridData.invalidate();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst snapshot: Record<string, unknown> = {};\n\t\t\tfor (const key of Object.keys(patch)) snapshot[key] = current ? current[key] : undefined;\n\t\t\treturn () => {\n\t\t\t\tconst reverted = infiniteGridData.updateRowAtIndex(rowIndex, snapshot);\n\t\t\t\tif (!reverted) infiniteGridData.invalidate();\n\t\t\t};\n\t\t},\n\t\t[infiniteScroll, infiniteGridData],\n\t);\n\n\tconst editCell = useCellEditing({\n\t\tcombinedRows,\n\t\tfieldMetaMap,\n\t\trelationInfoByField,\n\t\tupdateDraftCell,\n\t\ttableKey,\n\t\tupdate,\n\t\tgetRowIdentifier,\n\t\treadOnlyFields: primaryKeyFields,\n\t\tcanUpdate,\n\t\tonCellEdit,\n\t\tapplyOptimisticPatch: applyOptimisticCellPatch,\n\t});\n\n\t// History (undo/redo) for server-row value writes. Draft edits are NOT recorded.\n\tconst history = useUndoRedo();\n\n\t// Re-sync a canonical server row over the optimistic patch after the mutation\n\t// resolves (infinite mode only; paginated reconciles via React Query).\n\tconst resyncRow = useCallback(\n\t\t(rowIndex: number, updatedRow: Record<string, unknown>) => {\n\t\t\tif (!infiniteScroll) return;\n\t\t\tconst ok = infiniteGridData.updateRowAtIndex(rowIndex, updatedRow);\n\t\t\tif (!ok) infiniteGridData.invalidate();\n\t\t},\n\t\t[infiniteScroll, infiniteGridData],\n\t);\n\n\t// BATCHED commit primitive — the single server-row value-write path (paste / fill /\n\t// bulk AND, routed below, the single cell). Coalesces optimistic patches + server\n\t// mutations per row and records an undoable HistoryEntry (unless opts.record===false).\n\tconst commitCells = useBatchCommit({\n\t\tcombinedRows,\n\t\tfieldMetaMap,\n\t\trelationInfoByField,\n\t\tupdate,\n\t\tgetRowIdentifier,\n\t\treadOnlyFields: primaryKeyFields,\n\t\tcanUpdate,\n\t\tapplyOptimisticPatch: applyOptimisticCellPatch,\n\t\tresyncRow,\n\t\teditCell,\n\t\tonCellEdit,\n\t\trecord: history.record,\n\t});\n\n\t// @internal NATIVE value-commit for the TanStack DOM grid's portal editors.\n\t// Maps a (rowIndex, colKey, rawValue) commit straight onto the native `editCell`\n\t// (draft `updateDraftCell` / server mutation) — the raw value flows through with\n\t// NO glide cell round-trip (this is what keeps a boolean `false` as `false`). For\n\t// server edits `editCell` already applied the OPTIMISTIC infinite-cache patch before\n\t// awaiting the mutation (and reverted it on failure); here we only re-sync the\n\t// canonical server row when it comes back, then emit the observational `cell:edit`.\n\t// The DOM grid re-renders reactively from `combinedRows`.\n\tconst commitCellValue = useCallback(\n\t\t(rowIndex: number, colKey: string, nextValue: unknown): void => {\n\t\t\tvoid (async () => {\n\t\t\t\ttry {\n\t\t\t\t\t// Single-cell edits route through the SAME batched primitive so a normal cell\n\t\t\t\t\t// edit becomes undoable (server rows) — coercion / readonly / optimistic patch\n\t\t\t\t\t// / re-sync all live inside commitCells (draft rows take its per-cell branch).\n\t\t\t\t\tconst isDraft = !!getDraftMeta(combinedRows[rowIndex]);\n\t\t\t\t\tconst { applied } = await commitCells([{ rowIndex, colKey, value: nextValue }]);\n\n\t\t\t\t\t// Observational: a real cell edit landed — skip no-ops (applied 0 + non-draft).\n\t\t\t\t\tif (applied > 0 || isDraft) {\n\t\t\t\t\t\temit('cell:edit', { field: colKey, rowIndex, target: isDraft ? 'draft' : 'server' });\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconst description = e instanceof Error ? e.message : 'Failed to update cell';\n\t\t\t\t\ttoast.error({ message: 'Update failed', description });\n\t\t\t\t\tsheetsLogger().error('Cell edit error:', e);\n\t\t\t\t\tconfig.onError?.(e, { source: 'mutation', tableName });\n\t\t\t\t}\n\t\t\t})();\n\t\t},\n\t\t[commitCells, combinedRows, config, tableName, emit],\n\t);\n\n\t// @internal NATIVE patch-commit for self-committing DOM portal editors (relation/\n\t// image). These editors mutate server-side themselves, then push a MULTI-field\n\t// patch — routes straight through the EXISTING `handleEditorSaveComplete` (draft\n\t// store update / infinite-cache patch), using the FIRST patch key as the primary colKey.\n\tconst commitCellPatch = useCallback(\n\t\t(rowIndex: number, patch: Record<string, unknown>): void => {\n\t\t\tconst primaryColKey = Object.keys(patch)[0];\n\t\t\tif (!primaryColKey) return;\n\t\t\thandleEditorSaveComplete(primaryColKey, rowIndex, patch);\n\t\t},\n\t\t[handleEditorSaveComplete],\n\t);\n\n\t// @internal NATIVE data-invalidate for self-committing DOM portal editors. Mirrors\n\t// the canvas wiring: infinite mode refetches via the React Query cache; paginated\n\t// invalidation is already handled by React Query in use-table, so this is a no-op there.\n\tconst invalidateData = useCallback(() => {\n\t\tif (infiniteScroll) infiniteGridData.invalidate();\n\t}, [infiniteScroll, infiniteGridData]);\n\n\tconst handleRowAppended = useCallback(async () => {\n\t\tif (!canCreate) return undefined;\n\t\tif (draftRows.length > 0) {\n\t\t\treturn serverRowCount + draftRows.length - 1;\n\t\t}\n\n\t\t// Silently skip if metadata isn't ready - this is a transient state\n\t\tif (!effectiveColumnOrder.length) return undefined;\n\n\t\tcreateDraftRow({\n\t\t\ttableKey,\n\t\t\tcolumnOrder: effectiveColumnOrder,\n\t\t\tfieldMetaByKey: fieldMetaByKey as Record<string, any>,\n\t\t\trelationInfoByKey: relationInfoObject,\n\t\t\tmetaVersion: metaSignature,\n\t\t});\n\n\t\tconst rowIndex = serverRowCount + draftRows.length;\n\t\temit('row:create', { rowIndex });\n\t\treturn rowIndex;\n\t}, [\n\t\tcreateDraftRow,\n\t\teffectiveColumnOrder,\n\t\tfieldMetaByKey,\n\t\trelationInfoObject,\n\t\tmetaSignature,\n\t\ttableKey,\n\t\tdraftRows,\n\t\tserverRowCount,\n\t\tcanCreate,\n\t\temit,\n\t]);\n\n\tconst { selectedRowCount, selectedDraftRowEntries, hasDraftSelection } = useGridSelectionState({\n\t\tgridSelection: gridState.gridSelection,\n\t\tcombinedRows,\n\t\tdraftRowsTable,\n\t});\n\n\tconst {\n\t\tisSubmittingDrafts,\n\t\tsubmitDraftButtonDisabled,\n\t\tsubmitDraftLabel,\n\t\thandleSubmitDraftRows,\n\t\tsubmitDraftRowForEditor,\n\t} = useDraftSubmission({\n\t\ttableKey,\n\t\tdraftRowsTable,\n\t\tselectedDraftRowEntries,\n\t\thasDraftSelection,\n\t\tcreate,\n\t\tremoveDraftRow,\n\t\tsetDraftRowStatus,\n\t\tclearSelection: () => gridActions.setGridSelection(undefined),\n\t\tallowedColumns,\n\t\trelationInfoByKey: relationInfoObject,\n\t\tfieldMetaByKey: fieldMetaByKey as Record<string, any>,\n\t\tonSubmittedSuccessfully: infiniteScroll ? infiniteGridData.invalidate : undefined,\n\t\tfeedback: operationFeedback,\n\t});\n\n\t// Populate the ref for editor access (breaks circular dependency)\n\tsubmitDraftRowForEditorRef.current = submitDraftRowForEditor;\n\n\t// Compute sortable columns (exclude relation fields - only simple data types are sortable)\n\tconst sortableColumns = useMemo(() => {\n\t\treturn new Set(gridColumnKeys.filter((key) => !relationFieldNames.has(key)));\n\t}, [gridColumnKeys, relationFieldNames]);\n\n\t// Header click handler for sorting (only allows sorting on non-relation columns; the\n\t// draft-action column is excluded because it is never in `sortableColumns`).\n\tconst onHeaderClicked = useMemo(\n\t\t() => createHeaderClickHandler(gridColumnKeys, gridActions.toggleSorting, sortableColumns),\n\t\t[gridColumnKeys, gridActions.toggleSorting, sortableColumns],\n\t);\n\n\t// Emit sort:change whenever the resolved sort state transitions. Watching the\n\t// state (rather than the toggle call) reflects the real outcome and covers any\n\t// path that mutates sorting. Skip the initial mount so we don't fire on render.\n\tconst didMountSortRef = useRef(false);\n\tuseEffect(() => {\n\t\tif (!didMountSortRef.current) {\n\t\t\tdidMountSortRef.current = true;\n\t\t\treturn;\n\t\t}\n\t\temit('sort:change', {\n\t\t\tfield: gridState.sorting.id || null,\n\t\t\tdirection: gridState.sorting.id ? (gridState.sorting.desc ? 'desc' : 'asc') : null,\n\t\t});\n\t}, [gridState.sorting, emit]);\n\n\t// ============== INFINITE SCROLL: onVisibleRegionChanged handler ==============\n\t// Translate the DOM viewport's inclusive {startIndex,endIndex} window into the\n\t// prefetch range the infinite source loads (clamped to the server row count).\n\tconst handleVisibleRegionChanged = useCallback(\n\t\t(range: VisibleRowRange) => {\n\t\t\tif (!infiniteScroll) return;\n\t\t\tif (serverRowCount <= 0) return;\n\n\t\t\tconst start = Math.max(0, Math.min(range.startIndex, serverRowCount - 1));\n\t\t\tconst end = Math.max(start, Math.min(range.endIndex, serverRowCount - 1));\n\t\t\tinfiniteGridData.onVisibleRegionChanged({ startIndex: start, endIndex: end });\n\t\t},\n\t\t[infiniteScroll, infiniteGridData, serverRowCount],\n\t);\n\n\tconst setGridSelectionForControls = useCallback(\n\t\t(selection: SheetsSelection | null) => {\n\t\t\tgridActions.setGridSelection(selection ?? undefined);\n\t\t},\n\t\t[gridActions],\n\t);\n\n\t// Build fieldTypeMap for filter controls\n\tconst fieldTypeMap = useMemo(() => {\n\t\tconst map: Record<string, { gqlType: string; isArray: boolean }> = {};\n\t\tfieldMetaMap.forEach((meta, key) => {\n\t\t\tif (meta?.type?.gqlType) {\n\t\t\t\tmap[key] = { gqlType: meta.type.gqlType, isArray: !!meta.type.isArray };\n\t\t\t}\n\t\t});\n\t\treturn map;\n\t}, [fieldMetaMap]);\n\n\tconst applyFilters = useCallback(() => {\n\t\tgridActions.setFiltersOpen(false);\n\t\temit('filter:apply', { conditionCount: countConditions(gridState.filterTree) });\n\t}, [gridActions, emit, gridState.filterTree]);\n\n\t// Compute frozen columns: id column if present\n\tconst frozenCount = useMemo(() => {\n\t\tconst idFrozen = columnKeys[0] === 'id' ? 1 : 0;\n\t\treturn idFrozen; // Row markers are separate\n\t}, [columnKeys]);\n\n\t// Unified, mode-aware refetch. Shared by the load-state retry path and the\n\t// imperative handle in the Sheets shell.\n\tconst refetch = useCallback(() => {\n\t\tif (infiniteScroll) {\n\t\t\tinfiniteGridData.invalidate();\n\t\t} else {\n\t\t\tvoid dataLoadingResult.contextValue.refetch?.();\n\t\t}\n\t}, [infiniteScroll, infiniteGridData, dataLoadingResult.contextValue]);\n\n\t// Pagination setter that mirrors the default chrome behavior (emit page:change).\n\tconst setPageIndex = useCallback(\n\t\t(updater: number | ((prev: number) => number)) => {\n\t\t\tconst next = typeof updater === 'function' ? updater(gridState.pageIndex) : updater;\n\t\t\tgridActions.setPageIndex(next);\n\t\t\temit('page:change', { pageIndex: next });\n\t\t},\n\t\t[gridActions, gridState.pageIndex, emit],\n\t);\n\n\t// Loaded successfully but no server rows and nothing drafted yet, with no active filter.\n\tconst isEmpty =\n\t\thasCompletedInitialLoad &&\n\t\tserverRowCount === 0 &&\n\t\tdraftRows.length === 0 &&\n\t\tcountConditions(gridState.filterTree) === 0;\n\n\treturn {\n\t\t// -- Stable headless surface (see UseSheetsResult) --\n\t\tcolumns,\n\t\trowCount: combinedRows.length,\n\t\tdraft: {\n\t\t\thasDrafts: hasDraftRows,\n\t\t\tappendRow: handleRowAppended,\n\t\t\tsubmitDrafts: handleSubmitDraftRows,\n\t\t\tdeleteSelected,\n\t\t},\n\t\tselection: {\n\t\t\tgridSelection: gridState.gridSelection,\n\t\t\tsetGridSelection: gridActions.setGridSelection,\n\t\t\tsetActiveCell: gridActions.setActiveCell,\n\t\t\tmoveActive: gridActions.moveActiveCell,\n\t\t},\n\t\tpagination: {\n\t\t\tpageIndex: gridState.pageIndex,\n\t\t\tpageCount: totalPages,\n\t\t\tsetPageIndex,\n\t\t},\n\t\tisInitialLoading,\n\t\tdataError,\n\t\thasCompletedInitialLoad,\n\t\tisEmpty,\n\t\trefetch,\n\n\t\t// -- Internal chrome bindings (not a stable API) --\n\t\t_shell: {\n\t\t\tcombinedRows,\n\t\t\tcolumnKeys,\n\t\t\ttotalCount,\n\t\t\tserverRowCount,\n\t\t\tdraftRowCount: draftRows.length,\n\t\t\tinfiniteScroll,\n\t\t\tfilterTree: gridState.filterTree,\n\t\t\tfiltersOpen: gridState.filtersOpen,\n\t\t\tsetFilterTree: gridActions.setFilterTree,\n\t\t\tsetFiltersOpen: gridActions.setFiltersOpen,\n\t\t\tclearAllFilters: gridActions.clearAllFilters,\n\t\t\tapplyFilters,\n\t\t\tfieldTypeMap,\n\t\t\tsetGridSelectionForControls,\n\t\t\tonHeaderClicked,\n\t\t\tonVisibleRegionChanged: handleVisibleRegionChanged,\n\t\t\tsorting: gridState.sorting,\n\t\t\tcolumnWidths: gridState.columnWidths,\n\t\t\tresizeColumn: gridActions.resizeColumn,\n\t\t\tfrozenCount,\n\t\t\tselectedRowCount,\n\t\t\tcanCreate,\n\t\t\tcanUpdate,\n\t\t\tcanDelete,\n\t\t\treadOnlyReason,\n\t\t\tgetRowId,\n\t\t\tisSubmittingDrafts,\n\t\t\tsubmitDraftButtonDisabled,\n\t\t\tsubmitDraftLabel,\n\t\t\tgetSheetsCellContent,\n\t\t\tcellRegistry,\n\t\t\tcommitCellValue,\n\t\t\tcommitCells,\n\t\t\tcommitCellPatch,\n\t\t\tsubmitDraftRow: handleSubmitDraftRowForEditor,\n\t\t\tinvalidateData,\n\t\t\tundo: history.undo,\n\t\t\tredo: history.redo,\n\t\t\tcanUndo: history.canUndo,\n\t\t\tcanRedo: history.canRedo,\n\t\t\temit,\n\t\t},\n\t};\n}\n","/**\n * Build data grid columns that understand relation metadata\n */\nimport { useCallback, useMemo } from 'react';\n\nimport { isImageField, resolveCellType, type FieldMetadata } from '../cell-types/cell-type-resolver';\nimport { getColumnWidthByMeta } from '../grid/sheets.utils';\n\nimport { useRelationMetadataCache, type RelationMetadata } from './use-relation-metadata-cache';\n\ntype RelationKind = 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';\n\n/** Native column descriptor — key/title/width, mappable 1:1 to {@link SheetsColumnDescriptor}. */\nexport interface RelationGridColumn {\n\tid: string;\n\ttitle: string;\n\twidth: number;\n}\n\n/**\n * Relation-aware column info with simple error handling\n */\nexport interface RelationColumnInfo {\n\tcolumns: RelationGridColumn[];\n\tcolumnKeys: string[];\n\trelationMetadata: Record<string, RelationMetadata>;\n\tmetaFields?: FieldMetadata[];\n\thasRelationErrors: boolean;\n\trelationCount: number;\n\t// Helper functions (backward compatible)\n\tisImageField: (fieldMeta: FieldMetadata | undefined, fieldName?: string) => boolean;\n\tfindImageColumnKey: (columnKeys: string[], fieldMetaMap: Map<string, unknown>, currentColKey?: string) => string;\n\tgetRelationKind: (fieldName: string) => RelationKind | null;\n\tisRelationField: (fieldName: string) => boolean;\n\tinvalidateRelationCache: () => Promise<void>;\n\t// For backward compatibility\n\trelationTypeByField: Map<string, RelationKind>;\n}\n\n/**\n * Create data grid columns with relation metadata baked in\n */\nexport function useRelationColumns(tableName?: string, rows?: unknown[]): RelationColumnInfo {\n\tconst { relationMetadata, tableRelations, cacheState, getRelationKind, isRelationField, invalidateRelationCache } =\n\t\tuseRelationMetadataCache(tableName);\n\n\tconst metaFields = useMemo<FieldMetadata[] | undefined>(() => {\n\t\treturn tableRelations?.fields.map((field) => ({\n\t\t\tname: field.name,\n\t\t\ttype: field.type,\n\t\t}));\n\t}, [tableRelations]);\n\n\tconst metaFieldByName = useMemo(() => {\n\t\tconst map = new Map<string, FieldMetadata>();\n\t\tfor (const field of metaFields ?? []) {\n\t\t\tif (field?.name) map.set(field.name, field);\n\t\t}\n\t\treturn map;\n\t}, [metaFields]);\n\n\tconst baseFieldNames = useMemo(() => {\n\t\tif (rows && rows.length > 0) {\n\t\t\tconst sample = rows[0] ?? {};\n\t\t\treturn Object.keys(sample);\n\t\t}\n\n\t\tif (metaFields?.length) {\n\t\t\tconst scalarNames = metaFields.map((field) => field?.name).filter((name): name is string => Boolean(name));\n\t\t\tconst relationNames: string[] = [];\n\t\t\trelationMetadata.forEach((rel) => {\n\t\t\t\tif (rel.sourceField === 'relation') relationNames.push(rel.fieldName);\n\t\t\t});\n\t\t\treturn Array.from(new Set([...scalarNames, ...relationNames]));\n\t\t}\n\n\t\treturn [] as string[];\n\t}, [rows, metaFields, relationMetadata]);\n\n\t// Extract column keys from data\n\tconst columnKeys: string[] = useMemo(() => {\n\t\tif (baseFieldNames.length === 0) return [];\n\t\tconst keys = [...baseFieldNames];\n\n\t\tconst belongsToForeignKeysToHide = new Set<string>();\n\t\tconst foreignKeysByRelationField = new Map<string, string[]>();\n\n\t\trelationMetadata.forEach((rel) => {\n\t\t\tif (rel.sourceField === 'foreignKey' && rel.relationFieldName) {\n\t\t\t\tconst existing = foreignKeysByRelationField.get(rel.relationFieldName);\n\t\t\t\tif (existing) {\n\t\t\t\t\texisting.push(rel.fieldName);\n\t\t\t\t} else {\n\t\t\t\t\tforeignKeysByRelationField.set(rel.relationFieldName, [rel.fieldName]);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\trelationMetadata.forEach((rel) => {\n\t\t\tif (rel.sourceField !== 'relation' || rel.relationKind !== 'belongsTo' || !rel.relationFieldName) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst foreignKeyEntries = foreignKeysByRelationField.get(rel.relationFieldName);\n\t\t\tif (foreignKeyEntries?.length) {\n\t\t\t\tforeignKeyEntries.forEach((fieldName) => {\n\t\t\t\t\tbelongsToForeignKeysToHide.add(fieldName);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\tconst filteredKeys = keys.filter((key) => !belongsToForeignKeysToHide.has(key));\n\n\t\t// Ensure id comes first if present\n\t\tconst idIdx = filteredKeys.indexOf('id');\n\t\tif (idIdx > -1) {\n\t\t\tfilteredKeys.splice(idIdx, 1);\n\t\t\tfilteredKeys.unshift('id');\n\t\t}\n\t\treturn filteredKeys;\n\t}, [baseFieldNames, relationMetadata]);\n\n\t// Create relation metadata map for quick lookup\n\tconst relationMetadataMap = useMemo(() => {\n\t\tconst map: Record<string, RelationMetadata> = {};\n\n\t\trelationMetadata.forEach((rel) => {\n\t\t\tmap[rel.fieldName] = rel;\n\t\t});\n\n\t\treturn map;\n\t}, [relationMetadata]);\n\n\t// Table fields metadata\n\t// Generate columns with improved error handling\n\tconst columns: RelationGridColumn[] = useMemo(() => {\n\t\treturn columnKeys.map((fieldName) => {\n\t\t\tconst metaField = metaFieldByName.get(fieldName);\n\t\t\tconst relationInfo = relationMetadataMap[fieldName];\n\t\t\tconst relationDisplayField = relationInfo?.relationFieldName || undefined;\n\t\t\tconst isForeignKeyRelationField = relationInfo?.sourceField === 'foreignKey';\n\n\t\t\t// Use centralized cell type resolution\n\t\t\tconst resolution = resolveCellType(fieldName, metaField);\n\t\t\tconst cellType = resolution.cellType;\n\n\t\t\t// For relation fields, use relation kind as type label\n\t\t\tconst typeLabel = relationInfo?.relationKind\n\t\t\t\t? relationInfo.relationKind\n\t\t\t\t: metaField\n\t\t\t\t\t? metaField.type?.pgAlias || metaField.type?.pgType || metaField.type?.gqlType\n\t\t\t\t\t: cellType;\n\n\t\t\tlet headerName = fieldName;\n\t\t\tif (relationInfo?.displayName) {\n\t\t\t\theaderName = relationInfo.displayName;\n\t\t\t} else if (relationDisplayField) {\n\t\t\t\theaderName = relationDisplayField;\n\t\t\t} else if (isForeignKeyRelationField) {\n\t\t\t\tconst stripped = fieldName.replace(/Id$/i, '');\n\t\t\t\theaderName = stripped.length > 0 ? stripped : fieldName;\n\t\t\t}\n\n\t\t\tconst titleRaw = typeLabel ? `${headerName} (${typeLabel})` : headerName;\n\n\t\t\treturn {\n\t\t\t\tid: fieldName,\n\t\t\t\ttitle: titleRaw,\n\t\t\t\twidth: metaField ? getColumnWidthByMeta(metaField) : 150,\n\t\t\t} satisfies RelationGridColumn;\n\t\t});\n\t}, [columnKeys, metaFieldByName, relationMetadataMap]);\n\n\t// Helper function using centralized image field detection\n\tconst checkIsImageField = useCallback((fieldMeta: FieldMetadata | undefined, fieldName?: string): boolean => {\n\t\treturn isImageField(fieldMeta, fieldName);\n\t}, []);\n\n\t// Helper function to find the correct column key for image cells\n\tconst findImageColumnKey = useCallback(\n\t\t(columnKeys: string[], fieldMetaMap: Map<string, unknown>, currentColKey?: string): string => {\n\t\t\t// If we already have a reliable column key, use it\n\t\t\tif (currentColKey && currentColKey !== 'id' && fieldMetaMap.has(currentColKey)) {\n\t\t\t\tconst fieldMeta = fieldMetaMap.get(currentColKey) as FieldMetadata | undefined;\n\t\t\t\tif (checkIsImageField(fieldMeta, currentColKey)) {\n\t\t\t\t\treturn currentColKey;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Look through all columns to find image-type fields\n\t\t\tfor (const key of columnKeys) {\n\t\t\t\tconst fieldMeta = fieldMetaMap.get(key) as FieldMetadata | undefined;\n\t\t\t\tif (fieldMeta && checkIsImageField(fieldMeta, key)) {\n\t\t\t\t\treturn key;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Fallback to the current column key or first non-id column\n\t\t\treturn currentColKey || columnKeys.find((k) => k !== 'id') || columnKeys[0] || '';\n\t\t},\n\t\t[checkIsImageField],\n\t);\n\n\t// Create backward compatibility map\n\tconst relationTypeByField = useMemo(() => {\n\t\tconst map = new Map<string, RelationKind>();\n\t\tObject.entries(relationMetadataMap).forEach(([fieldName, info]) => {\n\t\t\tmap.set(fieldName, info.relationKind);\n\t\t});\n\t\treturn map;\n\t}, [relationMetadataMap]);\n\n\treturn {\n\t\tcolumns,\n\t\tcolumnKeys,\n\t\trelationMetadata: relationMetadataMap,\n\t\tmetaFields,\n\t\thasRelationErrors: cacheState.isError,\n\t\trelationCount: cacheState.relationCount,\n\t\tisImageField: checkIsImageField,\n\t\tfindImageColumnKey,\n\t\tgetRelationKind,\n\t\tisRelationField,\n\t\tinvalidateRelationCache,\n\t\trelationTypeByField, // For backward compatibility\n\t};\n}\n\n/**\n * Drop-in replacement for the original useDataGridColumns hook\n * Maintains complete backward compatibility while providing improvements\n */\nexport function useDataGridColumns(tableName?: string, rows: unknown[] = []) {\n\tconst enhanced = useRelationColumns(tableName, rows);\n\n\t// Return exact same interface as original for backward compatibility\n\treturn {\n\t\tcolumns: enhanced.columns,\n\t\tcolumnKeys: enhanced.columnKeys,\n\t\tmetaFields: enhanced.metaFields,\n\t\tisImageField: enhanced.isImageField,\n\t\tfindImageColumnKey: enhanced.findImageColumnKey,\n\t\trelationTypeByField: enhanced.relationTypeByField,\n\t\t// Add new enhanced features for those who want them\n\t\trelationMetadata: enhanced.relationMetadata,\n\t\thasRelationErrors: enhanced.hasRelationErrors,\n\t\trelationCount: enhanced.relationCount,\n\t\tgetRelationKind: enhanced.getRelationKind,\n\t\tisRelationField: enhanced.isRelationField,\n\t\tinvalidateRelationCache: enhanced.invalidateRelationCache,\n\t};\n}\n","import type { CellType } from './types';\n\nimport type { CellPlugin, CellRegistryEntry, CellRenderer } from './types';\n\nclass CellRegistryClass {\n\tprivate entries = new Map<CellType, CellRegistryEntry>();\n\tprivate plugins = new Map<string, CellPlugin>();\n\n\t// Register a cell renderer for a cell type\n\tregister(entry: CellRegistryEntry): void {\n\t\tthis.entries.set(entry.type, entry);\n\t}\n\n\t// Register multiple entries at once\n\tregisterBatch(entries: CellRegistryEntry[]): void {\n\t\tentries.forEach((entry) => this.register(entry));\n\t}\n\n\t// Get cell renderer for a type\n\tget(type: CellType): CellRegistryEntry | undefined {\n\t\treturn this.entries.get(type);\n\t}\n\n\t// Get all registered cell types\n\tgetAll(): CellRegistryEntry[] {\n\t\treturn Array.from(this.entries.values());\n\t}\n\n\t// Get cell component for a type\n\tgetComponent(type: CellType): CellRenderer | undefined {\n\t\tconst entry = this.entries.get(type);\n\t\treturn entry?.component;\n\t}\n\n\t// Find cell entry by match function\n\t// NOTE: Cell type is determined ONLY from schema metadata, never from runtime values\n\tfindByMatch(metadata: {\n\t\tgqlType: string;\n\t\tisArray: boolean;\n\t\tpgAlias?: string | null;\n\t\tpgType?: string | null;\n\t\tsubtype?: string | null;\n\t\tfieldName?: string;\n\t}): CellRegistryEntry | undefined {\n\t\t// Iterate through all entries and find the first one with a matching match function\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.match && entry.match(metadata)) {\n\t\t\t\treturn entry;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Get cell component using match function first, then fallback to type\n\t// NOTE: Cell type is determined ONLY from schema metadata, never from runtime values\n\tgetComponentWithMatch(\n\t\ttype: CellType,\n\t\tmetadata?: {\n\t\t\tgqlType: string;\n\t\t\tisArray: boolean;\n\t\t\tpgAlias?: string | null;\n\t\t\tpgType?: string | null;\n\t\t\tsubtype?: string | null;\n\t\t\tfieldName?: string;\n\t\t},\n\t): CellRenderer | undefined {\n\t\t// First try to find by match function if metadata is provided\n\t\tif (metadata) {\n\t\t\tconst matchedEntry = this.findByMatch(metadata);\n\t\t\tif (matchedEntry) {\n\t\t\t\treturn matchedEntry.component;\n\t\t\t}\n\t\t}\n\n\t\t// Fallback to regular type-based lookup\n\t\treturn this.getComponent(type);\n\t}\n\n\t// Get edit component for a type\n\tgetEditComponent(type: CellType): CellRenderer | undefined {\n\t\tconst entry = this.entries.get(type);\n\t\treturn entry?.editComponent || entry?.component;\n\t}\n\n\t// Check if a type is registered\n\thas(type: CellType): boolean {\n\t\treturn this.entries.has(type);\n\t}\n\n\t// Install a plugin\n\tinstallPlugin(plugin: CellPlugin): void {\n\t\tif (this.plugins.has(plugin.name)) {\n\t\t\tconsole.warn(`Plugin ${plugin.name} is already installed`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Install plugin cells\n\t\tplugin.cells.forEach((cell) => this.register(cell));\n\n\t\t// Run plugin install hook\n\t\tplugin.install?.();\n\n\t\tthis.plugins.set(plugin.name, plugin);\n\t}\n\n\t// Uninstall a plugin\n\tuninstallPlugin(pluginName: string): void {\n\t\tconst plugin = this.plugins.get(pluginName);\n\t\tif (!plugin) {\n\t\t\tconsole.warn(`Plugin ${pluginName} is not installed`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Remove plugin cells\n\t\tplugin.cells.forEach((cell) => this.entries.delete(cell.type));\n\n\t\t// Run plugin uninstall hook\n\t\tplugin.uninstall?.();\n\n\t\tthis.plugins.delete(pluginName);\n\t}\n\n\t// Get installed plugins\n\tgetInstalledPlugins(): CellPlugin[] {\n\t\treturn Array.from(this.plugins.values());\n\t}\n\n\t// Clear all entries (useful for testing)\n\tclear(): void {\n\t\tthis.entries.clear();\n\t\tthis.plugins.clear();\n\t}\n\n\t// Get entries by category\n\tgetByCategory(category: string): CellRegistryEntry[] {\n\t\treturn Array.from(this.entries.values()).filter((entry) => entry.metadata?.category === category);\n\t}\n}\n\n// Export singleton instance\n/**\n * @deprecated since 0.2.0 — pass cell types via <SheetsProvider config={{ plugins }}> or <Sheets cellTypes>. CellRegistry only ever affected detection.\n */\nexport const CellRegistry = new CellRegistryClass();\n\n// Export factory function for testing\nexport function createCellRegistry(): CellRegistryClass {\n\treturn new CellRegistryClass();\n}\n","import { ENHANCED_TYPES, MEDIA_TYPES, STRUCTURED_DATA_TYPES } from './cell-type-groups';\nimport type { CellType, ColumnSchema } from './types';\n\n/**\n * Maps GraphQL field metadata to frontend cell types\n * Uses priority: pgAlias > pgType > gqlType for type determination\n * This is completely backend-agnostic and focuses only on frontend rendering needs\n */\nexport function mapToFrontendCellType(metadata: {\n\tgqlType: string;\n\tisArray: boolean;\n\tpgAlias?: string | null;\n\tpgType?: string | null;\n\tsubtype?: string | null;\n\tencoding?: { kind: string; geometrySubtype?: string | null } | null;\n}): CellType {\n\tconst { gqlType, isArray, pgAlias, pgType } = metadata;\n\n\tconst encodedType = mapEncodingToCellType(metadata.encoding);\n\tif (encodedType) return encodedType;\n\n\t// Priority 1: Use pgAlias if available (most specific)\n\t// This must be checked FIRST, even for arrays, to preserve types like 'array' vs 'text-array'\n\tif (pgAlias) {\n\t\tconst aliasType = mapAliasToCellType(pgAlias);\n\t\tif (aliasType !== 'unknown') return aliasType;\n\t}\n\n\t// Handle arrays after pgAlias check\n\tif (isArray) {\n\t\tconst result = mapGraphQLTypeToCellType(gqlType, isArray, metadata.subtype, null);\n\t\treturn result;\n\t}\n\n\t// Priority 2: Use pgType if available (backend-specific but still useful)\n\tif (pgType) {\n\t\tconst pgTypeMapped = mapBackendTypeToCellType(pgType);\n\t\tif (pgTypeMapped !== 'unknown') return pgTypeMapped;\n\t}\n\n\t// Priority 3: Fall back to GraphQL type\n\tconst fallbackResult = mapGraphQLTypeToCellType(gqlType, isArray, metadata.subtype, null);\n\treturn fallbackResult;\n}\n\nfunction mapEncodingToCellType(\n\tencoding?: { kind: string; geometrySubtype?: string | null } | null,\n): CellType | null {\n\tif (!encoding) return null;\n\n\tswitch (encoding.kind) {\n\t\tcase 'bigint': return 'integer';\n\t\tcase 'datetime': return 'datetime';\n\t\tcase 'date': return 'date';\n\t\tcase 'time': return 'time';\n\t\tcase 'interval': return 'interval';\n\t\tcase 'uuid': return 'uuid';\n\t\tcase 'inet': return 'inet';\n\t\tcase 'point': return 'geometry-point';\n\t\tcase 'geojson':\n\t\t\treturn encoding.geometrySubtype === 'Point' ? 'geometry-point' : 'geometry';\n\t\tcase 'vector': return 'number-array';\n\t\tcase 'composite': return 'json';\n\t\tcase 'ltree':\n\t\tcase 'bytea':\n\t\t\treturn 'text';\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Maps PostgreSQL aliases to frontend cell types\n */\nfunction mapAliasToCellType(alias: string): CellType {\n\tconst aliasMap: Record<string, CellType> = {\n\t\t// Media types\n\t\timage: 'image',\n\t\tfile: 'file',\n\t\tvideo: 'video',\n\t\taudio: 'audio',\n\t\tupload: 'upload',\n\n\t\t// Relation types\n\t\trelation: 'relation',\n\n\t\t// Special text types\n\t\temail: 'email',\n\t\turl: 'url',\n\t\tphone: 'phone',\n\t\tcitext: 'citext',\n\t\ttextarea: 'textarea',\n\n\t\t// Enhanced numeric types\n\t\tnumber: 'number',\n\t\tcurrency: 'currency',\n\t\tpercentage: 'percentage',\n\t\tnumeric: 'decimal',\n\t\tdecimal: 'decimal',\n\t\tint: 'integer',\n\t\tinteger: 'integer',\n\t\tsmallint: 'smallint',\n\n\t\t// Boolean types\n\t\tboolean: 'boolean',\n\t\ttoggle: 'toggle',\n\n\t\t// Date/time types\n\t\tdate: 'date',\n\t\tdatetime: 'datetime',\n\t\ttime: 'time',\n\t\ttimestamptz: 'timestamptz',\n\t\tinterval: 'interval',\n\n\t\t// JSON types\n\t\tjson: 'json',\n\t\tjsonb: 'jsonb',\n\n\t\t// Network types\n\t\tinet: 'inet',\n\n\t\t// Geometric types\n\t\tgeometry: 'geometry',\n\t\t'geometry-point': 'geometry-point',\n\t\t'geometry-collection': 'geometry-collection',\n\n\t\t// Special types\n\t\tcolor: 'color',\n\t\trating: 'rating',\n\t\ttags: 'tags',\n\t\tuuid: 'uuid',\n\t\ttsvector: 'tsvector',\n\t\torigin: 'origin',\n\n\t\t// Character types\n\t\tchar: 'bpchar',\n\t\tbpchar: 'bpchar',\n\t\ttext: 'text',\n\n\t\t// Binary types\n\t\tbit: 'bit',\n\n\t\t// Array types (for when pgAlias is used with arrays)\n\t\tarray: 'array',\n\t\t'text-array': 'text-array',\n\t\t'integer-array': 'integer-array',\n\t\t'number-array': 'number-array',\n\t\t'uuid-array': 'uuid-array',\n\t\t'date-array': 'date-array',\n\t};\n\n\treturn aliasMap[alias.toLowerCase()] || 'unknown';\n}\n\n/**\n * Maps backend-specific types to frontend cell types\n */\nfunction mapBackendTypeToCellType(pgType: string): CellType {\n\tconst typeMap: Record<string, CellType> = {\n\t\t// Text types\n\t\ttext: 'text',\n\t\tvarchar: 'text',\n\t\tcharacter: 'text',\n\t\tchar: 'text',\n\t\t'character varying': 'text',\n\t\tcitext: 'citext',\n\t\tbpchar: 'bpchar',\n\n\t\t// Numeric types\n\t\tinteger: 'integer',\n\t\tint4: 'integer',\n\t\tsmallint: 'smallint',\n\t\tint2: 'smallint',\n\t\tbigint: 'integer',\n\t\tint8: 'integer',\n\t\tnumeric: 'decimal',\n\t\tdecimal: 'decimal',\n\t\treal: 'number',\n\t\tfloat4: 'number',\n\t\t'double precision': 'number',\n\t\tfloat8: 'number',\n\t\tmoney: 'currency',\n\n\t\t// Boolean\n\t\tboolean: 'boolean',\n\t\tbool: 'boolean',\n\n\t\t// Binary/Bit types\n\t\tbit: 'bit',\n\t\t'bit varying': 'bit',\n\t\tvarbit: 'bit',\n\n\t\t// Date/time types\n\t\tdate: 'date',\n\t\ttimestamp: 'datetime',\n\t\ttimestamptz: 'timestamptz',\n\t\t'timestamp with time zone': 'timestamptz',\n\t\t'timestamp without time zone': 'datetime',\n\t\ttime: 'time',\n\t\ttimetz: 'time',\n\t\t'time with time zone': 'time',\n\t\t'time without time zone': 'time',\n\t\tinterval: 'interval',\n\n\t\t// JSON types\n\t\tjson: 'json',\n\t\tjsonb: 'jsonb',\n\n\t\t// UUID\n\t\tuuid: 'uuid',\n\n\t\t// Full-text search\n\t\ttsvector: 'tsvector',\n\n\t\t// Network types\n\t\tinet: 'inet',\n\t\tcidr: 'inet',\n\t\tmacaddr: 'text',\n\t\tmacaddr8: 'text',\n\n\t\t// Geometric types\n\t\tpoint: 'geometry-point',\n\t\tline: 'geometry',\n\t\tlseg: 'geometry',\n\t\tbox: 'geometry',\n\t\tpath: 'geometry',\n\t\tpolygon: 'geometry',\n\t\tcircle: 'geometry',\n\t\tgeometry: 'geometry',\n\t\tgeography: 'geometry',\n\n\t\t// Custom types\n\t\temail: 'email',\n\t\turl: 'url',\n\t\timage: 'image',\n\t\tupload: 'upload',\n\t\torigin: 'origin',\n\n\t\t// Arrays are handled by isArray flag\n\t\t_text: 'array',\n\t\t_varchar: 'array',\n\t\t_integer: 'array',\n\t};\n\n\treturn typeMap[pgType.toLowerCase()] || 'unknown';\n}\n\n/**\n * Maps GraphQL types to frontend cell types based on actual _meta data structure\n */\nfunction mapGraphQLTypeToCellType(\n\tgqlType: string,\n\tisArray: boolean,\n\tsubtype?: string | null,\n\t_typmod?: unknown,\n): CellType {\n\t// Handle array types specifically\n\tif (isArray) {\n\t\t// Extract base type from array notation like [String], [UUID], etc.\n\t\tconst baseType = gqlType.replace(/[!\\[\\]]/g, '');\n\n\t\t// Map specific array types to their array cell types\n\t\tconst arrayTypeMap: Record<string, CellType> = {\n\t\t\tString: 'text-array',\n\t\t\tUUID: 'uuid-array',\n\t\t\tBigFloat: 'number-array',\n\t\t\tInt: 'integer-array',\n\t\t\tDate: 'date-array',\n\t\t};\n\n\t\treturn arrayTypeMap[baseType] || 'array'; // fallback to generic array\n\t}\n\n\t// Remove GraphQL type modifiers for base type matching\n\tconst baseType = gqlType.replace(/[!\\[\\]]/g, '');\n\n\t// Handle complex types based on actual metadata patterns\n\n\t// 1. Relation types\n\tif (baseType === 'Relation') {\n\t\treturn 'relation';\n\t}\n\n\t// 2. Interval types\n\tif (baseType === 'Interval') {\n\t\treturn 'interval';\n\t}\n\n\t// 3. GeometryGeometryCollection types\n\tif (baseType === 'GeometryGeometryCollection') {\n\t\treturn 'geometry-collection';\n\t}\n\n\t// 4. GeoJSON types with subtypes\n\tif (baseType === 'GeoJSON') {\n\t\tif (subtype === 'GeometryPoint') {\n\t\t\treturn 'geometry-point';\n\t\t}\n\t\tif (subtype === 'GeometryPolygon') {\n\t\t\treturn 'geometry-collection'; // Could be 'geometry-polygon' if you create that cell type\n\t\t}\n\t\t// Default for other GeoJSON types - should be geometry, not json\n\t\t// This ensures null geometry values are properly handled\n\t\treturn 'geometry';\n\t}\n\n\tconst typeMap: Record<string, CellType> = {\n\t\t// GraphQL scalar types\n\t\tString: 'text',\n\t\tInt: 'integer',\n\t\tFloat: 'number',\n\t\tBoolean: 'boolean',\n\t\tID: 'uuid',\n\n\t\t// Common GraphQL custom scalars\n\t\tDateTime: 'datetime',\n\t\tDatetime: 'datetime', // Handle both cases\n\t\tDate: 'date',\n\t\tTime: 'time',\n\t\tJSON: 'json',\n\t\tJSONObject: 'json',\n\t\tUpload: 'file',\n\t\tURL: 'url',\n\t\tEmailAddress: 'email',\n\t\tPhoneNumber: 'phone',\n\t\tUUID: 'uuid',\n\t\tBigFloat: 'number',\n\t\tBigInt: 'integer',\n\t};\n\n\treturn typeMap[baseType] || 'text'; // Default to text for unknown GraphQL types\n}\n\n/**\n * Determines if a field represents structured data that should be rendered as JSON\n */\nexport function isStructuredDataType(cellType: CellType): boolean {\n\treturn STRUCTURED_DATA_TYPES.has(cellType);\n}\n\n/**\n * Determines if a field represents media content\n */\nexport function isMediaType(cellType: CellType): boolean {\n\treturn MEDIA_TYPES.has(cellType);\n}\n\n/**\n * Determines if a field is a special frontend-enhanced type\n */\nexport function isEnhancedType(cellType: CellType): boolean {\n\treturn ENHANCED_TYPES.has(cellType);\n}\n\n/**\n * Create a ColumnSchema from GraphQL meta field data\n */\nexport function createColumnSchemaFromMeta(field: {\n\tname: string;\n\ttype: {\n\t\tgqlType: string;\n\t\tisArray: boolean;\n\t\tmodifier?: string | number | null;\n\t\tpgAlias?: string | null;\n\t\tpgType?: string | null;\n\t\tsubtype?: string | null;\n\t\ttypmod?: any;\n\t\tencoding?: { kind: string; geometrySubtype?: string | null } | null;\n\t};\n}): ColumnSchema {\n\tconst { name, type } = field;\n\tconst { gqlType, isArray, subtype } = type;\n\n\t// Determine if field is nullable (GraphQL types ending with ! are non-null)\n\tconst nullable = !gqlType.endsWith('!');\n\n\t// Map to frontend cell type using metadata\n\tconst cellType = mapToFrontendCellType(field.type);\n\n\t// Generate human-friendly label\n\tconst label = name\n\t\t.replace(/([A-Z])/g, ' $1')\n\t\t.replace(/^./, (str) => str.toUpperCase())\n\t\t.trim();\n\n\treturn {\n\t\tid: name,\n\t\tname,\n\t\ttype: cellType,\n\t\tnullable,\n\t\tmetadata: {\n\t\t\tlabel,\n\t\t\tdescription: `${gqlType}${isArray ? '[]' : ''}${subtype ? ` (${subtype})` : ''}`,\n\t\t\tsortable: !isArray && cellType !== 'json' && cellType !== 'geometry-collection',\n\t\t\tfilterable: cellType !== 'geometry-collection',\n\t\t},\n\t};\n}\n","import { CellRegistry } from './cell-registry';\nimport { NON_EDITABLE_TYPES, VIEWER_ONLY_TYPES } from './cell-type-groups';\nimport { mapToFrontendCellType } from './type-mapping';\n\nexport interface FieldMetadata {\n\tname: string;\n\ttype?: {\n\t\tgqlType: string;\n\t\tpgType?: string | null;\n\t\tpgAlias?: string | null;\n\t\tisArray?: boolean;\n\t\tsubtype?: string | null;\n\t};\n}\n\nexport interface CellTypeResolution {\n\tcellType: string;\n\tcanEdit: boolean;\n\tcanActivate: boolean;\n\tactivationBehavior: 'single-click' | 'double-click';\n\tisReadonly: boolean;\n}\n\n// Use double-click to activate overlay for all cell types\nconst SINGLE_CLICK_CELL_TYPES = new Set<string>();\n\nconst READONLY_CONDITIONS = new Map([\n\t['id', (fieldMeta?: FieldMetadata) => fieldMeta?.type?.gqlType === 'UUID'],\n\t['createdAt', () => true],\n\t['updatedAt', () => true],\n]);\n\nexport function resolveCellType(fieldName: string, fieldMeta?: FieldMetadata): CellTypeResolution {\n\t// Check for readonly fields first\n\tconst readonlyCheck = READONLY_CONDITIONS.get(fieldName);\n\tconst isReadonly = readonlyCheck?.(fieldMeta) ?? false;\n\n\tlet cellType: string = 'text'; // Default fallback\n\n\tif (fieldMeta?.type) {\n\t\t// First try CellRegistry matching (same as existing logic)\n\t\t// NOTE: Cell type is determined ONLY from schema metadata, never from runtime values\n\t\tconst matchedEntry = CellRegistry.findByMatch({\n\t\t\tgqlType: fieldMeta.type.gqlType || '',\n\t\t\tisArray: !!fieldMeta.type.isArray,\n\t\t\tpgAlias: fieldMeta.type.pgAlias,\n\t\t\tpgType: fieldMeta.type.pgType,\n\t\t\tsubtype: fieldMeta.type.subtype ?? null,\n\t\t\tfieldName,\n\t\t});\n\n\t\tif (matchedEntry) {\n\t\t\tcellType = matchedEntry.type;\n\t\t} else {\n\t\t\t// Fallback: Map GraphQL field metadata to frontend cell types\n\t\t\tcellType = mapToFrontendCellType({\n\t\t\t\tgqlType: fieldMeta.type.gqlType,\n\t\t\t\tisArray: !!fieldMeta.type.isArray,\n\t\t\t\tpgAlias: fieldMeta.type.pgAlias,\n\t\t\t\tpgType: fieldMeta.type.pgType,\n\t\t\t\tsubtype: fieldMeta.type.subtype ?? null,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Determine editing capabilities\n\tconst canEdit = !isReadonly && !NON_EDITABLE_TYPES.has(cellType);\n\tconst canActivate = canEdit || VIEWER_ONLY_TYPES.has(cellType);\n\tconst activationBehavior = SINGLE_CLICK_CELL_TYPES.has(cellType) ? 'single-click' : 'double-click';\n\n\treturn {\n\t\tcellType,\n\t\tcanEdit,\n\t\tcanActivate,\n\t\tactivationBehavior,\n\t\tisReadonly,\n\t};\n}\n\nexport function shouldShowCellActivation(fieldName: string, cellType: string): boolean {\n\t// Disable activation for specific readonly fields\n\tif (fieldName === 'createdAt' || fieldName === 'updatedAt') {\n\t\treturn false;\n\t}\n\n\tif (VIEWER_ONLY_TYPES.has(cellType)) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n// Helper for checking if a field is an image type (used by existing column logic)\nexport function isImageField(fieldMeta?: FieldMetadata, fieldName?: string): boolean {\n\tif (!fieldMeta || !fieldName) return false;\n\n\t// Check if this field is configured as an image type\n\tconst isImageByType =\n\t\tfieldMeta.type?.gqlType === 'JSON' && // Image fields are often JSON\n\t\t(fieldName.toLowerCase().includes('image') ||\n\t\t\tfieldName.toLowerCase().includes('picture') ||\n\t\t\tfieldName.toLowerCase().includes('photo') ||\n\t\t\tfieldName.toLowerCase().includes('avatar'));\n\n\t// Also check using CellRegistry matching\n\tconst matchedEntry = CellRegistry.findByMatch({\n\t\tgqlType: fieldMeta.type?.gqlType || '',\n\t\tisArray: !!fieldMeta.type?.isArray,\n\t\tpgAlias: fieldMeta.type?.pgAlias,\n\t\tpgType: fieldMeta.type?.pgType,\n\t\tsubtype: fieldMeta.type?.subtype ?? null,\n\t\tfieldName,\n\t});\n\n\treturn isImageByType || matchedEntry?.type === 'image';\n}\n","import { CellRegistry } from '../cell-types/cell-registry';\nimport { prepareCreateInput, type MetaField, type Filter } from '@constructive-io/data';\nimport { mapToFrontendCellType } from '../cell-types/type-mapping';\nimport type { RelationInfo } from '../store/relation-info-slice';\n\nimport type { FieldMetadata } from '../cell-types/cell-type-resolver';\nimport type { FilterCondition, FilterGroup, FilterNode, FilterValue } from './sheets.controls';\nimport { isFilterableType, isValuelessOperator } from './filter-operators';\nimport { compactJsonPreview } from './sheets.formatters';\n\nexport function formatColumnHeader(fieldName: string): string {\n\treturn fieldName\n\t\t.replace(/([A-Z])/g, ' $1')\n\t\t.replace(/^./, (str) => str.toUpperCase())\n\t\t.replace(/_/g, ' ')\n\t\t.trim();\n}\n\nexport function getColumnWidthByMeta(field: FieldMetadata): number {\n\tconst t = field.type;\n\tif (!t) return 150;\n\tconst cellType = mapToFrontendCellType({\n\t\tgqlType: t.gqlType,\n\t\tisArray: !!t.isArray,\n\t\tpgAlias: t.pgAlias,\n\t\tpgType: t.pgType,\n\t\tsubtype: t.subtype ?? null,\n\t});\n\tconst entry = CellRegistry.get(cellType);\n\treturn entry?.metadata?.width ?? 150;\n}\n\ntype FilterableFieldMeta = {\n\tname?: string | null;\n\ttype?: {\n\t\tgqlType?: string | null;\n\t\tisArray?: boolean | null;\n\t\tpgType?: string | null;\n\t} | null;\n};\n\ntype FilterableTableMeta = {\n\tfields?: Array<FilterableFieldMeta | null> | null;\n} | null | undefined;\n\n/** Coerce a raw string value to the appropriate JS type based on gqlType. */\nfunction coerceFilterValue(gqlType: string | null | undefined, strVal: string): unknown {\n\tswitch (gqlType) {\n\t\tcase 'Int': {\n\t\t\tconst n = parseInt(strVal, 10);\n\t\t\treturn Number.isNaN(n) ? null : n;\n\t\t}\n\t\tcase 'Float': {\n\t\t\tconst n = parseFloat(strVal);\n\t\t\treturn Number.isNaN(n) ? null : n;\n\t\t}\n\t\tcase 'Interval': {\n\t\t\t// Value is a JSON-encoded IntervalInput object from the structured UI\n\t\t\ttry {\n\t\t\t\tconst obj = JSON.parse(strVal);\n\t\t\t\tif (obj && typeof obj === 'object' && !Array.isArray(obj)) return obj;\n\t\t\t\treturn null;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\t// Everything else passes through as string\n\t\tdefault:\n\t\t\treturn strVal;\n\t}\n}\n\n/**\n * Build the filter expression for a single field using an explicit operator.\n * Returns null for types that cannot be filtered (arrays, GeoJSON, FullText, unknown types).\n */\nfunction buildFieldFilter(\n\tfieldMeta: FilterableFieldMeta | null | undefined,\n\toperator: string,\n\trawValue: FilterValue,\n): Record<string, unknown> | null {\n\t// Value-less operators encode their value in the operator name\n\tif (isValuelessOperator(operator)) {\n\t\tif (operator === 'isNull') return { isNull: true };\n\t\tif (operator === 'equalTo:true') return { equalTo: true };\n\t\tif (operator === 'equalTo:false') return { equalTo: false };\n\t}\n\n\tconst gqlType = fieldMeta?.type?.gqlType;\n\tconst isArray = !!fieldMeta?.type?.isArray;\n\n\t// Skip unfilterable types (arrays, GeoJSON, FullText, unknown)\n\tif (!isFilterableType(gqlType, isArray)) return null;\n\n\tconst strVal = String(rawValue);\n\tconst coerced = coerceFilterValue(gqlType, strVal);\n\tif (coerced === null) return null;\n\n\treturn { [operator]: coerced };\n}\n\n/** Convert a single condition node to a PostGraphile filter expression. */\nfunction conditionToWhere(\n\tcondition: FilterCondition,\n\tfieldsByName: Map<string, FilterableFieldMeta>,\n): Filter | null {\n\t// Skip empty-value conditions (unless valueless operator)\n\tif (\n\t\t!isValuelessOperator(condition.operator) &&\n\t\t(condition.value === '' || condition.value === null || condition.value === undefined)\n\t) {\n\t\treturn null;\n\t}\n\tconst fieldMeta = fieldsByName.get(condition.field);\n\tconst filterExpr = buildFieldFilter(fieldMeta, condition.operator, condition.value);\n\treturn filterExpr ? ({ [condition.field]: filterExpr } as Filter) : null;\n}\n\n/** Recursively convert a filter tree node to a PostGraphile Filter object. */\nfunction filterNodeToWhere(\n\tnode: FilterNode,\n\tfieldsByName: Map<string, FilterableFieldMeta>,\n): Filter | null {\n\tif (node.type === 'condition') {\n\t\treturn conditionToWhere(node, fieldsByName);\n\t}\n\n\tconst childFilters = node.children\n\t\t.map((child) => filterNodeToWhere(child, fieldsByName))\n\t\t.filter((f): f is Filter => f !== null);\n\n\tif (childFilters.length === 0) return null;\n\tif (childFilters.length === 1) return childFilters[0];\n\treturn { [node.conjunction]: childFilters };\n}\n\nexport function buildWhereFromFilters(\n\tfilterTree: FilterGroup,\n\ttableMeta: FilterableTableMeta,\n): Filter | undefined {\n\tif (!filterTree.children.length) return undefined;\n\n\t// Pre-build field lookup map\n\tconst fieldsByName = new Map<string, FilterableFieldMeta>();\n\tfor (const field of tableMeta?.fields ?? []) {\n\t\tif (field?.name) fieldsByName.set(field.name, field);\n\t}\n\n\tconst treeWhere = filterNodeToWhere(filterTree, fieldsByName);\n\treturn treeWhere ?? undefined;\n}\n\nexport function mapFromFieldMetaMap(fieldMetaMap: Map<string, MetaField>): Record<string, MetaField | undefined> {\n\tconst record: Record<string, MetaField | undefined> = {};\n\tfieldMetaMap.forEach((value, key) => {\n\t\trecord[key] = value;\n\t});\n\treturn record;\n}\n\nexport function mapFromRelationInfoMap(\n\trelationInfoMap: Map<string, RelationInfo | undefined>,\n): Record<string, RelationInfo | undefined> {\n\tconst record: Record<string, RelationInfo | undefined> = {};\n\trelationInfoMap.forEach((value, key) => {\n\t\trecord[key] = value;\n\t});\n\treturn record;\n}\n\nfunction unwrapConnectionNode(entry: unknown): unknown {\n\tif (!entry || typeof entry !== 'object') return entry;\n\n\tconst record = entry as Record<string, unknown>;\n\tif ('node' in record && record.node !== undefined) {\n\t\treturn unwrapConnectionNode(record.node);\n\t}\n\treturn entry;\n}\n\nexport function unwrapRelationValue<T = unknown>(value: T): T {\n\tif (Array.isArray(value)) {\n\t\treturn value.map((entry) => unwrapRelationValue(entry)) as unknown as T;\n\t}\n\n\tif (value && typeof value === 'object') {\n\t\tconst record = value as Record<string, unknown>;\n\n\t\tif (Array.isArray(record.nodes)) {\n\t\t\treturn record.nodes.map((entry) => unwrapRelationValue(entry)) as unknown as T;\n\t\t}\n\n\t\tif (Array.isArray(record.edges)) {\n\t\t\treturn record.edges.map((edge) => unwrapRelationValue(unwrapConnectionNode(edge))) as unknown as T;\n\t\t}\n\n\t\tif ('node' in record && record.node !== undefined) {\n\t\t\treturn unwrapRelationValue(record.node) as unknown as T;\n\t\t}\n\t}\n\n\treturn value;\n}\n\nexport function normalizeServerRow(row: Record<string, unknown>, relationFields: Set<string>): Record<string, unknown> {\n\tif (!row || typeof row !== 'object') {\n\t\treturn row;\n\t}\n\n\tconst next: Record<string, unknown> = { ...row };\n\trelationFields.forEach((fieldName) => {\n\t\tnext[fieldName] = unwrapRelationValue(next[fieldName]);\n\t});\n\treturn next;\n}\n\ninterface DraftSubmissionOptions {\n\tallowedColumns?: ReadonlySet<string>;\n\trelationInfoByKey?: Record<string, RelationInfo | undefined>;\n}\n\nexport interface DraftValidationFieldMeta {\n\tname?: string | null;\n\tisNotNull?: boolean | null;\n\thasDefault?: boolean | null;\n\ttype?: { gqlType?: string | null; isArray?: boolean | null } | null;\n}\n\nexport function validateDraftRowRequiredFields(\n\tvalues: Record<string, unknown>,\n\tfieldMetaByKey: Record<string, DraftValidationFieldMeta | undefined>,\n\toptions?: {\n\t\tallowedColumns?: ReadonlySet<string>;\n\t\trelationInfoByKey?: Record<string, RelationInfo | undefined>;\n\t},\n): Record<string, string> {\n\tconst errors: Record<string, string> = {};\n\tconst { allowedColumns, relationInfoByKey } = options ?? {};\n\tconst allowsAll = !allowedColumns || allowedColumns.size === 0;\n\n\tfor (const [key, meta] of Object.entries(fieldMetaByKey)) {\n\t\tif (!meta) continue;\n\t\tif (!meta.isNotNull) continue;\n\t\tif (meta.hasDefault) continue;\n\t\tif (key === 'id') continue;\n\t\tif (!allowsAll && !allowedColumns?.has(key)) continue;\n\n\t\tconst relInfo = relationInfoByKey?.[key];\n\t\tif (relInfo && relInfo.relationField === key) continue;\n\n\t\tconst value = values[key];\n\t\tif (value == null || value === '') {\n\t\t\terrors[key] = `${formatColumnHeader(key)} is required`;\n\t\t}\n\t}\n\n\treturn errors;\n}\n\nexport function prepareDraftSubmissionPayload(\n\tvalues: Record<string, unknown>,\n\toptions: DraftSubmissionOptions = {},\n): Record<string, unknown> {\n\tconst { allowedColumns, relationInfoByKey } = options;\n\tconst allowsAll = !allowedColumns || allowedColumns.size === 0;\n\n\t// Step 1: Filter nullish values using centralized utility\n\t// Draft submission is a CREATE operation, so null/undefined are filtered\n\tconst { id: _id, ...valuesWithoutId } = values;\n\tconst filtered = prepareCreateInput(valuesWithoutId);\n\n\t// Step 2: Apply relation-specific transformations\n\tconst payload: Record<string, unknown> = {};\n\n\tconst normalizeForeignKeyValue = (input: unknown): unknown => {\n\t\tif (input === undefined || input === null) return undefined;\n\n\t\tconst extractId = (candidate: unknown): string | number | null => {\n\t\t\tif (candidate === null || candidate === undefined) return null;\n\t\t\tif (typeof candidate === 'object') {\n\t\t\t\tconst record = candidate as Record<string, unknown>;\n\t\t\t\tconst id = record.id;\n\t\t\t\tif (typeof id === 'string' || typeof id === 'number') {\n\t\t\t\t\treturn id;\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (typeof candidate === 'string' || typeof candidate === 'number') {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input\n\t\t\t\t.map((entry) => extractId(entry))\n\t\t\t\t.filter((entry): entry is string | number => entry !== undefined && entry !== null);\n\t\t}\n\n\t\treturn extractId(input);\n\t};\n\n\tfor (const [key, value] of Object.entries(filtered)) {\n\t\tconst isAllowed = allowsAll || allowedColumns?.has(key);\n\t\tif (!isAllowed) continue;\n\n\t\tconst relInfo = relationInfoByKey?.[key];\n\n\t\tif (relInfo?.relationField === key) {\n\t\t\t// Skip relation display fields; rely on the corresponding foreign key entry\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (relInfo?.foreignKeyField === key) {\n\t\t\tconst normalized = normalizeForeignKeyValue(value);\n\t\t\tif (normalized === undefined) continue;\n\t\t\tpayload[key] = normalized;\n\t\t\tcontinue;\n\t\t}\n\n\t\tpayload[key] = value;\n\t}\n\n\treturn payload;\n}\n\nexport function prepareDraftRelationValue(\n\trawValue: unknown,\n\trelationInfo: RelationInfo,\n): {\n\trelationData: unknown;\n\tforeignKeyUpdates?: Record<string, unknown>;\n\trelationReferences?: unknown;\n} {\n\tlet value = rawValue;\n\n\tif (typeof value === 'string') {\n\t\tconst trimmed = value.trim();\n\t\tif (!trimmed) {\n\t\t\tvalue = null;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tvalue = JSON.parse(trimmed);\n\t\t\t} catch {\n\t\t\t\tvalue = trimmed;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst isListRelation = relationInfo.kind === 'hasMany' || relationInfo.kind === 'manyToMany';\n\n\tif (isListRelation) {\n\t\tconst entries = Array.isArray(value) ? value : value == null ? [] : [value];\n\t\tconst normalized = entries\n\t\t\t.map(normalizeRelationEntry)\n\t\t\t.filter((entry): entry is RelationNormalization => entry !== null);\n\n\t\tconst relationData = normalized.map((entry) => entry.value);\n\t\tconst relationReferences = normalized.map((entry) => entry.reference ?? null);\n\n\t\tconst fkField = relationInfo.foreignKeyField;\n\t\tconst foreignKeyUpdates = fkField\n\t\t\t? {\n\t\t\t\t\t[fkField]: normalized.map((entry) => (entry.reference === undefined ? null : entry.reference)),\n\t\t\t\t}\n\t\t\t: undefined;\n\n\t\treturn {\n\t\t\trelationData,\n\t\t\tforeignKeyUpdates,\n\t\t\trelationReferences,\n\t\t};\n\t}\n\n\tconst normalizedEntry = normalizeRelationEntry(Array.isArray(value) ? (value[0] ?? null) : value);\n\n\tconst relationData = normalizedEntry?.value ?? null;\n\tconst relationReference = normalizedEntry?.reference ?? null;\n\n\tconst fkField = relationInfo.foreignKeyField;\n\tconst foreignKeyUpdates = fkField\n\t\t? {\n\t\t\t\t[fkField]: normalizedEntry?.reference ?? null,\n\t\t\t}\n\t\t: undefined;\n\n\treturn {\n\t\trelationData,\n\t\tforeignKeyUpdates,\n\t\trelationReferences: relationReference,\n\t};\n}\n\ntype RelationNormalization = {\n\tvalue: unknown;\n\treference: string | number | null | undefined;\n};\n\nfunction normalizeRelationEntry(entry: unknown): RelationNormalization | null {\n\tif (entry === null || entry === undefined || entry === '') {\n\t\treturn null;\n\t}\n\n\tif (Array.isArray(entry)) {\n\t\treturn normalizeRelationEntry(entry[0]);\n\t}\n\n\tif (typeof entry === 'object') {\n\t\tconst record = entry as Record<string, unknown>;\n\t\tconst id = record.id;\n\t\treturn {\n\t\t\tvalue: record,\n\t\t\treference: typeof id === 'string' || typeof id === 'number' ? (id as string | number) : null,\n\t\t};\n\t}\n\n\tif (typeof entry === 'string' || typeof entry === 'number') {\n\t\treturn {\n\t\t\tvalue: entry,\n\t\t\treference: entry,\n\t\t};\n\t}\n\n\treturn null;\n}\n\n// Infer cell type from data content when location/metadata is not available\nexport function inferCellTypeFromData(data: string): string | undefined {\n\tif (!data || typeof data !== 'string') return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(data);\n\n\t\t// Check for geometry data patterns (wrapped format with geojson property)\n\t\tif (parsed && typeof parsed === 'object' && parsed.geojson) {\n\t\t\t// This is the wrapped geometry format: {\"geojson\": {...}, \"srid\": ..., \"x\": ..., \"y\": ...}\n\t\t\t// But sometimes it might only have the geojson property\n\t\t\tif (parsed.geojson.type === 'Point') {\n\t\t\t\treturn 'geometry-point';\n\t\t\t} else if (parsed.geojson.type === 'GeometryCollection') {\n\t\t\t\treturn 'geometry-collection';\n\t\t\t} else {\n\t\t\t\treturn 'geometry';\n\t\t\t}\n\t\t}\n\n\t\t// Check for raw GeoJSON (direct GeoJSON object)\n\t\tif (parsed && typeof parsed === 'object' && parsed.type && parsed.coordinates) {\n\t\t\tconst validGeoJSONTypes = [\n\t\t\t\t'Point',\n\t\t\t\t'LineString',\n\t\t\t\t'Polygon',\n\t\t\t\t'MultiPoint',\n\t\t\t\t'MultiLineString',\n\t\t\t\t'MultiPolygon',\n\t\t\t\t'GeometryCollection',\n\t\t\t];\n\t\t\tif (validGeoJSONTypes.includes(parsed.type)) {\n\t\t\t\tif (parsed.type === 'Point') {\n\t\t\t\t\treturn 'geometry-point';\n\t\t\t\t} else if (parsed.type === 'GeometryCollection') {\n\t\t\t\t\treturn 'geometry-collection';\n\t\t\t\t} else {\n\t\t\t\t\treturn 'geometry';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check for array data\n\t\tif (Array.isArray(parsed)) {\n\t\t\treturn 'array';\n\t\t}\n\n\t\t// Check for interval data (objects with days/hours/minutes/seconds properties)\n\t\tif (\n\t\t\tparsed &&\n\t\t\ttypeof parsed === 'object' &&\n\t\t\t(parsed.days !== undefined ||\n\t\t\t\tparsed.hours !== undefined ||\n\t\t\t\tparsed.minutes !== undefined ||\n\t\t\t\tparsed.seconds !== undefined)\n\t\t) {\n\t\t\treturn 'interval';\n\t\t}\n\n\t\t// Check for image data (objects with url/src/href/path properties)\n\t\tif (parsed && typeof parsed === 'object' && (parsed.url || parsed.src || parsed.href || parsed.path)) {\n\t\t\treturn 'image';\n\t\t}\n\n\t\t// Check for date strings (ISO format)\n\t\tif (typeof parsed === 'string' && /^\\d{4}-\\d{2}-\\d{2}/.test(parsed)) {\n\t\t\tif (parsed.includes('T')) {\n\t\t\t\treturn 'datetime';\n\t\t\t} else {\n\t\t\t\treturn 'date';\n\t\t\t}\n\t\t}\n\n\t\t// Generic JSON object\n\t\treturn 'json';\n\t} catch {\n\t\t// Not valid JSON, could be other data types\n\n\t\t// Check for date strings\n\t\tif (/^\\d{4}-\\d{2}-\\d{2}/.test(data)) {\n\t\t\tif (data.includes('T')) {\n\t\t\t\treturn 'datetime';\n\t\t\t} else {\n\t\t\t\treturn 'date';\n\t\t\t}\n\t\t}\n\n\t\t// Check for time strings\n\t\tif (/^\\d{2}:\\d{2}/.test(data)) {\n\t\t\treturn 'time';\n\t\t}\n\n\t\treturn undefined;\n\t}\n}\n\n// Utility functions for array previews\nexport function formatArrayPreview(arr: any[]): string {\n\tconst max = 3;\n\tconst items = arr.slice(0, max).map((v) => (typeof v === 'object' ? compactJsonPreview(v, 20) : String(v)));\n\tconst more = arr.length > max ? ` +${arr.length - max}` : '';\n\treturn items.join(', ') + more;\n}\n\n\n// Row operations\nexport async function handleRowAppend(\n\tcreateFunction: (data: any) => Promise<any>,\n): Promise<'top' | 'bottom' | number | undefined> {\n\tconst { createdRow } = await createFunction({});\n\tif (createdRow) {\n\t\treturn 'bottom';\n\t}\n\treturn undefined;\n}\n\n// Type-safe header click handler for sorting\n// Only allows sorting on columns in the sortableColumns set (excludes relation columns)\nexport function createHeaderClickHandler(\n\tcolumnKeys: string[],\n\ttoggleSorting: (colId: string) => void,\n\tsortableColumns?: Set<string>,\n) {\n\treturn (colIndex: number) => {\n\t\tconst colId = columnKeys[colIndex];\n\t\tif (!colId) return;\n\n\t\t// If sortableColumns is provided, only allow sorting on those columns\n\t\tif (sortableColumns && !sortableColumns.has(colId)) {\n\t\t\treturn;\n\t\t}\n\n\t\ttoggleSorting(colId);\n\t};\n}\n\n// Type-safe column resize handler\nexport function createColumnResizeHandler(resizeColumn: (id: string, width: number) => void) {\n\treturn (column: { id?: string }, newSize: number) => {\n\t\tif (column.id) {\n\t\t\tresizeColumn(column.id, newSize);\n\t\t}\n\t};\n}\n","/**\n * Light-weight relation metadata cache with straightforward error handling\n */\nimport { useCallback, useMemo } from 'react';\nimport { useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport { pluralize } from 'inflekt';\nimport { cleanTable, pgFieldToCamelCase, type CleanTable } from '@constructive-io/data';\nimport { useSheetsMeta } from './use-sheets-meta';\nimport { useSheetsContext, type SheetsScopeKey } from '../context/sheets-context';\nimport { sheetsQueryKeys } from './query-keys';\nimport { getJunctionTableNames, isJunctionTablePure } from '../utils/relation-utils';\nimport { sheetsLogger } from '../utils/sheets-logger';\n\n/**\n * Simple cache keys for relations\n */\nexport const RELATION_CACHE_KEYS = {\n\ttableRelations: (scope: SheetsScopeKey, tableName: string) => sheetsQueryKeys.relations(scope, tableName),\n} as const;\n\n/**\n * Cache timing tuned for relation metadata\n */\nexport const RELATION_CACHE_CONFIG = {\n\tstaleTime: 5 * 60 * 1000, // 5 minutes - reasonable for relation metadata\n\tgcTime: 30 * 60 * 1000, // 30 minutes - keep in memory longer\n\tretry: 3, // Retry failed requests\n\tretryDelay: (attemptIndex: number) => Math.min(1000 * 2 ** attemptIndex, 5000),\n} as const;\n\nexport type RelationMetadataSource = 'relation' | 'foreignKey';\n\nexport interface RelationMetadata {\n\ttableName: string;\n\tfieldName: string;\n\trelationKind: 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';\n\ttargetTable: string;\n\tisOptional: boolean;\n\tforeignKeyFields: string[];\n\t/** Headline relation field name when this metadata originates from a foreign key */\n\trelationFieldName?: string | null;\n\t/** Primary foreign key field associated with the relation */\n\tforeignKeyField?: string;\n\t/** Indicates whether the metadata entry is for the relation field or the FK column */\n\tsourceField: RelationMetadataSource;\n\tjunctionTable?: string;\n\tdisplayName?: string;\n}\n\n/**\n * Simple error state tracking\n */\nexport interface RelationCacheState {\n\tisLoading: boolean;\n\tisError: boolean;\n\terror: Error | null;\n\thasData: boolean;\n\trelationCount: number;\n}\n\nexport interface RelationMetadataSet {\n\trelationFields: RelationMetadata[];\n\tforeignKeyFields: RelationMetadata[];\n}\n\n/**\n * Cache and expose relation metadata for a table\n */\nexport function useRelationMetadataCache(tableName?: string) {\n\tconst queryClient = useQueryClient();\n\tconst { scopeKey } = useSheetsContext();\n\tconst { data: metaData, isError: metaError, error: metaErrorDetails } = useSheetsMeta();\n\n\t// Get table relations with improved error handling\n\tconst {\n\t\tdata: tableRelations,\n\t\tisLoading,\n\t\tisError,\n\t\terror,\n\t} = useQuery({\n\t\tqueryKey: RELATION_CACHE_KEYS.tableRelations(scopeKey, tableName || ''),\n\t\tqueryFn: async (): Promise<CleanTable | null> => {\n\t\t\tif (!metaData?._meta?.tables || !tableName) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst metaTable = metaData._meta.tables.find((t) => t?.name === tableName);\n\t\t\tif (!metaTable) {\n\t\t\t\t// Don't throw error for missing table - just return null\n\t\t\t\tsheetsLogger().debug?.(`Table \"${tableName}\" not found in metadata`);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn cleanTable(metaTable);\n\t\t},\n\t\t...RELATION_CACHE_CONFIG,\n\t\trefetchOnMount: true, // Respect staleTime and refresh stale relation metadata on mount\n\t\tenabled: Boolean(metaData && tableName),\n\t});\n\n\t// Extract relation metadata with error handling\n\tconst { relationFields, foreignKeyFields } = useMemo((): RelationMetadataSet => {\n\t\tif (!tableRelations?.relations || isError) {\n\t\t\treturn { relationFields: [], foreignKeyFields: [] };\n\t\t}\n\n\t\tconst relationFieldEntries: RelationMetadata[] = [];\n\t\tconst foreignKeyEntries: RelationMetadata[] = [];\n\t\tconst relations = tableRelations.relations;\n\n\t\ttry {\n\t\t\t// Process belongsTo relations\n\t\t\trelations.belongsTo.forEach((rel) => {\n\t\t\t\tif (!rel) return;\n\t\t\t\tconst foreignKeys = rel.keys.map((k) => k.name);\n\t\t\t\tconst primaryForeignKey = foreignKeys[0];\n\t\t\t\tif (rel.fieldName) {\n\t\t\t\t\trelationFieldEntries.push({\n\t\t\t\t\t\ttableName: tableName || '',\n\t\t\t\t\t\tfieldName: rel.fieldName,\n\t\t\t\t\t\trelationKind: 'belongsTo',\n\t\t\t\t\t\ttargetTable: rel.referencesTable,\n\t\t\t\t\t\tisOptional: !rel.isUnique,\n\t\t\t\t\t\tforeignKeyFields: foreignKeys,\n\t\t\t\t\t\trelationFieldName: rel.fieldName,\n\t\t\t\t\t\tforeignKeyField: primaryForeignKey,\n\t\t\t\t\t\tsourceField: 'relation',\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tforeignKeys.forEach((fk) => {\n\t\t\t\t\tif (!fk) return;\n\t\t\t\t\tforeignKeyEntries.push({\n\t\t\t\t\t\ttableName: tableName || '',\n\t\t\t\t\t\tfieldName: fk,\n\t\t\t\t\t\trelationKind: 'belongsTo',\n\t\t\t\t\t\ttargetTable: rel.referencesTable,\n\t\t\t\t\t\tisOptional: !rel.isUnique,\n\t\t\t\t\t\tforeignKeyFields: foreignKeys,\n\t\t\t\t\t\trelationFieldName: rel.fieldName ?? null,\n\t\t\t\t\t\tforeignKeyField: fk,\n\t\t\t\t\t\tsourceField: 'foreignKey',\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tconst rawMetaTables = (metaData?._meta?.tables ?? []).filter(\n\t\t\t\t(t): t is NonNullable<typeof t> => t != null,\n\t\t\t);\n\n\t\t\t// Resolve FK field in the related table using foreignKeyConstraints from _meta\n\t\t\tconst findFk = (relatedTableName: string): string | undefined => {\n\t\t\t\tconst rawRelated = rawMetaTables.find((t) => t?.name === relatedTableName);\n\t\t\t\tif (!rawRelated) return undefined;\n\t\t\t\t// v5 nested: constraints.foreignKey[]\n\t\t\t\tconst v5Fks = Array.isArray(rawRelated.constraints) ? [] : rawRelated.constraints?.foreignKey;\n\t\t\t\t// v4 flat: foreignKeyConstraints[]\n\t\t\t\tconst fks = v5Fks ?? rawRelated.foreignKeyConstraints ?? [];\n\t\t\t\tfor (const fk of fks) {\n\t\t\t\t\tif (!fk) continue;\n\t\t\t\t\tconst refName = fk.refTable?.name;\n\t\t\t\t\tif (refName && refName.toLowerCase() === (tableName || '').toLowerCase()) {\n\t\t\t\t\t\tconst fieldName = fk.fields?.[0]?.name;\n\t\t\t\t\t\tif (fieldName) return pgFieldToCamelCase(fieldName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t};\n\n\t\t\t// Process hasOne relations\n\t\t\trelations.hasOne.forEach((rel) => {\n\t\t\t\tif (rel.fieldName) {\n\t\t\t\t\trelationFieldEntries.push({\n\t\t\t\t\t\ttableName: tableName || '',\n\t\t\t\t\t\tfieldName: rel.fieldName,\n\t\t\t\t\t\trelationKind: 'hasOne',\n\t\t\t\t\t\ttargetTable: rel.referencedByTable,\n\t\t\t\t\t\tisOptional: true,\n\t\t\t\t\t\tforeignKeyFields: rel.keys.map((k) => k.name),\n\t\t\t\t\t\trelationFieldName: rel.fieldName,\n\t\t\t\t\t\tforeignKeyField: findFk(rel.referencedByTable),\n\t\t\t\t\t\tsourceField: 'relation',\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tconst junctionTableNames = getJunctionTableNames(relations, rawMetaTables);\n\n\t\t\t// Process hasMany relations (skip those pointing to junction tables)\n\t\t\trelations.hasMany.forEach((rel) => {\n\t\t\t\tif (!rel.fieldName) return;\n\t\t\t\t// Skip hasMany relations pointing to junction tables (M:N covers these)\n\t\t\t\tif (junctionTableNames.has(rel.referencedByTable)) return;\n\t\t\t\trelationFieldEntries.push({\n\t\t\t\t\ttableName: tableName || '',\n\t\t\t\t\tfieldName: rel.fieldName,\n\t\t\t\t\trelationKind: 'hasMany',\n\t\t\t\t\ttargetTable: rel.referencedByTable,\n\t\t\t\t\tisOptional: true,\n\t\t\t\t\tforeignKeyFields: rel.keys.map((k) => k.name),\n\t\t\t\t\trelationFieldName: rel.fieldName,\n\t\t\t\t\tforeignKeyField: findFk(rel.referencedByTable),\n\t\t\t\t\tsourceField: 'relation',\n\t\t\t\t});\n\t\t\t});\n\n\t\t\t// Process manyToMany relations (already deduped by rightTable in cleanTable())\n\t\t\t// Skip non-pure junction tables — they have required fields beyond the two FK columns\n\t\t\trelations.manyToMany.forEach((rel) => {\n\t\t\t\tif (rel.fieldName) {\n\t\t\t\t\tconst leftFk = rel.junctionLeftKeyFields?.[0];\n\t\t\t\t\tconst rightFk = rel.junctionRightKeyFields?.[0];\n\t\t\t\t\tif (rel.junctionTable && !isJunctionTablePure(rel.junctionTable, leftFk, rightFk, rawMetaTables)) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\trelationFieldEntries.push({\n\t\t\t\t\t\ttableName: tableName || '',\n\t\t\t\t\t\tfieldName: rel.fieldName,\n\t\t\t\t\t\trelationKind: 'manyToMany',\n\t\t\t\t\t\ttargetTable: rel.rightTable,\n\t\t\t\t\t\tisOptional: true,\n\t\t\t\t\t\tforeignKeyFields: [],\n\t\t\t\t\t\trelationFieldName: rel.fieldName,\n\t\t\t\t\t\tforeignKeyField: undefined,\n\t\t\t\t\t\tsourceField: 'relation',\n\t\t\t\t\t\tjunctionTable: rel.junctionTable,\n\t\t\t\t\t\tdisplayName: pluralize(rel.rightTable),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (processError) {\n\t\t\tsheetsLogger().warn('Error processing relation metadata:', processError);\n\t\t}\n\n\t\treturn { relationFields: relationFieldEntries, foreignKeyFields: foreignKeyEntries };\n\t}, [tableRelations, tableName, isError, metaData]);\n\n\tconst relationMetadata = useMemo(() => relationFields.concat(foreignKeyFields), [relationFields, foreignKeyFields]);\n\n\tconst relationMap = useMemo(() => {\n\t\tconst map = new Map<string, RelationMetadata>();\n\t\trelationFields.forEach((rel) => {\n\t\t\tmap.set(rel.fieldName, rel);\n\t\t});\n\t\tforeignKeyFields.forEach((rel) => {\n\t\t\tmap.set(rel.fieldName, rel);\n\t\t});\n\t\treturn map;\n\t}, [relationFields, foreignKeyFields]);\n\n\t// Simple cache invalidation\n\tconst invalidateRelationCache = useCallback(async () => {\n\t\tif (tableName) {\n\t\t\tawait queryClient.invalidateQueries({\n\t\t\t\tqueryKey: RELATION_CACHE_KEYS.tableRelations(scopeKey, tableName),\n\t\t\t});\n\t\t}\n\t}, [queryClient, scopeKey, tableName]);\n\n\t// Get relation info for a specific field\n\tconst getRelationInfo = useCallback(\n\t\t(fieldName: string): RelationMetadata | null => {\n\t\t\treturn relationMap.get(fieldName) || null;\n\t\t},\n\t\t[relationMap],\n\t);\n\n\t// Check if field is a relation\n\tconst isRelationField = useCallback(\n\t\t(fieldName: string): boolean => {\n\t\t\treturn relationMap.has(fieldName);\n\t\t},\n\t\t[relationMap],\n\t);\n\n\t// Get relation kind for backward compatibility\n\tconst getRelationKind = useCallback(\n\t\t(fieldName: string): 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany' | null => {\n\t\t\tconst relation = relationMap.get(fieldName);\n\t\t\treturn relation?.relationKind || null;\n\t\t},\n\t\t[relationMap],\n\t);\n\n\t// Simple cache state\n\tconst cacheState: RelationCacheState = useMemo(\n\t\t() => ({\n\t\t\tisLoading: isLoading || (!metaData && !metaError),\n\t\t\tisError: isError || metaError,\n\t\t\terror: error || metaErrorDetails || null,\n\t\t\thasData: Boolean(tableRelations && relationMetadata.length > 0),\n\t\t\trelationCount: relationMetadata.length,\n\t\t}),\n\t\t[isLoading, metaData, metaError, isError, error, metaErrorDetails, tableRelations, relationMetadata.length],\n\t);\n\n\treturn {\n\t\t// Data\n\t\trelationMetadata,\n\t\trelationFields,\n\t\tforeignKeyFields,\n\t\trelationMap,\n\t\ttableRelations,\n\n\t\t// State\n\t\tcacheState,\n\t\tisLoading,\n\t\tisError,\n\t\terror,\n\n\t\t// Utilities\n\t\tgetRelationInfo,\n\t\tisRelationField,\n\t\tgetRelationKind,\n\t\tinvalidateRelationCache,\n\t};\n}\n","// Typed row + draft-metadata model for the sheets grid.\n//\n// Draft metadata is attached to a row under a non-enumerable Symbol key so it\n// never collides with real column data and stays invisible to JSON.stringify\n// and key enumeration. NOTE: exactly like the previous non-enumerable string\n// markers (`__isDraft` etc.), this metadata does NOT survive an object spread\n// (`{ ...row }`) — callers must thread the row reference through rather than a\n// shallow copy. Use `copyDraftMeta()` when a copy is unavoidable.\nimport type { DraftRow } from '../store/draft-rows-slice';\n\n/** A grid row: arbitrary column values keyed by field name, plus an optional id. */\nexport type SheetsRow = Record<string, unknown> & { id?: string | number };\n\n/** Client-side draft metadata carried by a not-yet-persisted row. */\nexport interface DraftMeta {\n\treadonly isDraft: true;\n\treadonly draftRowId: string;\n\treadonly status: DraftRow['status'];\n\treadonly errors: Record<string, string> | null;\n}\n\nconst DRAFT_META: unique symbol = Symbol('sheets.draftMeta');\n\n/** A row that may carry draft metadata under the (non-enumerable) Symbol key. */\nexport type RowWithDraft<TRow extends SheetsRow = SheetsRow> = TRow & { readonly [DRAFT_META]?: DraftMeta };\n\n/** Attach draft metadata to a row in place (non-enumerable). Returns the same row, typed. */\nexport function attachDraftMeta<TRow extends SheetsRow>(row: TRow, meta: DraftMeta): RowWithDraft<TRow> {\n\tObject.defineProperty(row, DRAFT_META, { value: meta, enumerable: false, configurable: true });\n\treturn row as RowWithDraft<TRow>;\n}\n\n/** Read draft metadata, or undefined for a normal (server) row. */\nexport function getDraftMeta(row: SheetsRow | null | undefined): DraftMeta | undefined {\n\treturn row ? (row as RowWithDraft)[DRAFT_META] : undefined;\n}\n\n/** True when the row is a client-side draft. */\nexport function isDraftRow(row: SheetsRow | null | undefined): boolean {\n\treturn getDraftMeta(row)?.isDraft === true;\n}\n\n/** Re-attach draft metadata after an unavoidable shallow copy. */\nexport function copyDraftMeta<TRow extends SheetsRow>(from: SheetsRow | null | undefined, to: TRow): TRow {\n\tconst meta = getDraftMeta(from);\n\treturn meta ? (attachDraftMeta(to, meta) as TRow) : to;\n}\n","// Per-instance cell-type registry.\n//\n// This is a thin OVERRIDE LAYER over the built-in native rendering engine:\n// consumer definitions (from `SheetsConfig.plugins` and `<Sheets cellTypes>`)\n// win by `typeKey` and by `match()`, and anything they don't define falls back\n// to the built-in `toSheetsCell`. The built-in engine is injected so this module\n// stays free of a cell-types -> grid import cycle. The registry is created once\n// per <SheetsProvider> (same lifetime as the store), so it is SSR- and\n// multi-tenant-safe — no module singleton.\nimport type {\n\tCellTypeDefinition,\n\tCellTypeMatchInput,\n\tSheetsCellRenderContext,\n} from './define-cell-type';\nimport type { SheetsCell } from '../cell-model/sheets-cell';\nimport type { CellProps } from '../cell-model/cell-props';\nimport type { EditorProps } from '../grid-dom/editors/editor-props';\n\n/** The built-in engine the registry falls back to (injected to avoid a cycle). */\nexport interface CellTypeBuiltins {\n\ttoSheetsCell: (value: unknown, ctx: SheetsCellRenderContext) => SheetsCell;\n}\n\nexport interface CellTypeRegistry {\n\t/** Detection: consumer `match()` chain first (later defs win), else the built-in resolver. */\n\tresolveTypeKey(meta: CellTypeMatchInput, builtinFallback: () => string): string;\n\t/** Native display: consumer `def.toSheetsCell` for this typeKey, else the built-in renderer. */\n\ttoSheetsCell(typeKey: string, value: unknown, ctx: SheetsCellRenderContext): SheetsCell;\n\t/** The registered definition for a typeKey, if any (consumer defs only). */\n\tget(typeKey: string): CellTypeDefinition<any> | undefined;\n\t/** The native cell COMPONENT override for a typeKey, if any (consumer `def.cell`). */\n\tgetCellComponent(typeKey: string): React.ComponentType<CellProps> | undefined;\n\t/** The native EDITOR override for a typeKey, if any (consumer `def.editorComponent`). */\n\tgetEditorComponent(typeKey: string): React.ComponentType<EditorProps> | undefined;\n}\n\n/**\n * Build a registry. `cellTypes` are consumer definitions in precedence order\n * (provider `plugins` first, then per-instance `cellTypes`); later entries win,\n * so an instance-level def overrides a provider-level one with the same typeKey.\n */\nexport function createCellTypeRegistry(cellTypes: CellTypeDefinition<any>[], builtins: CellTypeBuiltins): CellTypeRegistry {\n\t// Index by typeKey — last write wins (instance overrides provider).\n\tconst byKey = new Map<string, CellTypeDefinition<any>>();\n\tfor (const def of cellTypes) byKey.set(def.typeKey, def);\n\n\t// Match list in REVERSE precedence so later (instance) defs are tried first.\n\tconst matchers = [...cellTypes].reverse().filter((d) => d.match);\n\n\treturn {\n\t\tresolveTypeKey(meta, builtinFallback) {\n\t\t\tfor (const def of matchers) {\n\t\t\t\tif (def.match!(meta)) return def.typeKey;\n\t\t\t}\n\t\t\treturn builtinFallback();\n\t\t},\n\t\ttoSheetsCell(typeKey, value, ctx) {\n\t\t\tconst def = byKey.get(typeKey);\n\t\t\treturn def?.toSheetsCell ? def.toSheetsCell(value, ctx) : builtins.toSheetsCell(value, ctx);\n\t\t},\n\t\tget(typeKey) {\n\t\t\treturn byKey.get(typeKey);\n\t\t},\n\t\tgetCellComponent(typeKey) {\n\t\t\treturn byKey.get(typeKey)?.cell;\n\t\t},\n\t\tgetEditorComponent(typeKey) {\n\t\t\treturn byKey.get(typeKey)?.editorComponent;\n\t\t},\n\t};\n}\n","// Consumer-facing cell-component override slots. A thin sugar over the native\n// `cell` field of a CellTypeDefinition: a `CellSlots` map (keyed by cell typeKey)\n// compiles down to component-only CellTypeDefinitions that the registry resolves\n// via `getCellComponent`. Pure logic — no React render, no glide.\n\nimport type { CellTypeDefinition } from '../cell-types/define-cell-type';\nimport type { CellProps } from './cell-props';\nimport type { EditorProps } from '../grid-dom/editors/editor-props';\n\n/**\n * A single slot: either a bare cell component, or an object overriding the cell\n * view and/or the native editor for a typeKey. The object form lets a consumer\n * override JUST the editor (`{ editor: MyEditor }`) without touching the view.\n */\nexport type CellSlot =\n\t| React.ComponentType<CellProps>\n\t| { cell?: React.ComponentType<CellProps>; editor?: React.ComponentType<EditorProps> };\n\n/** Consumer cell-component / editor overrides keyed by cell typeKey. */\nexport type CellSlots = Record<string, CellSlot>;\n\n/**\n * Compile a {@link CellSlots} map into {@link CellTypeDefinition}s. The function\n * form yields `{ typeKey, cell }` (view-only); the object form yields\n * `{ typeKey, cell?, editorComponent? }`. Entries that resolve to neither a cell\n * nor an editor (e.g. `{ json: {} }`) are skipped. Returns `[]` for empty/undefined.\n */\nexport function compileSlots(slots: CellSlots | undefined): CellTypeDefinition[] {\n\tif (!slots) return [];\n\tconst defs: CellTypeDefinition[] = [];\n\tfor (const [typeKey, slot] of Object.entries(slots)) {\n\t\tif (typeof slot === 'function') {\n\t\t\tdefs.push({ typeKey, cell: slot });\n\t\t\tcontinue;\n\t\t}\n\t\tconst { cell, editor } = slot;\n\t\tif (!cell && !editor) continue;\n\t\tdefs.push({ typeKey, cell, editorComponent: editor });\n\t}\n\treturn defs;\n}\n","export const DRAFT_ACTION_COLUMN_KEY = '__draft_action__';\n","import { useCallback } from 'react';\n\nimport { DRAFT_ACTION_COLUMN_KEY } from '../sheets.constants';\nimport { prepareDraftRelationValue } from '../sheets.utils';\nimport type { DraftRowsState } from './use-draft-rows';\nimport { getDraftMeta } from '../row-model';\nimport type { SheetsRowIdentifier } from '../../row-identity';\n\n/** Result from the useCellEditing hook */\nexport interface CellEditingResult {\n\t/** Type of edit: 'draft' for local draft row, 'server' for server mutation, 'noop' for no action */\n\ttype: 'draft' | 'server' | 'noop';\n\t/** The updated row data from the server (only for 'server' type) */\n\tupdatedRow?: Record<string, unknown> | null;\n\t/** The field that was patched (only for 'server' type) */\n\tpatchField?: string;\n\t/** The value that was sent (only for 'server' type) */\n\tpatchValue?: unknown;\n}\n\ninterface UseCellEditingParams {\n\tcombinedRows: any[];\n\tfieldMetaMap: Map<string, any>;\n\trelationInfoByField: Map<string, any>;\n\tupdateDraftCell: DraftRowsState['updateDraftCell'];\n\ttableKey: string;\n\tupdate: (id: SheetsRowIdentifier, data: Record<string, unknown>) => Promise<{ updatedRow?: Record<string, unknown> | null }>;\n\tgetRowIdentifier?: (row: Readonly<Record<string, unknown>>) => SheetsRowIdentifier | null;\n\treadOnlyFields?: ReadonlySet<string>;\n\tcanUpdate?: boolean;\n\tonCellEdit?: (id: SheetsRowIdentifier, field: string, value: unknown) => void;\n\t/**\n\t * Optimistic server-row cache patch. Applied to the local (infinite) cache BEFORE\n\t * the `update` round-trip so the cell flips instantly; returns a revert thunk that\n\t * the hook calls if `update` rejects. Omitted (e.g. paginated mode / unit tests) =>\n\t * no pre-await patch and the consumer reconciles after the await as before.\n\t */\n\tapplyOptimisticPatch?: (rowIndex: number, patch: Record<string, unknown>) => (() => void) | void;\n}\n\nfunction legacyRowIdentifier(row: Readonly<Record<string, unknown>>): SheetsRowIdentifier | null {\n\treturn typeof row.id === 'string' || typeof row.id === 'number' ? row.id : null;\n}\n\n/**\n * Normalize a relation value for a server PATCH: a JSON string is parsed, an array\n * is mapped to its ids (single id for belongsTo/hasOne, list otherwise), a single\n * object to its id. Mirrors the relation branch the canvas `handleCellEdit` ran,\n * but on the RAW native value instead of an extracted glide cell.\n */\nexport function normalizeRelationPatchValue(rawValue: unknown, relationKind: string | undefined): unknown {\n\tlet value = rawValue;\n\n\tif (typeof value === 'string') {\n\t\tconst trimmed = value.trim();\n\t\tif (trimmed === '') {\n\t\t\tvalue = null;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tvalue = JSON.parse(trimmed);\n\t\t\t} catch {\n\t\t\t\tvalue = trimmed;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (Array.isArray(value)) {\n\t\tconst mapped = value\n\t\t\t.map((entry) => (entry && typeof entry === 'object' ? ((entry as any).id ?? entry) : entry))\n\t\t\t.filter((entry) => entry !== undefined && entry !== null);\n\t\tvalue = relationKind === 'belongsTo' || relationKind === 'hasOne' ? (mapped[0] ?? null) : mapped;\n\t} else if (value && typeof value === 'object') {\n\t\tvalue = (value as any).id ?? null;\n\t}\n\n\tif (value === '') value = null;\n\treturn value;\n}\n\n/** The resolved server PATCH for one cell write, or a reason it is a no-op. */\nexport type ServerPatchResolution =\n\t| { kind: 'patch'; field: string; value: unknown }\n\t| { kind: 'noop' };\n\n/**\n * Derive the single-field server PATCH for a server-row cell write — the ONE place\n * that owns server-row coercion + readonly guards (UUID id / relation-not-inline /\n * undefined). Shared by `useCellEditing` (single cell) and the batched `commitCells`\n * (paste/fill/bulk) so neither forks the rules. PURE; never touches the cache or\n * network. `rowData` is the target row (skip callers must null-guard before calling).\n */\nexport function resolveServerPatch(\n\tcolKey: string,\n\trawValue: unknown,\n\tfieldMetaMap: Map<string, any>,\n\trelationInfoByField: Map<string, any>,\n\treadOnlyFields?: ReadonlySet<string>,\n): ServerPatchResolution {\n\tif (!colKey || colKey === DRAFT_ACTION_COLUMN_KEY) return { kind: 'noop' };\n\tif (readOnlyFields?.has(colKey)) return { kind: 'noop' };\n\n\t// Block edits to the UUID primary key id.\n\tconst metaField = fieldMetaMap.get(colKey);\n\tif (colKey === 'id' && metaField?.type?.gqlType === 'UUID') return { kind: 'noop' };\n\n\tconst relationInfo = relationInfoByField.get(colKey);\n\tlet value: unknown = rawValue;\n\n\tif (relationInfo) {\n\t\tconst patchFieldCandidate = relationInfo.foreignKeyField || colKey;\n\t\tconst canEditRelationInline = relationInfo.kind === 'belongsTo' && fieldMetaMap.has(patchFieldCandidate);\n\t\tif (!canEditRelationInline) return { kind: 'noop' };\n\t\tvalue = normalizeRelationPatchValue(rawValue, relationInfo.kind);\n\t}\n\n\tif (value === undefined) return { kind: 'noop' };\n\n\tconst field = relationInfo?.foreignKeyField || colKey;\n\treturn { kind: 'patch', field, value };\n}\n\nexport function useCellEditing({\n\tcombinedRows,\n\tfieldMetaMap,\n\trelationInfoByField,\n\tupdateDraftCell,\n\ttableKey,\n\tupdate,\n\tgetRowIdentifier = legacyRowIdentifier,\n\treadOnlyFields,\n\tcanUpdate = true,\n\tonCellEdit,\n\tapplyOptimisticPatch,\n}: UseCellEditingParams) {\n\treturn useCallback(\n\t\t// NATIVE signature: the DOM editors / inline-toggle pass a raw value that flows\n\t\t// straight through — no glide cell round-trip. This is what fixes the boolean\n\t\t// toggle: a raw `false` persists as `false`, never stringified to \"false\".\n\t\tasync (rowIndex: number, colKey: string, rawValue: unknown): Promise<CellEditingResult> => {\n\t\t\tconst rowData = combinedRows[rowIndex];\n\t\t\tif (!colKey || !rowData) return { type: 'noop' };\n\n\t\t\tif (colKey === DRAFT_ACTION_COLUMN_KEY) {\n\t\t\t\treturn { type: 'noop' };\n\t\t\t}\n\n\t\t\tconst draftMeta = getDraftMeta(rowData);\n\t\t\tif (draftMeta?.isDraft && colKey === 'id') {\n\t\t\t\treturn { type: 'noop' };\n\t\t\t}\n\n\t\t\tif (draftMeta?.isDraft) {\n\t\t\t\tconst draftRowId: string | undefined = draftMeta.draftRowId;\n\t\t\t\tif (!draftRowId) return { type: 'noop' };\n\n\t\t\t\tconst baseValue = rawValue;\n\t\t\t\tconst relationInfo = relationInfoByField.get(colKey);\n\n\t\t\t\tlet storedValue: unknown = baseValue;\n\t\t\t\tlet extraValues: Record<string, unknown> | undefined;\n\n\t\t\t\tif (relationInfo) {\n\t\t\t\t\tconst { relationData, foreignKeyUpdates, relationReferences } = prepareDraftRelationValue(\n\t\t\t\t\t\tbaseValue,\n\t\t\t\t\t\trelationInfo,\n\t\t\t\t\t);\n\t\t\t\t\tconst relationFieldKey = relationInfo.relationField;\n\t\t\t\t\tconst foreignKeyFieldKey = relationInfo.foreignKeyField;\n\t\t\t\t\tconst editingRelationField = relationFieldKey ? relationFieldKey === colKey : false;\n\t\t\t\t\tconst editingForeignKeyField = foreignKeyFieldKey ? foreignKeyFieldKey === colKey : false;\n\n\t\t\t\t\tconst processedRelationData = Array.isArray(relationData)\n\t\t\t\t\t\t? relationData.filter((entry) => entry !== undefined)\n\t\t\t\t\t\t: relationData;\n\n\t\t\t\t\tconst relationExtra = relationFieldKey\n\t\t\t\t\t\t? processedRelationData === undefined\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: processedRelationData === null\n\t\t\t\t\t\t\t\t? { [relationFieldKey]: null }\n\t\t\t\t\t\t\t\t: typeof processedRelationData === 'object'\n\t\t\t\t\t\t\t\t\t? { [relationFieldKey]: processedRelationData }\n\t\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tconst processedReferenceValue = Array.isArray(relationReferences)\n\t\t\t\t\t\t? relationReferences.filter((entry) => entry !== undefined)\n\t\t\t\t\t\t: relationReferences;\n\n\t\t\t\t\tconst foreignKeyExtra = foreignKeyFieldKey\n\t\t\t\t\t\t? processedReferenceValue !== undefined\n\t\t\t\t\t\t\t? { [foreignKeyFieldKey]: processedReferenceValue }\n\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tif (editingRelationField) {\n\t\t\t\t\t\tstoredValue = processedRelationData;\n\t\t\t\t\t\textraValues = {\n\t\t\t\t\t\t\t...(foreignKeyUpdates ?? {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t} else if (editingForeignKeyField) {\n\t\t\t\t\t\tstoredValue = processedReferenceValue ?? processedRelationData;\n\t\t\t\t\t\textraValues = {\n\t\t\t\t\t\t\t...(foreignKeyUpdates ?? {}),\n\t\t\t\t\t\t\t...(relationExtra ?? {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstoredValue = processedRelationData;\n\t\t\t\t\t\textraValues = {\n\t\t\t\t\t\t\t...(foreignKeyUpdates ?? {}),\n\t\t\t\t\t\t\t...(relationExtra ?? {}),\n\t\t\t\t\t\t\t...(foreignKeyExtra ?? {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tupdateDraftCell({\n\t\t\t\t\ttableKey,\n\t\t\t\t\tdraftRowId,\n\t\t\t\t\tcolumnKey: colKey,\n\t\t\t\t\tvalue: storedValue,\n\t\t\t\t\textraValues: extraValues && Object.keys(extraValues).length > 0 ? extraValues : undefined,\n\t\t\t\t});\n\t\t\t\treturn { type: 'draft' };\n\t\t\t}\n\n\t\t\t// Server row edit — derive the PATCH via the shared resolver (the single owner\n\t\t\t// of server-row coercion + readonly guards, also used by batched `commitCells`).\n\t\t\tif (!canUpdate) return { type: 'noop' };\n\t\t\tconst resolution = resolveServerPatch(colKey, rawValue, fieldMetaMap, relationInfoByField, readOnlyFields);\n\t\t\tif (resolution.kind === 'noop') return { type: 'noop' };\n\t\t\tconst { field: patchField, value } = resolution;\n\t\t\tconst rowIdentifier = getRowIdentifier(rowData);\n\t\t\tif (rowIdentifier === null) return { type: 'noop' };\n\n\t\t\t// Optimistic: patch the local cache with the new value BEFORE awaiting the\n\t\t\t// server so the cell updates instantly. `applyOptimisticPatch` returns a revert\n\t\t\t// thunk (snapshot of the prior value) which we replay only if `update` rejects.\n\t\t\tconst revertOptimisticPatch = applyOptimisticPatch?.(rowIndex, { [patchField]: value });\n\n\t\t\tlet result: { updatedRow?: Record<string, unknown> | null };\n\t\t\ttry {\n\t\t\t\tresult = await update(rowIdentifier, { [patchField]: value });\n\t\t\t} catch (error) {\n\t\t\t\tif (typeof revertOptimisticPatch === 'function') revertOptimisticPatch();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tonCellEdit?.(rowIdentifier, patchField, value);\n\n\t\t\treturn {\n\t\t\t\ttype: 'server',\n\t\t\t\tupdatedRow: result?.updatedRow ?? null,\n\t\t\t\tpatchField,\n\t\t\t\tpatchValue: value,\n\t\t\t};\n\t\t},\n\t\t[combinedRows, fieldMetaMap, relationInfoByField, tableKey, update, getRowIdentifier, readOnlyFields, canUpdate, onCellEdit, updateDraftCell, applyOptimisticPatch],\n\t);\n}\n","/**\n * useBatchCommit — the batched cell-value commit primitive behind paste / fill /\n * bulk-edit AND (routed through it) the single-cell edit, so EVERY server-row value\n * write is one undoable, coalesced operation.\n *\n * It owns NO coercion/readonly rules of its own: server-row writes go through the\n * shared {@link resolveServerPatch} (the same resolver `useCellEditing` uses), so the\n * UUID-id guard, relation normalization and readonly skips stay in ONE place.\n *\n * Coalescing contract (load-bearing for a 1000-cell paste):\n * • prior values are captured from `combinedRows` BEFORE any optimistic patch, so\n * undo restores the EXACT pre-edit value.\n * • ONE optimistic cache patch is applied per affected ROW (merged col patches),\n * not per cell — N rows -> N patches, never N×cols.\n * • ONE server `update(rowId, {merged})` is issued per row.\n * • when recording, the HistoryEntry's `undo`/`redo` re-enter `commitCells` with\n * `{ record: false }` so replays never double-record.\n *\n * Draft-row writes are NOT batched here — they route to the existing per-cell draft\n * path (`editCell`) and are excluded from history (draft undo is out of P3 scope).\n */\nimport { useCallback, useRef } from 'react';\n\nimport { resolveServerPatch } from './use-cell-editing';\nimport type { CellEditingResult } from './use-cell-editing';\nimport { getDraftMeta, type SheetsRow } from '../row-model';\nimport type { SheetsRowIdentifier } from '../../row-identity';\n\n/** A single cell write request. */\nexport interface CellWrite {\n\trowIndex: number;\n\tcolKey: string;\n\tvalue: unknown;\n}\n\nexport interface CommitCellsOptions {\n\t/** When false, the commit is NOT pushed to history (used by undo/redo replays). Default true. */\n\trecord?: boolean;\n}\n\nexport interface CommitCellsResult {\n\t/** Number of server cells actually written (post readonly/null/no-op filtering). */\n\tapplied: number;\n}\n\ninterface UseBatchCommitParams {\n\tcombinedRows: SheetsRow[];\n\tfieldMetaMap: Map<string, any>;\n\trelationInfoByField: Map<string, any>;\n\tupdate: (id: SheetsRowIdentifier, data: Record<string, unknown>) => Promise<{ updatedRow?: Record<string, unknown> | null }>;\n\tgetRowIdentifier?: (row: Readonly<Record<string, unknown>>) => SheetsRowIdentifier | null;\n\treadOnlyFields?: ReadonlySet<string>;\n\tcanUpdate?: boolean;\n\t/** Single-write optimistic cache patch (infinite mode) — returns a revert thunk. */\n\tapplyOptimisticPatch?: (rowIndex: number, patch: Record<string, unknown>) => (() => void) | void;\n\t/** Re-sync a server row over the optimistic patch after the mutation resolves (infinite mode). */\n\tresyncRow?: (rowIndex: number, updatedRow: Record<string, unknown>) => void;\n\t/** Existing per-cell editor (draft routing + single-cell server coercion). */\n\teditCell: (rowIndex: number, colKey: string, rawValue: unknown) => Promise<CellEditingResult>;\n\t/** Observational per-server-write callback (mirrors useCellEditing's onCellEdit). */\n\tonCellEdit?: (id: SheetsRowIdentifier, field: string, value: unknown) => void;\n\t/** Push a reversible step to the history. */\n\trecord: (entry: { label: string; undo: () => Promise<void> | void; redo: () => Promise<void> | void }) => void;\n}\n\n/** A resolved server write: its row, the patch field, the next + prior values. */\ninterface ResolvedWrite {\n\trowIndex: number;\n\trowId: SheetsRowIdentifier;\n\tfield: string;\n\tvalue: unknown;\n\tprior: unknown;\n}\n\nfunction legacyRowIdentifier(row: Readonly<Record<string, unknown>>): SheetsRowIdentifier | null {\n\treturn typeof row.id === 'string' || typeof row.id === 'number' ? row.id : null;\n}\n\nexport function useBatchCommit({\n\tcombinedRows,\n\tfieldMetaMap,\n\trelationInfoByField,\n\tupdate,\n\tgetRowIdentifier = legacyRowIdentifier,\n\treadOnlyFields,\n\tcanUpdate = true,\n\tapplyOptimisticPatch,\n\tresyncRow,\n\teditCell,\n\tonCellEdit,\n\trecord,\n}: UseBatchCommitParams) {\n\t// Holds the latest commitCells so a recorded HistoryEntry (captured at record-time)\n\t// always re-enters the CURRENT closure — avoids a stale-row snapshot. Per-hook\n\t// instance, so multiple grids never share a commit fn.\n\tconst commitRef = useRef<((writes: CellWrite[], opts?: CommitCellsOptions) => Promise<CommitCellsResult>) | null>(null);\n\n\tconst commitCells = useCallback(\n\t\tasync (writes: CellWrite[], opts?: CommitCellsOptions): Promise<CommitCellsResult> => {\n\t\t\tif (!writes.length) return { applied: 0 };\n\n\t\t\tconst resolved: ResolvedWrite[] = [];\n\t\t\tconst draftWrites: CellWrite[] = [];\n\n\t\t\tfor (const w of writes) {\n\t\t\t\tconst rowData = combinedRows[w.rowIndex] as Record<string, unknown> | null | undefined;\n\t\t\t\t// Null-guard unfetched proxy rows — skip writes whose row is not loaded.\n\t\t\t\tif (!rowData) continue;\n\n\t\t\t\t// Draft rows keep their existing per-cell path; excluded from coalescing + history.\n\t\t\t\tif (getDraftMeta(rowData)) {\n\t\t\t\t\tdraftWrites.push(w);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (!canUpdate) continue;\n\t\t\t\tconst resolution = resolveServerPatch(w.colKey, w.value, fieldMetaMap, relationInfoByField, readOnlyFields);\n\t\t\t\tif (resolution.kind === 'noop') continue;\n\t\t\t\tconst rowIdentifier = getRowIdentifier(rowData);\n\t\t\t\tif (rowIdentifier === null) continue;\n\n\t\t\t\tresolved.push({\n\t\t\t\t\trowIndex: w.rowIndex,\n\t\t\t\t\trowId: rowIdentifier,\n\t\t\t\t\tfield: resolution.field,\n\t\t\t\t\tvalue: resolution.value,\n\t\t\t\t\t// Capture the PRIOR value of the patched field BEFORE any optimistic patch.\n\t\t\t\t\tprior: rowData[resolution.field],\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Fire draft writes through the existing path (not batched, not recorded).\n\t\t\tfor (const dw of draftWrites) {\n\t\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\t\tawait editCell(dw.rowIndex, dw.colKey, dw.value);\n\t\t\t}\n\n\t\t\tif (!resolved.length) return { applied: 0 };\n\n\t\t\t// Group by row: one merged optimistic patch + one merged server PATCH per row.\n\t\t\tconst byRow = new Map<number, ResolvedWrite[]>();\n\t\t\tfor (const r of resolved) {\n\t\t\t\tconst list = byRow.get(r.rowIndex);\n\t\t\t\tif (list) list.push(r);\n\t\t\t\telse byRow.set(r.rowIndex, [r]);\n\t\t\t}\n\n\t\t\t// Apply ONE optimistic patch per row (merged) and collect revert thunks.\n\t\t\tconst reverts: Array<() => void> = [];\n\t\t\tfor (const [rowIndex, group] of byRow) {\n\t\t\t\tconst patch: Record<string, unknown> = {};\n\t\t\t\tfor (const r of group) patch[r.field] = r.value;\n\t\t\t\tconst revert = applyOptimisticPatch?.(rowIndex, patch);\n\t\t\t\tif (revert) reverts.push(revert);\n\t\t\t}\n\n\t\t\t// Issue ONE server mutation per row; revert ALL optimistic patches on first failure.\n\t\t\ttry {\n\t\t\t\tfor (const [rowIndex, group] of byRow) {\n\t\t\t\t\tconst patch: Record<string, unknown> = {};\n\t\t\t\t\tfor (const r of group) patch[r.field] = r.value;\n\t\t\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\t\t\tconst result = await update(group[0].rowId, patch);\n\t\t\t\t\tif (result?.updatedRow) resyncRow?.(rowIndex, result.updatedRow);\n\t\t\t\t\tfor (const r of group) onCellEdit?.(r.rowId, r.field, r.value);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tfor (const revert of reverts) revert();\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\t// Record the inverse (prior values) so undo restores the exact pre-edit state.\n\t\t\tif (opts?.record !== false) {\n\t\t\t\tconst priorWrites: CellWrite[] = resolved.map((r) => ({\n\t\t\t\t\trowIndex: r.rowIndex,\n\t\t\t\t\tcolKey: r.field,\n\t\t\t\t\tvalue: r.prior,\n\t\t\t\t}));\n\t\t\t\tconst redoWrites: CellWrite[] = resolved.map((r) => ({\n\t\t\t\t\trowIndex: r.rowIndex,\n\t\t\t\t\tcolKey: r.field,\n\t\t\t\t\tvalue: r.value,\n\t\t\t\t}));\n\t\t\t\t// Capture the live commit fn via the closure below (commitRef).\n\t\t\t\trecord({\n\t\t\t\t\tlabel: resolved.length > 1 ? `Edit ${resolved.length} cells` : 'Edit cell',\n\t\t\t\t\tundo: () => void commitRef.current?.(priorWrites, { record: false }),\n\t\t\t\t\tredo: () => void commitRef.current?.(redoWrites, { record: false }),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn { applied: resolved.length };\n\t\t},\n\t\t[combinedRows, fieldMetaMap, relationInfoByField, update, getRowIdentifier, readOnlyFields, canUpdate, applyOptimisticPatch, resyncRow, editCell, onCellEdit, record],\n\t);\n\n\tcommitRef.current = commitCells;\n\treturn commitCells;\n}\n","/**\n * useUndoRedo — a tiny two-stack history for grid mutations.\n *\n * Each {@link HistoryEntry} carries its own inverse: `undo` reverts the change,\n * `redo` re-applies it (both may be async — a server mutation). `record` pushes a\n * new entry onto the undo stack and CLEARS the redo stack (a fresh edit forks the\n * timeline). `undo`/`redo` move the top entry across the two stacks, running the\n * matching thunk.\n *\n * The stacks live in refs so the handler identities (`undo`/`redo`/`record`) stay\n * STABLE across renders — keydown wiring binds them once. `canUndo`/`canRedo` are\n * reactive (state) so chrome can disable buttons. Depth is capped to bound memory.\n */\nimport { useCallback, useRef, useState } from 'react';\n\n/** One reversible step: a label plus its undo / redo thunks. */\nexport interface HistoryEntry {\n\tlabel: string;\n\tundo: () => Promise<void> | void;\n\tredo: () => Promise<void> | void;\n}\n\nexport interface UseUndoRedoResult {\n\t/** Push a new entry; clears the redo stack. */\n\trecord: (entry: HistoryEntry) => void;\n\t/** Pop the top undo entry, run its `undo`, push it to the redo stack. No-op when empty. */\n\tundo: () => Promise<void>;\n\t/** Pop the top redo entry, run its `redo`, push it to the undo stack. No-op when empty. */\n\tredo: () => Promise<void>;\n\t/** True when the undo stack is non-empty. */\n\tcanUndo: boolean;\n\t/** True when the redo stack is non-empty. */\n\tcanRedo: boolean;\n\t/** Drop all history. */\n\tclear: () => void;\n}\n\nconst DEFAULT_MAX_DEPTH = 100;\n\nexport function useUndoRedo(maxDepth: number = DEFAULT_MAX_DEPTH): UseUndoRedoResult {\n\tconst undoStack = useRef<HistoryEntry[]>([]);\n\tconst redoStack = useRef<HistoryEntry[]>([]);\n\tconst [canUndo, setCanUndo] = useState(false);\n\tconst [canRedo, setCanRedo] = useState(false);\n\n\tconst sync = useCallback(() => {\n\t\tsetCanUndo(undoStack.current.length > 0);\n\t\tsetCanRedo(redoStack.current.length > 0);\n\t}, []);\n\n\tconst record = useCallback(\n\t\t(entry: HistoryEntry) => {\n\t\t\tundoStack.current.push(entry);\n\t\t\tif (undoStack.current.length > maxDepth) undoStack.current.shift();\n\t\t\tredoStack.current = [];\n\t\t\tsync();\n\t\t},\n\t\t[maxDepth, sync],\n\t);\n\n\tconst undo = useCallback(async () => {\n\t\tconst entry = undoStack.current.pop();\n\t\tif (!entry) return;\n\t\tredoStack.current.push(entry);\n\t\tsync();\n\t\tawait entry.undo();\n\t}, [sync]);\n\n\tconst redo = useCallback(async () => {\n\t\tconst entry = redoStack.current.pop();\n\t\tif (!entry) return;\n\t\tundoStack.current.push(entry);\n\t\tsync();\n\t\tawait entry.redo();\n\t}, [sync]);\n\n\tconst clear = useCallback(() => {\n\t\tundoStack.current = [];\n\t\tredoStack.current = [];\n\t\tsync();\n\t}, [sync]);\n\n\treturn { record, undo, redo, canUndo, canRedo, clear };\n}\n","import { useMemo } from 'react';\n\nimport { useSheetsStore } from '../../store/sheets-store';\nimport type { DraftRow, DraftRowsSlice } from '../../store/draft-rows-slice';\nimport { attachDraftMeta, isDraftRow } from '../row-model';\n\ninterface DraftRowsTableState {\n\torder: string[];\n\tmap: Record<string, DraftRow>;\n\ttemplate: Record<string, unknown>;\n\tmetaVersion: string;\n\tcolumnOrder: string[];\n}\n\ninterface UseDraftRowsParams {\n\ttableKey: string;\n\tserverRows: any[];\n\thasCompletedInitialLoad: boolean;\n}\n\nexport interface DraftRowsState {\n\tdraftRowsTable?: DraftRowsTableState;\n\tdraftRows: DraftRow[];\n\thasDraftRows: boolean;\n\tcombinedRows: any[];\n\tdraftRowIndices: number[];\n\tcreateDraftRow: DraftRowsSlice['createDraftRow'];\n\tupdateDraftCell: DraftRowsSlice['updateDraftCell'];\n\tremoveDraftRow: DraftRowsSlice['removeDraftRow'];\n\tsyncDraftRowsWithMeta: DraftRowsSlice['syncDraftRowsWithMeta'];\n\tsetDraftRowStatus: DraftRowsSlice['setDraftRowStatus'];\n}\n\nexport function useDraftRows({\n\ttableKey,\n\tserverRows,\n\thasCompletedInitialLoad,\n}: UseDraftRowsParams): DraftRowsState {\n\tconst draftRowsTable = useSheetsStore(\n\t\t(state) => state.draftRowsByTable[tableKey] as DraftRowsTableState | undefined,\n\t);\n\tconst createDraftRow = useSheetsStore((state) => state.createDraftRow);\n\tconst updateDraftCell = useSheetsStore((state) => state.updateDraftCell);\n\tconst removeDraftRow = useSheetsStore((state) => state.removeDraftRow);\n\tconst syncDraftRowsWithMeta = useSheetsStore((state) => state.syncDraftRowsWithMeta);\n\tconst setDraftRowStatus = useSheetsStore((state) => state.setDraftRowStatus);\n\n\tconst draftRows = useMemo(() => {\n\t\tif (!draftRowsTable) return [] as DraftRow[];\n\t\treturn draftRowsTable.order.map((id) => draftRowsTable.map[id]).filter((row): row is DraftRow => Boolean(row));\n\t}, [draftRowsTable]);\n\n\tconst mayShowDrafts = hasCompletedInitialLoad || serverRows.length > 0 || draftRows.length > 0;\n\n\tconst combinedRows = useMemo(() => {\n\t\tif (!draftRows.length || !mayShowDrafts) return serverRows as any[];\n\n\t\tconst draftDataRows = draftRows.map((draft) => {\n\t\t\tconst row = { ...draft.values } as Record<string, unknown>;\n\t\t\treturn attachDraftMeta(row, {\n\t\t\t\tisDraft: true,\n\t\t\t\tdraftRowId: draft.id,\n\t\t\t\tstatus: draft.status,\n\t\t\t\terrors: draft.errors,\n\t\t\t});\n\t\t});\n\n\t\treturn [...(serverRows as any[]), ...draftDataRows];\n\t}, [serverRows, draftRows, mayShowDrafts]);\n\n\tconst draftRowIndices = useMemo(() => {\n\t\tconst indices: number[] = [];\n\t\tcombinedRows.forEach((row, index) => {\n\t\t\tif (isDraftRow(row)) {\n\t\t\t\tindices.push(index);\n\t\t\t}\n\t\t});\n\t\treturn indices;\n\t}, [combinedRows]);\n\n\tconst hasDraftRows = draftRows.length > 0 && mayShowDrafts;\n\n\treturn {\n\t\tdraftRowsTable,\n\t\tdraftRows,\n\t\thasDraftRows,\n\t\tcombinedRows,\n\t\tdraftRowIndices,\n\t\tcreateDraftRow,\n\t\tupdateDraftCell,\n\t\tremoveDraftRow,\n\t\tsyncDraftRowsWithMeta,\n\t\tsetDraftRowStatus,\n\t};\n}\n","import { useCallback, useMemo, useState } from 'react';\n\nimport type { RelationInfo } from '../../store/relation-info-slice';\nimport type { DraftRow } from '../../store/draft-rows-slice';\nimport { SHEETS_CONCURRENCY } from '../../config/sheets-concurrency';\n\nimport { prepareDraftSubmissionPayload, validateDraftRowRequiredFields, type DraftValidationFieldMeta } from '../sheets.utils';\nimport type { DraftSubmitResult } from '../draft-types';\nimport type { DraftRowEntry } from './use-grid-selection';\nimport { sheetsLogger } from '../../utils/sheets-logger';\n\ninterface DraftRowsTableState {\n\torder: string[];\n\tmap: Record<string, DraftRow>;\n\ttemplate: Record<string, unknown>;\n\tmetaVersion: string;\n\tcolumnOrder: string[];\n}\n\ninterface OperationFeedbackCallbacks {\n\tonStart?: (type: 'submit', total: number) => string;\n\tonProgress?: (id: string, completed: number, failed: number) => void;\n\tonComplete?: (id: string, status: 'success' | 'partial' | 'error', message: string) => void;\n}\n\ninterface UseDraftSubmissionParams {\n\ttableKey: string;\n\tdraftRowsTable?: DraftRowsTableState;\n\tselectedDraftRowEntries: DraftRowEntry[];\n\thasDraftSelection: boolean;\n\tcreate: (data: Record<string, unknown>) => Promise<{ createdRow?: Record<string, unknown> | null }>;\n\tremoveDraftRow: (tableKey: string, draftRowId: string) => void;\n\tsetDraftRowStatus: (args: {\n\t\ttableKey: string;\n\t\tdraftRowId: string;\n\t\tstatus: DraftRow['status'];\n\t\terrors?: Record<string, string> | null;\n\t}) => void;\n\tclearSelection: () => void;\n\tallowedColumns?: ReadonlySet<string>;\n\trelationInfoByKey?: Record<string, RelationInfo | undefined>;\n\tfieldMetaByKey?: Record<string, DraftValidationFieldMeta | undefined>;\n\tonSubmittedSuccessfully?: (result: { success: number; failed: number }) => void;\n\t/** Feedback callbacks for inline status indicators */\n\tfeedback?: OperationFeedbackCallbacks;\n}\n\nexport function useDraftSubmission({\n\ttableKey,\n\tdraftRowsTable,\n\tselectedDraftRowEntries,\n\thasDraftSelection,\n\tcreate,\n\tremoveDraftRow,\n\tsetDraftRowStatus,\n\tclearSelection,\n\tallowedColumns,\n\trelationInfoByKey,\n\tfieldMetaByKey,\n\tonSubmittedSuccessfully,\n\tfeedback,\n}: UseDraftSubmissionParams) {\n\tconst [isSubmittingDrafts, setIsSubmittingDrafts] = useState(false);\n\n\tconst submitDraftEntries = useCallback(\n\t\tasync (entries: DraftRowEntry[], operationId?: string): Promise<{ success: number; failed: number }> => {\n\t\t\tif (!entries.length) {\n\t\t\t\treturn { success: 0, failed: 0 };\n\t\t\t}\n\n\t\t\tsetIsSubmittingDrafts(true);\n\n\t\t\tconst submissionResults = {\n\t\t\t\tsuccess: 0,\n\t\t\t\tfailed: 0,\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tlet nextEntryIndex = 0;\n\t\t\t\tconst workerCount = Math.min(SHEETS_CONCURRENCY.draftSubmit, entries.length);\n\n\t\t\t\tconst runSubmitWorker = async () => {\n\t\t\t\t\twhile (nextEntryIndex < entries.length) {\n\t\t\t\t\t\tconst currentIndex = nextEntryIndex;\n\t\t\t\t\t\tnextEntryIndex += 1;\n\t\t\t\t\t\tconst { draftRowId, draftRow } = entries[currentIndex];\n\n\t\t\t\t\t\t// Pre-validate required fields before sending to server\n\t\t\t\t\t\tif (fieldMetaByKey) {\n\t\t\t\t\t\t\tconst validationErrors = validateDraftRowRequiredFields(\n\t\t\t\t\t\t\t\tdraftRow.values,\n\t\t\t\t\t\t\t\tfieldMetaByKey,\n\t\t\t\t\t\t\t\t{ allowedColumns, relationInfoByKey },\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (Object.keys(validationErrors).length > 0) {\n\t\t\t\t\t\t\t\tsubmissionResults.failed += 1;\n\t\t\t\t\t\t\t\tsetDraftRowStatus({ tableKey, draftRowId, status: 'error', errors: validationErrors });\n\t\t\t\t\t\t\t\tif (operationId) {\n\t\t\t\t\t\t\t\t\tfeedback?.onProgress?.(operationId, submissionResults.success, submissionResults.failed);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsetDraftRowStatus({ tableKey, draftRowId, status: 'saving', errors: null });\n\t\t\t\t\t\tconst payload = prepareDraftSubmissionPayload(draftRow.values, {\n\t\t\t\t\t\t\tallowedColumns,\n\t\t\t\t\t\t\trelationInfoByKey,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait create(payload);\n\t\t\t\t\t\t\tremoveDraftRow(tableKey, draftRowId);\n\t\t\t\t\t\t\tsubmissionResults.success += 1;\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tsubmissionResults.failed += 1;\n\t\t\t\t\t\t\tconst message = error instanceof Error ? error.message : 'Failed to submit draft row';\n\t\t\t\t\t\t\tsheetsLogger().error('submitDraftRow failed', error);\n\t\t\t\t\t\t\tsetDraftRowStatus({ tableKey, draftRowId, status: 'error', errors: { submit: message } });\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (operationId) {\n\t\t\t\t\t\t\tfeedback?.onProgress?.(\n\t\t\t\t\t\t\t\toperationId,\n\t\t\t\t\t\t\t\tsubmissionResults.success,\n\t\t\t\t\t\t\t\tsubmissionResults.failed,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tawait Promise.all(Array.from({ length: workerCount }, () => runSubmitWorker()));\n\t\t\t} finally {\n\t\t\t\tsetIsSubmittingDrafts(false);\n\t\t\t}\n\n\t\t\tif (submissionResults.success > 0) {\n\t\t\t\tonSubmittedSuccessfully?.(submissionResults);\n\t\t\t}\n\n\t\t\treturn submissionResults;\n\t\t},\n\t\t[\n\t\t\tallowedColumns,\n\t\t\trelationInfoByKey,\n\t\t\tfieldMetaByKey,\n\t\t\tcreate,\n\t\t\tremoveDraftRow,\n\t\t\tsetDraftRowStatus,\n\t\t\ttableKey,\n\t\t\tfeedback,\n\t\t\tonSubmittedSuccessfully,\n\t\t],\n\t);\n\n\tconst handleSubmitDraftRows = useCallback(async () => {\n\t\tif (!draftRowsTable || !hasDraftSelection) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst total = selectedDraftRowEntries.length;\n\t\tconst operationId = feedback?.onStart?.('submit', total);\n\n\t\tconst submissionResults = await submitDraftEntries(selectedDraftRowEntries, operationId);\n\n\t\tif (operationId) {\n\t\t\tconst { success, failed } = submissionResults;\n\t\t\tif (failed === 0 && success > 0) {\n\t\t\t\tfeedback?.onComplete?.(\n\t\t\t\t\toperationId,\n\t\t\t\t\t'success',\n\t\t\t\t\t`Submitted ${success} ${success === 1 ? 'row' : 'rows'}`,\n\t\t\t\t);\n\t\t\t} else if (success > 0 && failed > 0) {\n\t\t\t\tfeedback?.onComplete?.(\n\t\t\t\t\toperationId,\n\t\t\t\t\t'partial',\n\t\t\t\t\t`Submitted ${success}, ${failed} failed`,\n\t\t\t\t);\n\t\t\t} else if (failed > 0) {\n\t\t\t\tfeedback?.onComplete?.(\n\t\t\t\t\toperationId,\n\t\t\t\t\t'error',\n\t\t\t\t\t`Failed to submit ${failed} ${failed === 1 ? 'row' : 'rows'}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif (submissionResults.success > 0) {\n\t\t\tclearSelection();\n\t\t}\n\t}, [draftRowsTable, hasDraftSelection, selectedDraftRowEntries, submitDraftEntries, clearSelection, feedback]);\n\n\tconst handleSubmitSingleDraftRow = useCallback(\n\t\tasync (draftRowId: string) => {\n\t\t\tif (!draftRowsTable) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst draftRow = draftRowsTable.map[draftRowId];\n\t\t\tif (!draftRow) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Single row submission - no operation feedback, rely on row status indicator\n\t\t\tawait submitDraftEntries([{ draftRowId, draftRow }]);\n\t\t},\n\t\t[draftRowsTable, submitDraftEntries],\n\t);\n\n\tconst submitDraftLabel = useMemo(() => {\n\t\tif (!hasDraftSelection) {\n\t\t\treturn 'Submit draft rows';\n\t\t}\n\t\tconst count = selectedDraftRowEntries.length;\n\t\treturn `Submit ${count} draft ${count === 1 ? 'row' : 'rows'}`;\n\t}, [hasDraftSelection, selectedDraftRowEntries.length]);\n\n\tconst submitDraftButtonDisabled = isSubmittingDrafts || !hasDraftSelection;\n\n\t/**\n\t * Submit a single draft row for editor workflows (e.g., ImageEditor upload).\n\t * Returns the created row with real database ID for subsequent operations.\n\t *\n\t * NOTE: This does NOT call onSingleRowSubmitted - the editor is responsible\n\t * for triggering data refresh after any follow-up operations (like upload)\n\t * are complete. This prevents premature cache invalidation.\n\t */\n\tconst submitDraftRowForEditor = useCallback(\n\t\tasync (draftRowId: string): Promise<DraftSubmitResult> => {\n\t\t\tif (!draftRowsTable) {\n\t\t\t\treturn { createdRow: null };\n\t\t\t}\n\n\t\t\tconst draftRow = draftRowsTable.map[draftRowId];\n\t\t\tif (!draftRow) {\n\t\t\t\treturn { createdRow: null };\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tsetDraftRowStatus({ tableKey, draftRowId, status: 'saving', errors: null });\n\n\t\t\t\tconst payload = prepareDraftSubmissionPayload(draftRow.values, {\n\t\t\t\t\tallowedColumns,\n\t\t\t\t\trelationInfoByKey,\n\t\t\t\t});\n\n\t\t\t\tconst result = await create(payload);\n\t\t\t\tconst createdRow = result?.createdRow ?? null;\n\n\t\t\t\tif (createdRow) {\n\t\t\t\t\tremoveDraftRow(tableKey, draftRowId);\n\t\t\t\t\t// NOTE: Don't call onSingleRowSubmitted here - let the editor\n\t\t\t\t\t// trigger refresh after follow-up operations complete\n\t\t\t\t}\n\n\t\t\t\treturn { createdRow };\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : 'Failed to create row';\n\t\t\t\tsetDraftRowStatus({ tableKey, draftRowId, status: 'error', errors: { submit: message } });\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\t[draftRowsTable, setDraftRowStatus, tableKey, allowedColumns, relationInfoByKey, create, removeDraftRow],\n\t);\n\n\treturn {\n\t\tisSubmittingDrafts,\n\t\tsubmitDraftButtonDisabled,\n\t\tsubmitDraftLabel,\n\t\thandleSubmitDraftRows,\n\t\thandleSubmitSingleDraftRow,\n\t\tsubmitDraftRowForEditor,\n\t};\n}\n","/**\n * Centralized concurrency limits for Sheets async workflows.\n * Keep these values conservative to avoid overloading API endpoints.\n */\nexport const SHEETS_CONCURRENCY = {\n\tdraftSubmit: 3,\n\tbulkDelete: 4,\n} as const;\n","// The DOM content resolver — the native analogue of the canvas `useGridContent`\n// (grid/hooks/use-grid-content.ts). It MIRRORS that hook's routing steps 1:1 but\n// produces a neutral {@link SheetsCell} (+ the resolved view component) instead of\n// a glide `GridCell`, so the DOM grid never touches the canvas render path.\n//\n// It deliberately does NOT own the `ensureRelationInfo` effect: the canvas\n// `useGridContent` already runs that effect for the same table, so this hook takes\n// `relationInfoByField` + `meta` as INPUTS to avoid a duplicate store write/effect.\n// Draft VISUAL styling (faded/error theme overrides) is intentionally deferred to\n// Phase 7 — here we only blank the leaked draft-id text and tag `styleHint.draft`\n// so Phase 7 can style from a neutral flag (no glide theme imports).\n\nimport { useCallback, useMemo } from 'react';\n\nimport type { CellTypeRegistry } from '../cell-types/cell-type-registry';\nimport type { FieldMetadata } from '../cell-types/cell-type-resolver';\nimport type { CellCreationMetadata } from '../grid/grid-cell-types';\nimport type { CellProps } from '../cell-model/cell-props';\nimport type { SheetsCell } from '../cell-model/sheets-cell';\nimport type { SheetsRow } from '../grid/row-model';\nimport type { RelationInfo } from '../store/relation-info-slice';\nimport type { MetaQuery } from '@constructive-io/data';\nimport { buildRelationFieldNameSet, resolveGridCellRoute } from '../grid/cell-routing';\nimport { getDraftMeta } from '../grid/row-model';\nimport { unwrapRelationValue } from '../grid/sheets.utils';\nimport { MEDIA_TYPES } from '../cell-types/cell-type-groups';\nimport type { SheetsRowIdentifier } from '../row-identity';\n\ninterface RelationOptions {\n\trelationChipLimit?: number;\n\trelationLabelMaxLength?: number;\n}\n\n/** Resolved DOM cell payload: the neutral cell plus its (optional) view component. */\nexport interface SheetsCellResolution {\n\tcell: SheetsCell;\n\tcomponent?: React.ComponentType<CellProps>;\n\tcolKey: string;\n\t/**\n\t * The resolved cell-type key (post detection-override) — the SINGLE source of\n\t * truth the host feeds to `resolveEditIntent` to route activation. Always set;\n\t * `'text'` for the loading/empty fallthrough cells that carry no type. (Mirror\n\t * of the `meta.cellType` the cell itself now self-describes.)\n\t */\n\ttypeKey: string;\n\t/** Field metadata for the column — fed to a native overlay editor's EditorProps.fieldMeta. */\n\tfieldMeta?: FieldMetadata;\n\t/** Relation info for the column (when relational) — fed to a native overlay editor's EditorProps.relationInfo. */\n\trelationInfo?: RelationInfo;\n}\n\nexport interface UseSheetsContentArgs {\n\tdata: SheetsRow[];\n\tcolumnKeys: string[];\n\tfieldMetaMap: ReadonlyMap<string, FieldMetadata>;\n\tregistry: CellTypeRegistry;\n\ttableName?: string;\n\toptions?: RelationOptions;\n\t/** Relation info per field — owned by the canvas `useGridContent` ensureRelationInfo effect. */\n\trelationInfoByField: ReadonlyMap<string, RelationInfo>;\n\t/** Schema meta (same value the canvas path reads via useSheetsMeta). */\n\tmeta: MetaQuery | undefined;\n\t/** Disable every persisted-row editor when the table cannot expose update mutations. */\n\tserverRowsReadOnly?: boolean;\n\t/** Primary-key fields are immutable after insertion because they define row identity. */\n\tserverReadOnlyFields?: ReadonlySet<string>;\n\t/** Resolve the GraphQL mutation identity; self-committing editors require a legacy scalar id. */\n\tgetRowIdentifier?: (row: Readonly<Record<string, unknown>>) => SheetsRowIdentifier | null;\n\t/** Relation/upload editors still use scalar record APIs and must fail closed otherwise. */\n\tsupportsScalarSelfCommit?: boolean;\n}\n\nfunction isDraftId(value: unknown): boolean {\n\treturn typeof value === 'string' && value.startsWith('draft:');\n}\n\n/**\n * DISPLAY-LEVEL suppression of an internal draft key leaking as visible cell text —\n * the {@link SheetsCell} mirror of the canvas `suppressDraftIdText`. When the row is\n * a draft AND the value being rendered is the draft key (the `id` column starting\n * with `draft:`, or any value equal to the draft id), blank the cell's display/data\n * text while preserving kind and structural flags. Narrow by design: nothing else.\n */\nexport function suppressDraftIdText(\n\tcell: SheetsCell,\n\targs: { isDraftRow: boolean; colKey: string; rawValue: unknown; draftId: string | undefined },\n): SheetsCell {\n\tconst { isDraftRow, colKey, rawValue, draftId } = args;\n\tif (!isDraftRow) return cell;\n\n\tconst isIdColumnDraftKey = colKey === 'id' && isDraftId(rawValue);\n\tconst valueIsDraftId = typeof draftId === 'string' && rawValue === draftId;\n\tif (!isIdColumnDraftKey && !valueIsDraftId) return cell;\n\n\treturn { ...cell, data: typeof cell.data === 'string' ? '' : cell.data, displayData: '' };\n}\n\n/**\n * Tag the cell as a draft row so the host can apply faded/error styling from a flag —\n * the DOM mirror of the canvas applyDraftDisabledStyle/applyDraftErrorStyle split.\n * `error` is set when draftMeta.errors carries a field-level error for THIS colKey\n * (canvas: applyDraftErrorStyle); `draft` always (canvas: faded/disabled visuals).\n */\nfunction tagDraftStyle(cell: SheetsCell, hasError: boolean): SheetsCell {\n\treturn { ...cell, styleHint: { ...cell.styleHint, draft: true, error: hasError } };\n}\n\n/**\n * Build the DOM content resolver. Returns `getSheetsCell(rowIndex, colKey)` which\n * mirrors the canvas `getCellContent` routing exactly (draftMeta → fieldMeta →\n * relationInfo → route → relation value unwrap → matchInput → resolveTypeKey →\n * metadata → registry.toSheetsCell), then suppresses any leaked draft-id text and\n * tags draft rows. The view component is resolved alongside via `getCellComponent`.\n */\nexport function useSheetsContent(args: UseSheetsContentArgs) {\n\tconst {\n\t\tdata,\n\t\tcolumnKeys,\n\t\tfieldMetaMap,\n\t\tregistry,\n\t\ttableName,\n\t\toptions,\n\t\trelationInfoByField,\n\t\tmeta,\n\t\tserverRowsReadOnly = false,\n\t\tserverReadOnlyFields,\n\t\tgetRowIdentifier,\n\t\tsupportsScalarSelfCommit = true,\n\t} = args;\n\n\tconst relationFieldNamesFromMeta = useMemo(() => buildRelationFieldNameSet(meta, tableName), [meta, tableName]);\n\n\t// PER-RESOLVER RESULT CACHE. The cell host calls `getSheetsCell` for every visible\n\t// cell on every re-render, almost always re-deriving an identical resolution. This\n\t// Map memoizes the last resolution per `rowIndex|colKey`, keyed on the cell's raw\n\t// VALUE: a repeat call whose value is reference-equal to the cached one returns the\n\t// cached resolution and skips the full pipeline (route → relation unwrap →\n\t// resolveTypeKey → toSheetsCell, which allocates ≥3 objects).\n\t//\n\t// SAFETY: the deps below are IDENTICAL to the `getSheetsCell` useCallback's deps, so\n\t// the cache is thrown away exactly when the resolver would change identity. Every\n\t// input that can change a cell's resolution flows through one of these deps — most\n\t// notably `data`: draft status/errors rebuild `combinedRows` (new array + new row\n\t// objects, see useDraftRows), and any server-data / optimistic change recreates the\n\t// rows array too. So `styleHint.draft/error` (derived from the row's DraftMeta) and\n\t// the relation-unwrap fields (read off the same row object) cannot change without a\n\t// new `data` reference resetting this cache — making the per-value compare sound:\n\t// within one resolver identity the row objects are immutable, so a value that is\n\t// reference-equal guarantees an identical resolution.\n\tconst cache = useMemo(\n\t\t() => new Map<string, { value: unknown; resolution: SheetsCellResolution }>(),\n\t\t[data, columnKeys, fieldMetaMap, registry, relationFieldNamesFromMeta, relationInfoByField, options, serverRowsReadOnly, serverReadOnlyFields, getRowIdentifier, supportsScalarSelfCommit],\n\t);\n\n\tconst getSheetsCell = useCallback(\n\t\t(rowIndex: number, colKey: string): SheetsCellResolution => {\n\t\t\t// UNLOADED INFINITE ROW → loading skeleton. In infinite-scroll mode `data` is the\n\t\t\t// null-backed proxy from useSheets: a server index whose page is still in flight reads\n\t\t\t// back as `null` (drafts are real objects, never null). Resolve those slots to a neutral\n\t\t\t// `kind: 'loading'` cell with NO component, so the host's kind→view map paints\n\t\t\t// LoadingCellView (the canvas analogue is glide's loadingCell). Without this the row\n\t\t\t// coerces to `{}` below and every cell renders as blank text instead of a skeleton.\n\t\t\tconst rawRow = (data as any[])[rowIndex];\n\t\t\tconst cacheKey = rowIndex + '|' + colKey;\n\t\t\tif (colKey && rawRow == null) {\n\t\t\t\t// Cache the loading slot keyed on its (null) value: when the page loads, the row\n\t\t\t\t// flips null → object, the value identity changes, and this naturally MISSES and\n\t\t\t\t// recomputes (a new `data` proxy also resets the whole cache, so this is belt-and-braces).\n\t\t\t\tconst hit = cache.get(cacheKey);\n\t\t\t\tif (hit && hit.value === rawRow) return hit.resolution;\n\t\t\t\tconst resolution: SheetsCellResolution = {\n\t\t\t\t\tcell: { kind: 'loading', data: null, displayData: '', readonly: true },\n\t\t\t\t\tcolKey,\n\t\t\t\t\ttypeKey: 'text',\n\t\t\t\t};\n\t\t\t\tcache.set(cacheKey, { value: rawRow, resolution });\n\t\t\t\treturn resolution;\n\t\t\t}\n\t\t\tconst rowData = rawRow ?? {};\n\t\t\tif (!colKey) {\n\t\t\t\treturn { cell: { kind: 'text', data: '', displayData: '', readonly: false }, colKey, typeKey: 'text' };\n\t\t\t}\n\n\t\t\tconst rawValue = rowData?.[colKey];\n\n\t\t\t// RESULT-CACHE FAST PATH: the resolution is fully determined by the row object's\n\t\t\t// fields (see the cache declaration), and the row object is immutable within this\n\t\t\t// resolver identity, so a reference-equal `rawValue` means an identical resolution.\n\t\t\tconst hit = cache.get(cacheKey);\n\t\t\tif (hit && hit.value === rawValue) return hit.resolution;\n\t\t\tconst draftMeta = getDraftMeta(rowData);\n\t\t\tconst isDraftRow = Boolean(draftMeta?.isDraft);\n\t\t\tconst isDraftIdCell = isDraftRow && colKey === 'id';\n\n\t\t\tconst baseFieldMeta = fieldMetaMap.get(colKey);\n\t\t\tconst relationInfo = relationInfoByField.get(colKey);\n\t\t\tconst isRelationFallback = relationFieldNamesFromMeta.has(colKey);\n\t\t\tconst isRelation = Boolean(relationInfo) || isRelationFallback;\n\t\t\tconst foreignKeyField = relationInfo?.foreignKeyField;\n\t\t\tconst canEditRelationInline =\n\t\t\t\trelationInfo?.kind === 'belongsTo' &&\n\t\t\t\ttypeof foreignKeyField === 'string' &&\n\t\t\t\tfieldMetaMap.has(foreignKeyField);\n\n\t\t\tconst fieldMeta: FieldMetadata | undefined = baseFieldMeta;\n\t\t\tconst route = resolveGridCellRoute({\n\t\t\t\tcolKey,\n\t\t\t\tfieldMeta,\n\t\t\t\trelationInfo,\n\t\t\t\tisRelationFallback,\n\t\t\t\tisDraftIdCell,\n\t\t\t\thasForeignKeyField: canEditRelationInline,\n\t\t\t});\n\t\t\tconst tableForcedReadOnly = !isDraftRow && (\n\t\t\t\tserverRowsReadOnly || Boolean(serverReadOnlyFields?.has(colKey))\n\t\t\t);\n\n\t\t\tlet valueForCell = rawValue;\n\n\t\t\tif (relationInfo && relationInfo.relationField && relationInfo.relationField !== colKey) {\n\t\t\t\tconst relatedValue = (rowData as any)?.[relationInfo.relationField];\n\t\t\t\tif (relatedValue !== undefined && relatedValue !== null) {\n\t\t\t\t\tvalueForCell = relatedValue;\n\t\t\t\t} else if (typeof rawValue === 'string' && rawValue && !isDraftId(rawValue)) {\n\t\t\t\t\tvalueForCell = { id: rawValue };\n\t\t\t\t}\n\t\t\t} else if (relationInfo && valueForCell == null) {\n\t\t\t\tconst fkField = relationInfo.foreignKeyField;\n\t\t\t\tconst fkValue = fkField ? (rowData as any)?.[fkField] : undefined;\n\t\t\t\tif (fkValue && !isDraftId(fkValue)) {\n\t\t\t\t\tvalueForCell = { id: fkValue };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isRelation) {\n\t\t\t\tvalueForCell = unwrapRelationValue(valueForCell);\n\t\t\t}\n\n\t\t\t// Consumer detection override: a registered def's match() may override the\n\t\t\t// resolved typeKey. With no consumer cell types this returns route.cellType.\n\t\t\tconst matchInput = {\n\t\t\t\tgqlType: fieldMeta?.type?.gqlType ?? '',\n\t\t\t\tisArray: Boolean(fieldMeta?.type?.isArray),\n\t\t\t\tpgAlias: fieldMeta?.type?.pgAlias ?? null,\n\t\t\t\tpgType: fieldMeta?.type?.pgType ?? null,\n\t\t\t\tsubtype: fieldMeta?.type?.subtype ?? null,\n\t\t\t\tfieldName: colKey,\n\t\t\t};\n\t\t\tconst cellType = registry.resolveTypeKey(matchInput, () => route.cellType);\n\t\t\tconst rowIdentifier = !isDraftRow ? getRowIdentifier?.(rowData) : null;\n\t\t\tconst selfCommittingEditor = isRelation || MEDIA_TYPES.has(cellType);\n\t\t\tconst lacksScalarEditorIdentity =\n\t\t\t\tselfCommittingEditor &&\n\t\t\t\t(!supportsScalarSelfCommit || (\n\t\t\t\t\trowIdentifier != null && typeof rowIdentifier === 'object'\n\t\t\t\t));\n\t\t\tconst forcedReadOnly = tableForcedReadOnly || lacksScalarEditorIdentity;\n\n\t\t\tconst metadata: CellCreationMetadata = {\n\t\t\t\tcellType,\n\t\t\t\tfieldName: colKey,\n\t\t\t\tfieldMeta,\n\t\t\t\trelationInfo,\n\t\t\t\trelationOptions: relationInfo ? options || {} : undefined,\n\t\t\t\tcanEdit: route.canEdit && !forcedReadOnly,\n\t\t\t\tisReadonly: route.isReadonly || forcedReadOnly,\n\t\t\t\tactivationBehavior: route.activationBehavior,\n\t\t\t};\n\n\t\t\tconst resolvedCell = registry.toSheetsCell(cellType, valueForCell, { metadata });\n\t\t\tconst cell = forcedReadOnly && !resolvedCell.readonly\n\t\t\t\t? { ...resolvedCell, readonly: true }\n\t\t\t\t: resolvedCell;\n\n\t\t\t// Blank any internal draft key that would otherwise render as visible text\n\t\t\t// (kind unchanged); narrow to the draft id, nothing else.\n\t\t\tconst displaySafe = suppressDraftIdText(cell, {\n\t\t\t\tisDraftRow,\n\t\t\t\tcolKey,\n\t\t\t\trawValue,\n\t\t\t\tdraftId: draftMeta?.draftRowId,\n\t\t\t});\n\n\t\t\t// Flag draft rows (faded) and per-cell errors (error) so the host can paint\n\t\t\t// the DOM equivalent of applyDraftDisabledStyle / applyDraftErrorStyle.\n\t\t\tconst draftErrors = draftMeta?.errors ?? null;\n\t\t\tconst hasCellError = Boolean(draftErrors && colKey in draftErrors);\n\t\t\tconst styled = isDraftRow ? tagDraftStyle(displaySafe, hasCellError) : displaySafe;\n\n\t\t\tconst component = registry.getCellComponent(cellType);\n\t\t\t// Surface the already-computed field/relation meta so a native overlay editor\n\t\t\t// (relation/image, Phase 5) can read EditorProps.fieldMeta / relationInfo without\n\t\t\t// re-resolving — no extra work, just exposing what this routing already derived.\n\t\t\t// `typeKey` is the resolved cellType — the single source of truth for edit-intent.\n\t\t\tconst resolution: SheetsCellResolution = { cell: styled, component, colKey, typeKey: cellType, fieldMeta, relationInfo };\n\t\t\tcache.set(cacheKey, { value: rawValue, resolution });\n\t\t\treturn resolution;\n\t\t},\n\t\t[data, columnKeys, fieldMetaMap, registry, relationFieldNamesFromMeta, relationInfoByField, options, serverRowsReadOnly, serverReadOnlyFields, getRowIdentifier, supportsScalarSelfCommit],\n\t);\n\n\treturn { getSheetsCell };\n}\n","import type { MetaQuery } from '@constructive-io/data';\n\nimport { resolveCellType, type FieldMetadata } from '../cell-types/cell-type-resolver';\nimport type { RelationInfo } from '../store/relation-info-slice';\n\ntype MetaTable = NonNullable<NonNullable<MetaQuery['_meta']>['tables']>[number];\n\nexport interface GridCellRouteInput {\n\tcolKey: string;\n\tfieldMeta?: FieldMetadata;\n\trelationInfo?: RelationInfo;\n\tisRelationFallback?: boolean;\n\tisCustomGeometryCell?: boolean;\n\tisDraftIdCell?: boolean;\n\thasForeignKeyField?: boolean;\n}\n\nexport interface GridCellRoute {\n\tcellType: string;\n\tbaseCellType: string;\n\tisRelation: boolean;\n\tcanEdit: boolean;\n\tcanActivate: boolean;\n\tisReadonly: boolean;\n\tactivationBehavior: 'single-click' | 'double-click';\n}\n\nexport interface ResolveEditorLocationInput {\n\tcellLocation?: readonly [number, number];\n\tactiveCell?: readonly [number, number] | null;\n\tcolumnKeys: string[];\n\tdataLength: number;\n}\n\nexport interface ResolvedEditorLocation {\n\tcolIndex: number;\n\trowIndex: number;\n\tcolKey: string;\n}\n\nexport function buildRelationFieldNameSet(meta: MetaQuery | undefined, tableName?: string): Set<string> {\n\tif (!tableName) return new Set<string>();\n\n\tconst table = meta?._meta?.tables?.find((entry): entry is MetaTable => Boolean(entry && entry.name === tableName));\n\tif (!table?.relations) return new Set<string>();\n\n\tconst out = new Set<string>();\n\tconst push = (fieldName?: string | null) => {\n\t\tif (fieldName) out.add(fieldName);\n\t};\n\n\ttable.relations.belongsTo?.forEach((relation) => {\n\t\tpush(relation?.fieldName);\n\t\trelation?.keys?.forEach((key) => push(key?.name));\n\t});\n\ttable.relations.hasOne?.forEach((relation) => push(relation?.fieldName));\n\ttable.relations.hasMany?.forEach((relation) => push(relation?.fieldName));\n\ttable.relations.manyToMany?.forEach((relation) => push(relation?.fieldName));\n\n\treturn out;\n}\n\nexport function resolveGridCellRoute({\n\tcolKey,\n\tfieldMeta,\n\trelationInfo,\n\tisRelationFallback = false,\n\tisCustomGeometryCell = false,\n\tisDraftIdCell = false,\n\thasForeignKeyField = false,\n}: GridCellRouteInput): GridCellRoute {\n\tconst base = resolveCellType(colKey, fieldMeta);\n\tconst isRelation = Boolean(relationInfo) || isRelationFallback;\n\tconst canEditRelationInline = Boolean(\n\t\trelationInfo && relationInfo.kind === 'belongsTo' && relationInfo.foreignKeyField && hasForeignKeyField,\n\t);\n\n\tconst canEdit = isDraftIdCell ? false : isRelation ? canEditRelationInline : base.canEdit;\n\tconst canActivate = isDraftIdCell ? false : isRelation ? true : base.canActivate;\n\tconst isReadonly = isDraftIdCell ? true : isRelation ? !canEditRelationInline : base.isReadonly;\n\n\tlet cellType = isRelation ? 'relation' : base.cellType;\n\tif (!isRelation && isCustomGeometryCell) {\n\t\tcellType = 'geometry';\n\t}\n\n\treturn {\n\t\tcellType,\n\t\tbaseCellType: base.cellType,\n\t\tisRelation,\n\t\tcanEdit,\n\t\tcanActivate,\n\t\tisReadonly,\n\t\tactivationBehavior: base.activationBehavior,\n\t};\n}\n\nexport function resolveEditorLocation({\n\tcellLocation,\n\tactiveCell,\n\tcolumnKeys,\n\tdataLength,\n}: ResolveEditorLocationInput): ResolvedEditorLocation | null {\n\tconst source = cellLocation ?? activeCell ?? null;\n\tif (!source) return null;\n\n\tconst [colIndex, rowIndex] = source;\n\tif (!Number.isInteger(colIndex) || !Number.isInteger(rowIndex)) return null;\n\tif (colIndex < 0 || colIndex >= columnKeys.length) return null;\n\tif (rowIndex < 0 || rowIndex >= dataLength) return null;\n\n\tconst colKey = columnKeys[colIndex];\n\tif (!colKey) return null;\n\n\treturn {\n\t\tcolIndex,\n\t\trowIndex,\n\t\tcolKey,\n\t};\n}\n","import { useCallback } from 'react';\n\nimport type { SheetsSelection } from '../../selection/selection-model';\nimport { SHEETS_CONCURRENCY } from '../../config/sheets-concurrency';\nimport { sheetsLogger } from '../../utils/sheets-logger';\nimport { getDraftMeta } from '../row-model';\nimport type { SheetsRowIdentifier } from '../../row-identity';\n\ninterface OperationFeedbackCallbacks {\n\tonStart?: (type: 'delete', total: number) => string;\n\tonProgress?: (id: string, completed: number, failed: number) => void;\n\tonComplete?: (id: string, status: 'success' | 'partial' | 'error', message: string) => void;\n}\n\ntype DeleteOutcome = { status: 'success' | 'partial' | 'error'; message: string } | null;\n\n/**\n * Build the completion toast for a bulk delete, distinguishing UNSAVED draft rows\n * (discarded client-side, nothing hit the server) from real server-row deletes.\n *\n * `drafts` = draft rows discarded, `deleted` = server rows deleted, `failed` =\n * server deletes that errored. All-success wording reflects reality:\n * - only drafts -> \"Discarded N draft(s)\"\n * - only server -> \"Deleted N row(s)\" (unchanged)\n * - mixed -> \"Deleted N rows, discarded M drafts\"\n * The partial/error (failure) wording is unchanged from prior behavior.\n */\nexport function summarizeDeleteResult(drafts: number, deleted: number, failed: number): DeleteOutcome {\n\tconst successes = drafts + deleted;\n\n\tif (failed === 0 && successes > 0) {\n\t\tlet message: string;\n\t\tif (deleted === 0) {\n\t\t\tmessage = `Discarded ${drafts} draft${drafts === 1 ? '' : 's'}`;\n\t\t} else if (drafts === 0) {\n\t\t\tmessage = `Deleted ${deleted} ${deleted === 1 ? 'row' : 'rows'}`;\n\t\t} else {\n\t\t\tmessage = `Deleted ${deleted} ${deleted === 1 ? 'row' : 'rows'}, discarded ${drafts} draft${drafts === 1 ? '' : 's'}`;\n\t\t}\n\t\treturn { status: 'success', message };\n\t}\n\n\tif (successes > 0 && failed > 0) {\n\t\treturn { status: 'partial', message: `Deleted ${successes}, ${failed} failed` };\n\t}\n\n\tif (failed > 0) {\n\t\treturn { status: 'error', message: `Failed to delete ${failed} ${failed === 1 ? 'row' : 'rows'}` };\n\t}\n\n\treturn null;\n}\n\nexport function useGridOperations(\n\tdata: any[],\n\tdeleteRow: (id: SheetsRowIdentifier) => Promise<any>,\n\tgridSelection: SheetsSelection | undefined,\n\tclearSelection: () => void,\n\toptions?: {\n\t\tonRemoveDraftRow?: (draftRowId: string) => void;\n\t\tonAfterServerDeletes?: () => void;\n\t\tgetRowIdentifier?: (row: Readonly<Record<string, unknown>>) => SheetsRowIdentifier | null;\n\t\tcanDeleteServerRows?: boolean;\n\t\tfeedback?: OperationFeedbackCallbacks;\n\t},\n) {\n\tconst deleteSelected = useCallback(async () => {\n\t\tif (!gridSelection) return;\n\n\t\tconst rows = gridSelection.rows.toArray();\n\t\tif (rows.length === 0) return;\n\n\t\t\t// Start operation feedback\n\t\t\tconst operationId = options?.feedback?.onStart?.('delete', rows.length);\n\n\t\t\tlet successes = 0;\n\t\t\tlet failures = 0;\n\t\t\tlet serverSuccesses = 0;\n\t\t\tlet draftDiscards = 0;\n\t\t\tconst records = rows.map((idx) => data[idx]);\n\t\t\tlet nextRecordIndex = 0;\n\t\t\tconst workerCount = Math.min(SHEETS_CONCURRENCY.bulkDelete, records.length);\n\n\t\t\tconst runDeleteWorker = async () => {\n\t\t\t\twhile (nextRecordIndex < records.length) {\n\t\t\t\t\tconst currentIndex = nextRecordIndex;\n\t\t\t\t\tnextRecordIndex += 1;\n\t\t\t\t\tconst record = records[currentIndex];\n\n\t\t\t\t\tconst draftMeta = getDraftMeta(record);\n\t\t\t\t\tif (draftMeta?.isDraft && options?.onRemoveDraftRow) {\n\t\t\t\t\t\tconst draftRowId = draftMeta.draftRowId;\n\t\t\t\t\t\tif (draftRowId) {\n\t\t\t\t\t\t\toptions.onRemoveDraftRow(draftRowId);\n\t\t\t\t\t\t\tsuccesses += 1;\n\t\t\t\t\t\t\tdraftDiscards += 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfailures += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (options?.canDeleteServerRows !== false) {\n\t\t\t\t\t\tconst identifier = options?.getRowIdentifier\n\t\t\t\t\t\t\t? options.getRowIdentifier(record)\n\t\t\t\t\t\t\t: typeof record?.id === 'string' || typeof record?.id === 'number'\n\t\t\t\t\t\t\t\t? record.id\n\t\t\t\t\t\t\t\t: null;\n\t\t\t\t\t\tif (identifier === null) {\n\t\t\t\t\t\t\tfailures += 1;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait deleteRow(identifier);\n\t\t\t\t\t\t\tsuccesses += 1;\n\t\t\t\t\t\t\tserverSuccesses += 1;\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tsheetsLogger().error('Failed to delete record', { identifier, error });\n\t\t\t\t\t\t\tfailures += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfailures += 1;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (operationId) {\n\t\t\t\t\t\toptions?.feedback?.onProgress?.(operationId, successes, failures);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tawait Promise.all(Array.from({ length: workerCount }, () => runDeleteWorker()));\n\n\t\t\t// Complete operation feedback — distinguish discarded drafts from server deletes.\n\t\t\tif (operationId) {\n\t\t\t\tconst outcome = summarizeDeleteResult(draftDiscards, serverSuccesses, failures);\n\t\t\t\tif (outcome) {\n\t\t\t\t\toptions?.feedback?.onComplete?.(operationId, outcome.status, outcome.message);\n\t\t\t\t}\n\t\t\t}\n\n\t\tif (serverSuccesses > 0) {\n\t\t\toptions?.onAfterServerDeletes?.();\n\t\t}\n\n\t\t// Always clear selection so indices don't point to new rows after deletion\n\t\tclearSelection();\n\t}, [gridSelection, data, deleteRow, clearSelection, options]);\n\n\treturn {\n\t\tdeleteSelected,\n\t};\n}\n","import { useMemo } from 'react';\n\nimport type { SheetsSelection } from '../../selection/selection-model';\nimport type { DraftRow } from '../../store/draft-rows-slice';\nimport { getDraftMeta, type DraftMeta } from '../row-model';\n\ninterface DraftRowsTableState {\n\torder: string[];\n\tmap: Record<string, DraftRow>;\n\ttemplate: Record<string, unknown>;\n\tmetaVersion: string;\n\tcolumnOrder: string[];\n}\n\nexport interface DraftRowEntry {\n\tdraftRowId: string;\n\tdraftRow: DraftRow;\n}\n\ninterface UseGridSelectionStateParams {\n\tgridSelection: SheetsSelection | undefined;\n\tcombinedRows: any[];\n\tdraftRowsTable?: DraftRowsTableState;\n}\n\nexport function useGridSelectionState({ gridSelection, combinedRows, draftRowsTable }: UseGridSelectionStateParams) {\n\tconst selectedRowIndices = useMemo(() => {\n\t\tif (!gridSelection) return [] as number[];\n\t\treturn gridSelection.rows.toArray();\n\t}, [gridSelection]);\n\n\tconst selectedRowCount = selectedRowIndices.length;\n\n\tconst selectedDraftRowEntries = useMemo(() => {\n\t\tif (!draftRowsTable || selectedRowIndices.length === 0) return [] as DraftRowEntry[];\n\n\t\treturn selectedRowIndices\n\t\t\t.map((rowIndex) => getDraftMeta(combinedRows[rowIndex]))\n\t\t\t.filter((meta): meta is DraftMeta => Boolean(meta?.draftRowId))\n\t\t\t.map((meta) => {\n\t\t\t\tconst draftRow = draftRowsTable.map[meta.draftRowId];\n\t\t\t\treturn draftRow ? { draftRowId: meta.draftRowId, draftRow } : null;\n\t\t\t})\n\t\t\t.filter((entry): entry is DraftRowEntry => entry !== null);\n\t}, [draftRowsTable, selectedRowIndices, combinedRows]);\n\n\tconst hasDraftSelection = selectedDraftRowEntries.length > 0;\n\n\treturn {\n\t\tselectedRowIndices,\n\t\tselectedRowCount,\n\t\tselectedDraftRowEntries,\n\t\thasDraftSelection,\n\t};\n}\n","import { useCallback, useMemo, useReducer } from 'react';\n\nimport { emptySheetsSelection, moveActive, selectCell } from '../../selection/selection-model';\nimport type { SheetsSelection } from '../../selection/selection-model';\nimport type { FilterGroup } from '../sheets.controls';\n\n// Centralized grid state interface\nexport interface GridState {\n\t// Sorting state\n\tsorting: {\n\t\tid: string | null;\n\t\tdesc: boolean;\n\t};\n\n\t// Pagination state\n\tpageIndex: number;\n\n\t// Filter states\n\tfilterTree: FilterGroup;\n\tfiltersOpen: boolean;\n\n\t// Column state\n\tcolumnWidths: Map<string, number>;\n\n\t// Selection state (native SheetsSelection — glide is only a derived projection now).\n\t// Field name kept as `gridSelection` to minimize consumer churn during the port.\n\tgridSelection: SheetsSelection | undefined;\n}\n\nconst EMPTY_FILTER_TREE: FilterGroup = { type: 'group', id: 'root', conjunction: 'and', children: [] };\n\n// Action types for state updates\nexport type GridAction =\n\t| { type: 'SET_SORTING'; payload: GridState['sorting'] }\n\t| { type: 'TOGGLE_SORTING'; payload: string }\n\t| { type: 'SET_PAGE_INDEX'; payload: number }\n\t| { type: 'SET_FILTER_TREE'; payload: FilterGroup }\n\t| { type: 'CLEAR_ALL_FILTERS' }\n\t| { type: 'TOGGLE_FILTERS_PANEL' }\n\t| { type: 'SET_FILTERS_OPEN'; payload: boolean }\n\t| { type: 'RESIZE_COLUMN'; payload: { id: string; width: number } }\n\t| { type: 'SET_GRID_SELECTION'; payload: SheetsSelection | undefined }\n\t| { type: 'SET_ACTIVE_CELL'; payload: { col: number; row: number } }\n\t| { type: 'MOVE_ACTIVE'; payload: { dCol: number; dRow: number; colCount: number; rowCount: number } }\n\t| { type: 'RESET_PAGE_IF_NEEDED'; payload: { totalPages: number } };\n\n// Initial state factory\nfunction createInitialGridState(): GridState {\n\treturn {\n\t\tsorting: { id: null, desc: false },\n\t\tpageIndex: 0,\n\t\tfilterTree: { ...EMPTY_FILTER_TREE },\n\t\tfiltersOpen: false,\n\t\tcolumnWidths: new Map(),\n\t\tgridSelection: undefined,\n\t};\n}\n\n// State reducer with type-safe action handling\nfunction gridStateReducer(state: GridState, action: GridAction): GridState {\n\tswitch (action.type) {\n\t\tcase 'SET_SORTING':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tsorting: action.payload,\n\t\t\t};\n\n\t\tcase 'TOGGLE_SORTING': {\n\t\t\tconst colId = action.payload;\n\t\t\tlet newSorting: GridState['sorting'];\n\n\t\t\tif (state.sorting.id !== colId) {\n\t\t\t\t// Different column clicked: start with ASC\n\t\t\t\tnewSorting = { id: colId, desc: false };\n\t\t\t} else if (!state.sorting.desc) {\n\t\t\t\t// Same column, currently ASC: switch to DESC\n\t\t\t\tnewSorting = { id: colId, desc: true };\n\t\t\t} else {\n\t\t\t\t// Same column, currently DESC: reset to neutral (no sorting)\n\t\t\t\tnewSorting = { id: null, desc: false };\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tsorting: newSorting,\n\t\t\t};\n\t\t}\n\n\t\tcase 'SET_PAGE_INDEX':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tpageIndex: action.payload,\n\t\t\t};\n\n\t\tcase 'SET_FILTER_TREE':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tfilterTree: action.payload,\n\t\t\t};\n\n\t\tcase 'CLEAR_ALL_FILTERS':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tfilterTree: { ...EMPTY_FILTER_TREE },\n\t\t\t};\n\n\t\tcase 'TOGGLE_FILTERS_PANEL':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tfiltersOpen: !state.filtersOpen,\n\t\t\t};\n\n\t\tcase 'SET_FILTERS_OPEN':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tfiltersOpen: action.payload,\n\t\t\t};\n\n\t\tcase 'RESIZE_COLUMN': {\n\t\t\tconst newColumnWidths = new Map(state.columnWidths);\n\t\t\tnewColumnWidths.set(action.payload.id, action.payload.width);\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tcolumnWidths: newColumnWidths,\n\t\t\t};\n\t\t}\n\n\t\tcase 'SET_GRID_SELECTION':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tgridSelection: action.payload,\n\t\t\t};\n\n\t\tcase 'SET_ACTIVE_CELL': {\n\t\t\tconst { col, row } = action.payload;\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tgridSelection: selectCell(state.gridSelection ?? emptySheetsSelection, col, row),\n\t\t\t};\n\t\t}\n\n\t\tcase 'MOVE_ACTIVE': {\n\t\t\tconst { dCol, dRow, colCount, rowCount } = action.payload;\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tgridSelection: moveActive(state.gridSelection ?? emptySheetsSelection, dCol, dRow, colCount, rowCount),\n\t\t\t};\n\t\t}\n\n\t\tcase 'RESET_PAGE_IF_NEEDED': {\n\t\t\tconst { totalPages } = action.payload;\n\t\t\tif (state.pageIndex >= totalPages) {\n\t\t\t\treturn {\n\t\t\t\t\t...state,\n\t\t\t\t\tpageIndex: Math.max(0, totalPages - 1),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn state;\n\t\t}\n\n\t\tdefault:\n\t\t\treturn state;\n\t}\n}\n\n// Custom hook for grid state management\nexport function useGridState() {\n\tconst [state, dispatch] = useReducer(gridStateReducer, undefined, createInitialGridState);\n\n\tconst setSorting = useCallback((sorting: GridState['sorting']) => {\n\t\tdispatch({ type: 'SET_SORTING', payload: sorting });\n\t}, []);\n\n\tconst toggleSorting = useCallback((colId: string) => {\n\t\tdispatch({ type: 'TOGGLE_SORTING', payload: colId });\n\t}, []);\n\n\tconst setPageIndex = useCallback((pageIndex: number) => {\n\t\tdispatch({ type: 'SET_PAGE_INDEX', payload: pageIndex });\n\t}, []);\n\n\tconst setFilterTree = useCallback((tree: FilterGroup) => {\n\t\tdispatch({ type: 'SET_FILTER_TREE', payload: tree });\n\t}, []);\n\n\tconst clearAllFilters = useCallback(() => {\n\t\tdispatch({ type: 'CLEAR_ALL_FILTERS' });\n\t}, []);\n\n\tconst toggleFiltersPanel = useCallback(() => {\n\t\tdispatch({ type: 'TOGGLE_FILTERS_PANEL' });\n\t}, []);\n\n\tconst setFiltersOpen = useCallback((open: boolean) => {\n\t\tdispatch({ type: 'SET_FILTERS_OPEN', payload: open });\n\t}, []);\n\n\tconst resizeColumn = useCallback((id: string, width: number) => {\n\t\tdispatch({ type: 'RESIZE_COLUMN', payload: { id, width } });\n\t}, []);\n\n\tconst setGridSelection = useCallback((selection: SheetsSelection | undefined) => {\n\t\tdispatch({ type: 'SET_GRID_SELECTION', payload: selection });\n\t}, []);\n\n\tconst setActiveCell = useCallback((col: number, row: number) => {\n\t\tdispatch({ type: 'SET_ACTIVE_CELL', payload: { col, row } });\n\t}, []);\n\n\tconst moveActiveCell = useCallback((dCol: number, dRow: number, colCount: number, rowCount: number) => {\n\t\tdispatch({ type: 'MOVE_ACTIVE', payload: { dCol, dRow, colCount, rowCount } });\n\t}, []);\n\n\tconst resetPageIfNeeded = useCallback((totalPages: number) => {\n\t\tdispatch({ type: 'RESET_PAGE_IF_NEEDED', payload: { totalPages } });\n\t}, []);\n\n\t// Stable object identity (avoid prop/effect churn in consumers)\n\tconst actions = useMemo(\n\t\t() => ({\n\t\t\tsetSorting,\n\t\t\ttoggleSorting,\n\t\t\tsetPageIndex,\n\t\t\tsetFilterTree,\n\t\t\tclearAllFilters,\n\t\t\ttoggleFiltersPanel,\n\t\t\tsetFiltersOpen,\n\t\t\tresizeColumn,\n\t\t\tsetGridSelection,\n\t\t\tsetActiveCell,\n\t\t\tmoveActiveCell,\n\t\t\tresetPageIfNeeded,\n\t\t}),\n\t\t[\n\t\t\tsetSorting,\n\t\t\ttoggleSorting,\n\t\t\tsetPageIndex,\n\t\t\tsetFilterTree,\n\t\t\tclearAllFilters,\n\t\t\ttoggleFiltersPanel,\n\t\t\tsetFiltersOpen,\n\t\t\tresizeColumn,\n\t\t\tsetGridSelection,\n\t\t\tsetActiveCell,\n\t\t\tmoveActiveCell,\n\t\t\tresetPageIfNeeded,\n\t\t],\n\t);\n\n\treturn {\n\t\tstate,\n\t\tactions,\n\t};\n}\n","/**\n * RangeSet — the immutable selection primitive for the native (TanStack DOM)\n * grid. It replaces glide's `CompactSelection` for row selection state.\n *\n * Internal representation: a sorted, non-overlapping, NON-ADJACENT array of\n * `[start, end)` half-open ranges. Adjacency MERGES on touch (so `add([0,3))`\n * then `add([3,5))` collapses to a single `[0,5)`), keeping a 10k-row selection\n * O(#ranges) instead of O(#rows). Every mutator returns a NEW RangeSet; the\n * receiver is never mutated.\n *\n * Focused tests protect merging, splitting, offsets, and immutability without\n * freezing the obsolete grid implementation this class replaced.\n */\n\ntype Range = readonly [start: number, end: number];\n\n/** Normalize the `number | [number, number]` arg to a half-open `[start, end)`. */\nfunction toRange(i: number | [number, number]): Range {\n\treturn typeof i === 'number' ? [i, i + 1] : [i[0], i[1]];\n}\n\n/** True when the range is empty/inverted (start >= end) and contributes nothing. */\nfunction isEmptyRange([start, end]: Range): boolean {\n\treturn start >= end;\n}\n\n/**\n * Insert `[s, e)` into a sorted, disjoint, non-adjacent range list, merging any\n * ranges it overlaps OR merely TOUCHES (touch = adjacency merge). Returns a new\n * sorted, disjoint, non-adjacent list.\n */\nfunction insertRange(ranges: readonly Range[], [s, e]: Range): Range[] {\n\tconst out: Range[] = [];\n\tlet start = s;\n\tlet end = e;\n\tlet inserted = false;\n\tfor (const [rs, re] of ranges) {\n\t\tif (re < start) {\n\t\t\t// Entirely before the new range (and not touching) — keep as-is.\n\t\t\tout.push([rs, re]);\n\t\t} else if (rs > end) {\n\t\t\t// Entirely after the new range (and not touching) — emit the merged\n\t\t\t// range once, then keep the rest.\n\t\t\tif (!inserted) {\n\t\t\t\tout.push([start, end]);\n\t\t\t\tinserted = true;\n\t\t\t}\n\t\t\tout.push([rs, re]);\n\t\t} else {\n\t\t\t// Overlaps or touches — widen the in-flight merged range.\n\t\t\tstart = Math.min(start, rs);\n\t\t\tend = Math.max(end, re);\n\t\t}\n\t}\n\tif (!inserted) out.push([start, end]);\n\treturn out;\n}\n\n/**\n * Subtract `[selMin, selMax)` from a sorted, disjoint range list, SPLITTING any\n * covering range (removing the middle of one yields two).\n *\n * This is a faithful port of glide `CompactSelection.remove`, including its two\n * documented quirks rather than a clean set difference:\n *\n * 1. Overlap test is `start <= selMax && selMin <= end` — both bounds `<=`, so\n * a range touching the cut is \"intersected\" (usually a harmless in-place\n * replace with an identical range).\n * 2. It SPLICES `items` in place while iterating with `items.entries()`, whose\n * cursor just counts iterations (0,1,2,…) regardless of mutation. So when a\n * range is fully consumed (`toAdd` empty), `splice(i, 1)` shrinks the array\n * and the element that slides into slot `i` is SKIPPED — the next read is\n * slot `i + 1`. A plain index loop over the MUTATED array reproduces this\n * exactly: never re-align `i`. (\"remove-spanning-three-ranges\" depends on\n * it — the range after a fully dropped middle range survives untouched.)\n */\nfunction subtractRange(ranges: readonly Range[], [selMin, selMax]: Range): Range[] {\n\tconst items: Range[] = ranges.map(([start, end]) => [start, end]);\n\tfor (let i = 0; i < items.length; i++) {\n\t\tconst [start, end] = items[i];\n\t\tif (start <= selMax && selMin <= end) {\n\t\t\tconst toAdd: Range[] = [];\n\t\t\tif (start < selMin) toAdd.push([start, selMin]);\n\t\t\tif (selMax < end) toAdd.push([selMax, end]);\n\t\t\titems.splice(i, 1, ...toAdd);\n\t\t}\n\t}\n\treturn items;\n}\n\nexport class RangeSet {\n\tprivate readonly ranges: readonly Range[];\n\n\tprivate constructor(ranges: readonly Range[]) {\n\t\tthis.ranges = ranges;\n\t}\n\n\tstatic empty(): RangeSet {\n\t\treturn new RangeSet([]);\n\t}\n\n\t/** RESET to a single index `[i, i+1)` or a single `[start, end)` range. */\n\tstatic fromSingleSelection(i: number | [number, number]): RangeSet {\n\t\tconst range = toRange(i);\n\t\treturn isEmptyRange(range) ? new RangeSet([]) : new RangeSet([range]);\n\t}\n\n\t/** Add an index/range; merges adjacent + overlapping ranges; contained = no-op. */\n\tadd(i: number | [number, number]): RangeSet {\n\t\tconst range = toRange(i);\n\t\tif (isEmptyRange(range)) return this;\n\t\treturn new RangeSet(insertRange(this.ranges, range));\n\t}\n\n\t/** Remove an index/range; SPLITS a covering range. */\n\tremove(i: number | [number, number]): RangeSet {\n\t\tconst range = toRange(i);\n\t\tif (isEmptyRange(range)) return this;\n\t\treturn new RangeSet(subtractRange(this.ranges, range));\n\t}\n\n\t/** Shift every range by `amount`. */\n\toffset(amount: number): RangeSet {\n\t\tif (amount === 0) return this;\n\t\treturn new RangeSet(this.ranges.map(([start, end]) => [start + amount, end + amount]));\n\t}\n\n\thasIndex(i: number): boolean {\n\t\tfor (const [start, end] of this.ranges) {\n\t\t\tif (i >= start && i < end) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Ascending expansion of every selected index. */\n\ttoArray(): number[] {\n\t\tconst out: number[] = [];\n\t\tfor (const [start, end] of this.ranges) {\n\t\t\tfor (let i = start; i < end; i++) out.push(i);\n\t\t}\n\t\treturn out;\n\t}\n\n\t/** Total selected count — sum of `(end - start)` across ranges. */\n\tget length(): number {\n\t\tlet total = 0;\n\t\tfor (const [start, end] of this.ranges) total += end - start;\n\t\treturn total;\n\t}\n\n\t/** Lowest selected index, or `undefined` when empty. */\n\tfirst(): number | undefined {\n\t\treturn this.ranges.length === 0 ? undefined : this.ranges[0][0];\n\t}\n\n\t/** Highest selected index, or `undefined` when empty. */\n\tlast(): number | undefined {\n\t\tif (this.ranges.length === 0) return undefined;\n\t\treturn this.ranges[this.ranges.length - 1][1] - 1;\n\t}\n}\n","/**\n * SheetsSelection — the native (TanStack DOM) selection value that replaces\n * glide's `GridSelection`. It is the canonical selection state for the new grid;\n * glide's `GridSelection` is only a derived projection (see `glide-projection.ts`)\n * kept alive for the still-drawing canvas during the phased port.\n *\n * Shape mirrors the slice of glide the grid actually reads/round-trips:\n * - `rows` — selected ROW indices (a {@link RangeSet}; the only thing\n * production consumes via `.toArray()` / `.length`).\n * - `columns` — selected COLUMN indices. Nothing consumes it today; it exists\n * solely so the glide projection has a faithful slot. Stays empty.\n * - `current` — the active cell + optional active range (glide's `current.cell`\n * + `current.range`). The canvas keyboard-nav cursor depends on it,\n * so the projection must preserve it round-trip.\n *\n * The interaction helpers below are PURE and own the click logic glide used to\n * own internally (plain/ctrl/shift row clicks). They operate on ROW indices.\n *\n * NOTE — anchor tracking for shift-click is NOT stored here: `selectRange` takes\n * the anchor as an argument, so the caller (the reducer / interaction layer) owns\n * \"where the last plain click landed\". This keeps the model a pure value with no\n * hidden interaction state.\n */\n\nimport { RangeSet } from './range-set';\n\n/** A half-open active range in cell coordinates (mirrors glide's `Rectangle`). */\nexport interface SelectionRect {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n}\n\n/** The active cell (and optional active range) — glide's `current`, trimmed. */\nexport interface SelectionCurrent {\n\t/** `[col, row]` — mirrors glide's `Item` ordering. */\n\tcell: [number, number];\n\t/** Active range; absent for a bare single-cell cursor. */\n\trange?: SelectionRect;\n}\n\nexport interface SheetsSelection {\n\tcurrent?: SelectionCurrent;\n\trows: RangeSet;\n\tcolumns: RangeSet;\n}\n\n/** The zero value — no rows, no columns, no active cell. */\nexport const emptySheetsSelection: SheetsSelection = {\n\trows: RangeSet.empty(),\n\tcolumns: RangeSet.empty()\n};\n\n/**\n * Plain row click: REPLACE the row selection with just `index` and park the\n * active cell on that row (column 0). Columns are left empty.\n */\nexport function selectRow(sel: SheetsSelection, index: number): SheetsSelection {\n\treturn {\n\t\tcurrent: { cell: [0, index] },\n\t\trows: RangeSet.fromSingleSelection(index),\n\t\tcolumns: sel.columns\n\t};\n}\n\n/**\n * Ctrl/cmd row click: TOGGLE `index` in the existing row selection (add when\n * absent, remove when present). The active cell follows the touched row.\n */\nexport function toggleRow(sel: SheetsSelection, index: number): SheetsSelection {\n\tconst rows = sel.rows.hasIndex(index) ? sel.rows.remove(index) : sel.rows.add(index);\n\treturn {\n\t\tcurrent: { cell: [0, index] },\n\t\trows,\n\t\tcolumns: sel.columns\n\t};\n}\n\n/**\n * Shift row click: REPLACE the row selection with the contiguous block spanning\n * `anchor`..`index` (inclusive, either order). The active cell follows `index`.\n */\nexport function selectRange(sel: SheetsSelection, anchor: number, index: number): SheetsSelection {\n\tconst min = Math.min(anchor, index);\n\tconst max = Math.max(anchor, index);\n\treturn {\n\t\tcurrent: { cell: [0, index] },\n\t\trows: RangeSet.fromSingleSelection([min, max + 1]),\n\t\tcolumns: sel.columns\n\t};\n}\n\n/** Clear everything back to the empty selection. */\nexport function clear(_sel: SheetsSelection): SheetsSelection {\n\treturn emptySheetsSelection;\n}\n\n/** Clamp `n` into the inclusive `[min, max]` range. */\nfunction clamp(n: number, min: number, max: number): number {\n\treturn Math.max(min, Math.min(max, n));\n}\n\n/**\n * Park the active cell on `[col, row]`, dropping any prior active range. PRESERVES\n * `rows` and `columns` — cell navigation must NOT touch the row-checkbox selection\n * that drives delete/export.\n */\nexport function selectCell(sel: SheetsSelection, col: number, row: number): SheetsSelection {\n\treturn { ...sel, current: { cell: [col, row] } };\n}\n\n/**\n * Extend the active range from an anchor cell to `[col, row]`. The active cell\n * becomes `[col, row]`; `current.range` is a normalized HALF-OPEN {@link SelectionRect}\n * spanning anchor..target in either order. PRESERVES `rows` and `columns`.\n */\nexport function extendRangeToCell(\n\tsel: SheetsSelection,\n\tcol: number,\n\trow: number,\n\tanchorCol: number,\n\tanchorRow: number,\n): SheetsSelection {\n\treturn {\n\t\t...sel,\n\t\tcurrent: {\n\t\t\tcell: [col, row],\n\t\t\trange: {\n\t\t\t\tx: Math.min(col, anchorCol),\n\t\t\t\ty: Math.min(row, anchorRow),\n\t\t\t\twidth: Math.abs(col - anchorCol) + 1,\n\t\t\t\theight: Math.abs(row - anchorRow) + 1,\n\t\t\t},\n\t\t},\n\t};\n}\n\n/**\n * Select the WHOLE grid as a single cell range (Ctrl/Cmd+A). `current.range` is ONE\n * rect spanning every column/row and `current.cell` parks at `[0, 0]`; `rows`/`columns`\n * are untouched. Coordinate-only — NEVER enumerates rows (the infinite row-model is\n * O(totalCount)), so a million-row grid stays a single interval.\n */\nexport function selectAllCells(sel: SheetsSelection, colCount: number, rowCount: number): SheetsSelection {\n\treturn {\n\t\t...sel,\n\t\tcurrent: { cell: [0, 0], range: { x: 0, y: 0, width: colCount, height: rowCount } },\n\t};\n}\n\n/**\n * Move the active cell by `[dCol, dRow]`, clamped to the grid bounds. Starts from\n * `[0, 0]` when no active cell exists. Drops any prior range; PRESERVES rows/columns.\n */\nexport function moveActive(\n\tsel: SheetsSelection,\n\tdCol: number,\n\tdRow: number,\n\tcolCount: number,\n\trowCount: number,\n): SheetsSelection {\n\tconst base = sel.current?.cell ?? [0, 0];\n\tconst col = clamp(base[0] + dCol, 0, colCount - 1);\n\tconst row = clamp(base[1] + dRow, 0, rowCount - 1);\n\treturn selectCell(sel, col, row);\n}\n\n/**\n * Pure nav-key resolver for the extended spreadsheet keys (Tab/Home/End + their\n * Ctrl/Cmd variants + PageUp/PageDown). Returns the NEW `[col, row]` target clamped\n * to grid bounds, or `null` when the key is not one of these moves (Arrow keys and\n * Enter/F2 are handled separately). `base` is the current active cell, `pageRows` is\n * the row span of one visible page (PageUp/Dn). Coordinate-only — never enumerates rows.\n */\nexport function computeKeyNavTarget(\n\tkey: string,\n\tmods: { ctrlOrMeta: boolean; shift: boolean },\n\tbase: [number, number],\n\tcolCount: number,\n\trowCount: number,\n\tpageRows: number,\n): [number, number] | null {\n\tconst [col, row] = base;\n\tconst lastCol = colCount - 1;\n\tconst lastRow = rowCount - 1;\n\n\tswitch (key) {\n\t\tcase 'Tab': {\n\t\t\tif (mods.shift) {\n\t\t\t\t// col-1; before col 0 wrap to the last col of the previous row. Clamp at grid start.\n\t\t\t\tif (col > 0) return [col - 1, row];\n\t\t\t\tif (row > 0) return [lastCol, row - 1];\n\t\t\t\treturn [0, 0];\n\t\t\t}\n\t\t\t// col+1; past the last col wrap to col 0 of the next row. Clamp at grid end.\n\t\t\tif (col < lastCol) return [col + 1, row];\n\t\t\tif (row < lastRow) return [0, row + 1];\n\t\t\treturn [lastCol, lastRow];\n\t\t}\n\t\tcase 'Home':\n\t\t\treturn mods.ctrlOrMeta ? [0, 0] : [0, row];\n\t\tcase 'End':\n\t\t\treturn mods.ctrlOrMeta ? [lastCol, lastRow] : [lastCol, row];\n\t\tcase 'PageUp':\n\t\t\treturn [col, clamp(row - pageRows, 0, lastRow)];\n\t\tcase 'PageDown':\n\t\t\treturn [col, clamp(row + pageRows, 0, lastRow)];\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n","/**\n * Hook for integrating infinite scroll with the data grid\n * Wraps useSheetsInfiniteTable and provides grid-specific utilities\n */\nimport { useCallback, useMemo } from 'react';\n\nimport type { MetaField, MetaQuery } from '@constructive-io/data';\n\nimport { useSheetsContext } from '../../context/sheets-context';\nimport { useSheetsMeta } from '../../hooks/use-sheets-meta';\nimport { useSheetsInfiniteTable, type UseInfiniteTableOptions } from '../../hooks/use-sheets-infinite-table';\n\nimport { getAllRelationFields } from '../../utils/relation-utils';\nimport { normalizeServerRow } from '../sheets.utils';\n\ntype RowRecord = Record<string, unknown>;\n\n/** Native inclusive row window — the DOM grid's visible-range shape (no glide Rectangle). */\nexport interface VisibleRowRange {\n\tstartIndex: number;\n\tendIndex: number;\n}\n\ntype MetaTable = NonNullable<NonNullable<NonNullable<MetaQuery['_meta']>['tables']>[number]>;\n\n/**\n * Apply field type overrides from SheetsConfig to field metadata.\n * Mirrors the logic in use-load-grid.ts for consistent behavior.\n */\nfunction buildFieldMetaMap(\n\tfields: MetaField[],\n\ttableName: string,\n\tfieldTypeOverrides?: Record<string, string>,\n): Map<string, MetaField> {\n\tconst map = new Map<string, MetaField>();\n\n\tif (!fields || fields.length === 0) return map;\n\n\tfor (const field of fields) {\n\t\tif (!field?.name) continue;\n\n\t\tconst overrideKey = `${tableName}.${field.name}`;\n\t\tconst overridePgAlias = fieldTypeOverrides?.[overrideKey];\n\n\t\tif (overridePgAlias && field.type?.pgAlias !== overridePgAlias) {\n\t\t\tmap.set(field.name, {\n\t\t\t\t...field,\n\t\t\t\ttype: {\n\t\t\t\t\t...field.type,\n\t\t\t\t\tpgAlias: overridePgAlias,\n\t\t\t\t},\n\t\t\t} as MetaField);\n\t\t} else {\n\t\t\tmap.set(field.name, field);\n\t\t}\n\t}\n\n\treturn map;\n}\n\nexport interface UseInfiniteGridDataOptions extends Omit<UseInfiniteTableOptions, 'select'> {\n\ttableName: string;\n}\n\nexport interface UseInfiniteGridDataResult {\n\t/** Get row at index, returns null if not loaded */\n\tgetRowAtIndex: (index: number) => RowRecord | null;\n\t/** Total count of rows */\n\ttotalCount: number;\n\t/** Check if row is loaded */\n\tisRowLoaded: (rowIndex: number) => boolean;\n\t/** Prefetch the rows in an inclusive visible window (native range, not a glide Rectangle). */\n\tonVisibleRegionChanged: (range: VisibleRowRange) => void;\n\t/** Whether data is loading */\n\tisLoading: boolean;\n\t/** Whether initial data has been fetched */\n\thasInitialData: boolean;\n\t/** Error if any */\n\terror: Error | null;\n\t/** Invalidate and refetch all data */\n\tinvalidate: () => void;\n\t/**\n\t * Optimistically update a single row in the cache without refetching.\n\t * Used after successful cell edits to avoid full grid refresh.\n\t * @param rowIndex The index of the row to update\n\t * @param patch Partial row data to merge with existing row\n\t * @returns true if the row was found and updated, false on a cache miss\n\t */\n\tupdateRowAtIndex: (rowIndex: number, patch: Partial<RowRecord>) => boolean;\n\t/** Table metadata */\n\ttableMeta: MetaTable | null;\n\t/** Field metadata map */\n\tfieldMetaMap: Map<string, MetaField>;\n\t/** All relation field names */\n\tallRelationFields: string[];\n\t/** Page size */\n\tpageSize: number;\n}\n\n/**\n * Hook that provides infinite scroll data loading for the grid\n */\nexport function useInfiniteGridData({\n\ttableName,\n\tpageSize = 100,\n\torderBy,\n\twhere,\n\tenabled = true,\n}: UseInfiniteGridDataOptions): UseInfiniteGridDataResult {\n\t// Get metadata\n\tconst { data: meta, error: metaError } = useSheetsMeta({ enabled });\n\tconst { config } = useSheetsContext();\n\n\tconst tableMeta = useMemo<MetaTable | null>(() => {\n\t\tconst candidate = meta?._meta?.tables?.find((t) => t?.name === tableName) as MetaTable | undefined;\n\t\treturn candidate ?? null;\n\t}, [meta, tableName]);\n\n\t// Field metadata map for quick lookup, enhanced with field type overrides\n\tconst fieldMetaMap = useMemo(() => {\n\t\tconst candidate = meta?._meta?.tables?.find((t) => t?.name === tableName) as MetaTable | undefined;\n\t\tconst fields = (candidate?.fields as MetaField[]) || [];\n\t\treturn buildFieldMetaMap(fields, tableName, config.fieldTypeOverrides);\n\t}, [meta, tableName, config.fieldTypeOverrides]);\n\n\tconst metaTables = meta?._meta?.tables;\n\tconst allRelationFields = useMemo<string[]>(\n\t\t() => {\n\t\t\tconst rawTables = metaTables?.filter((t): t is NonNullable<typeof t> => t != null);\n\t\t\treturn getAllRelationFields(tableMeta?.relations, rawTables);\n\t\t},\n\t\t[tableMeta, metaTables],\n\t);\n\n\tconst relationFieldNames = useMemo(() => new Set(allRelationFields), [allRelationFields]);\n\n\tconst fieldSelection = useMemo(() => {\n\t\tif (allRelationFields.length === 0) return 'all' as const;\n\t\treturn { includeRelations: allRelationFields };\n\t}, [allRelationFields]);\n\n\t// Use the infinite table hook\n\tconst infiniteTable = useSheetsInfiniteTable<RowRecord>(tableName, {\n\t\tpageSize,\n\t\torderBy,\n\t\twhere,\n\t\tselect: fieldSelection,\n\t\tenabled,\n\t});\n\n\t// Get row at index with normalization\n\t// Note: We don't cache normalized rows because optimistic updates change the underlying\n\t// data without changing the row id. Caching by id causes stale data to be returned.\n\t// Normalization is cheap enough to do on every access.\n\tconst getRowAtIndex = useCallback(\n\t\t(rowIndex: number): RowRecord | null => {\n\t\t\tconst rawRow = infiniteTable.getRowAtIndex(rowIndex);\n\t\t\tif (rawRow === null) return null;\n\n\t\t\t// Always normalize - caching caused stale data issues with optimistic updates\n\t\t\t// because the cache key (id) doesn't change when other fields are updated\n\t\t\treturn normalizeServerRow(rawRow, relationFieldNames);\n\t\t},\n\t\t[infiniteTable, relationFieldNames],\n\t);\n\n\t// Prefetch rows for an inclusive visible window (native range).\n\tconst onVisibleRegionChanged = useCallback(\n\t\t(range: VisibleRowRange) => {\n\t\t\tconst startRow = range.startIndex;\n\t\t\tconst endRow = range.endIndex;\n\n\t\t\t// Add buffer for smoother scrolling\n\t\t\tconst buffer = Math.ceil(pageSize / 2);\n\t\t\tinfiniteTable.ensureRowsLoaded(Math.max(0, startRow - buffer), endRow + buffer);\n\t\t},\n\t\t[infiniteTable, pageSize],\n\t);\n\n\t// Invalidate and refetch\n\tconst invalidate = useCallback(() => {\n\t\tinfiniteTable.invalidate();\n\t}, [infiniteTable]);\n\n\t// Optimistically update a single row without refetching\n\tconst updateRowAtIndex = useCallback(\n\t\t(rowIndex: number, patch: Partial<RowRecord>): boolean => {\n\t\t\t// Update the underlying React Query page cache\n\t\t\t// getRowAtIndex will return the updated data on next access.\n\t\t\t// Propagate the inner boolean so callers can self-heal (refetch) on a cache miss.\n\t\t\treturn infiniteTable.updateRowAtIndex(rowIndex, patch);\n\t\t},\n\t\t[infiniteTable],\n\t);\n\n\treturn {\n\t\tgetRowAtIndex,\n\t\ttotalCount: infiniteTable.totalCount,\n\t\tisRowLoaded: infiniteTable.isRowLoaded,\n\t\tonVisibleRegionChanged,\n\t\tisLoading: infiniteTable.isLoading,\n\t\thasInitialData: infiniteTable.hasInitialData,\n\t\terror: metaError ?? infiniteTable.error,\n\t\tinvalidate,\n\t\tupdateRowAtIndex,\n\t\ttableMeta,\n\t\tfieldMetaMap,\n\t\tallRelationFields,\n\t\tpageSize,\n\t};\n}\n","/**\n * Infinite scroll table hook with hybrid cursor-based pagination\n *\n * Uses a hybrid pagination strategy:\n * - Page 0: Offset-based (`first: N`) to get initial data + endCursor\n * - Page N+1: Cursor-based (`first: N, after: endCursor`) for efficient deep pagination\n *\n * This leverages PostGraphile's Relay Connection spec for optimal performance on large datasets.\n *\n * Data Persistence:\n * - Uses React Query cache as the source of truth for page data\n * - Data survives component unmount/remount and route changes\n * - Only clears when table name or query options actually change (deep comparison)\n *\n * Ported from apps/admin use-infinite-table.ts with context injection.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useQueries, useQueryClient } from '@tanstack/react-query';\n\nimport { useSheetsContext } from '../context/sheets-context';\nimport type { SheetsScopeKey } from '../context/sheets-context';\n\nimport {\n\tcleanTable,\n\ttype CleanTable,\n\ttype MetaTable,\n\ttype MutationOptions,\n\ttype PageInfo,\n\ttype QueryOptions,\n} from '@constructive-io/data';\nimport { createError } from '@constructive-io/data';\nimport type { FieldSelection } from '@constructive-io/data';\nimport { reuseSheetsPlaceholderData } from './query-keys';\nimport { toOrderByEnumValue } from '@constructive-io/data';\nimport { useSheetsAdapter } from '../adapter/use-sheets-adapter';\nimport { useSheetsMeta } from './use-sheets-meta';\nimport { sheetsQueryKeys } from './query-keys';\nimport { resolveRelationFieldMap } from './relation-field-resolution';\nimport { validateOrderByVariables } from './orderby-enum-resolution';\nimport { transformToPostGraphileVariables } from './use-sheets-table';\n\ntype RowRecord = Record<string, unknown>;\n\n/** Data for a single loaded page */\nexport interface PageData<T = RowRecord> {\n\trows: T[];\n\tpageInfo: PageInfo;\n\tpageIndex: number;\n\ttotalCount?: number;\n}\n\n/** Options for the infinite table hook */\nexport interface UseInfiniteTableOptions {\n\t/** Page size for fetching */\n\tpageSize?: number;\n\t/** Order by clauses */\n\torderBy?: Array<{ field: string; direction: 'asc' | 'desc' }>;\n\t/** Filter conditions */\n\twhere?: Record<string, unknown>;\n\t/** Field selection preset or custom selection */\n\tselect?: FieldSelection;\n\t/** Enable/disable the hook */\n\tenabled?: boolean;\n\t/** Mutation options for CRUD operations */\n\tmutationOptions?: MutationOptions;\n}\n\n/** Result from the infinite table hook */\nexport interface UseInfiniteTableResult<T = RowRecord> {\n\t/** Get row at a specific index, returns null if not loaded */\n\tgetRowAtIndex: (index: number) => T | null;\n\t/** Total count of rows in the table */\n\ttotalCount: number;\n\t/** Check if a specific row index is loaded */\n\tisRowLoaded: (rowIndex: number) => boolean;\n\t/** Check if a specific page is currently loading */\n\tisPageLoading: (pageIndex: number) => boolean;\n\t/** Ensure rows in a range are loaded (call from onVisibleRegionChanged) */\n\tensureRowsLoaded: (startRow: number, endRow: number) => void;\n\t/** All loaded pages */\n\tloadedPages: Map<number, PageData<T>>;\n\t/** Page size */\n\tpageSize: number;\n\t/** Overall loading state (true if any page is loading) */\n\tisLoading: boolean;\n\t/** Whether initial data has been loaded */\n\thasInitialData: boolean;\n\t/** Error from the most recent failed fetch */\n\terror: Error | null;\n\t/** Invalidate all pages and refetch */\n\tinvalidate: () => void;\n\t/** Reset to initial state (clears all pages, refetches page 0) */\n\treset: () => void;\n\t/**\n\t * Optimistically update a single row in the page cache without refetching.\n\t * @param rowIndex The absolute row index\n\t * @param patch Partial row data to merge with existing row\n\t * @returns true if the row was found and updated, false otherwise\n\t */\n\tupdateRowAtIndex: (rowIndex: number, patch: Partial<T>) => boolean;\n}\n\n/** Query key factory for infinite table pages */\nconst sheetsInfiniteTableKeys = {\n\tall: (scope: SheetsScopeKey, tableName: string) => sheetsQueryKeys.infiniteTable(scope, tableName),\n\tpage: (scope: SheetsScopeKey, tableName: string, pageIndex: number, optionsKey: string) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableName), 'page', pageIndex, optionsKey] as const,\n\ttotalCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown>) =>\n\t\tsheetsQueryKeys.infiniteTableTotalCount(scope, tableName, where),\n};\n\n/**\n * Create a stable JSON key from options for deep comparison.\n * This ensures the key only changes when the actual values change, not object references.\n */\nfunction createStableOptionsKey(options: {\n\tpageSize: number;\n\torderBy?: Array<{ field: string; direction: 'asc' | 'desc' }>;\n\twhere?: Record<string, unknown>;\n\tfieldSelection?: FieldSelection;\n}): string {\n\treturn JSON.stringify({\n\t\tpageSize: options.pageSize,\n\t\torderBy: options.orderBy ?? null,\n\t\twhere: options.where ?? null,\n\t\tfieldSelection: options.fieldSelection ?? null,\n\t});\n}\n\n/**\n * Hook for infinite scroll table with hybrid cursor-based pagination.\n * Uses React Query cache as the source of truth for data persistence.\n */\nexport function useSheetsInfiniteTable<T extends RowRecord = RowRecord>(\n\ttableName: string,\n\toptions: UseInfiniteTableOptions = {},\n): UseInfiniteTableResult<T> {\n\tconst { pageSize = 100, orderBy, where, select: fieldSelection, enabled = true } = options;\n\n\tconst queryClient = useQueryClient();\n\tconst { execute, scopeKey } = useSheetsContext();\n\tconst { data: meta } = useSheetsMeta({ enabled });\n\tconst adapter = useSheetsAdapter();\n\n\t// Create stable options key using JSON serialization for deep comparison\n\tconst stableOptionsKey = useMemo(\n\t\t() => createStableOptionsKey({ pageSize, orderBy, where, fieldSelection }),\n\t\t[pageSize, orderBy, where, fieldSelection],\n\t);\n\n\t// Track which pages we want to load\n\tconst [requestedPages, setRequestedPages] = useState<Set<number>>(() => new Set([0]));\n\n\t// Cursor chain for cursor-based pagination (stored in ref for performance)\n\tconst cursorChainRef = useRef<Map<number, string>>(new Map());\n\tconst [cursorChainVersion, setCursorChainVersion] = useState(0);\n\n\t// Track latest total count from any page response\n\tconst totalCountRef = useRef<number>(0);\n\n\t// Flag to defer cache invalidation to useEffect after synchronous reset\n\tconst needsInvalidationRef = useRef(false);\n\n\t// Generation counter: incremented on every table/options reset. queryFn closures capture\n\t// the current generation and skip cursor writes if stale. This prevents in-flight queries\n\t// from a previous table/options context from poisoning cursorChainRef after a reset.\n\t// (PostGraphile v5 cursors include a digest hash scoped to table + ORDER BY, so a cursor\n\t// from one query context will be rejected by a different query context.)\n\tconst generationRef = useRef(0);\n\n\t// Track previous stable key to detect actual changes\n\tconst prevStableKeyRef = useRef<string>(stableOptionsKey);\n\tconst prevTableNameRef = useRef<string>(tableName);\n\n\t// Get table metadata\n\tconst tables = useMemo<CleanTable[]>(() => {\n\t\tif (!meta?._meta?.tables) return [];\n\t\treturn meta._meta.tables\n\t\t\t.filter((candidate): candidate is MetaTable => candidate != null)\n\t\t\t.map((metaTable) => cleanTable(metaTable));\n\t}, [meta]);\n\n\tconst table = useMemo<CleanTable | null>(\n\t\t() => tables.find((candidate) => candidate.name === tableName) ?? null,\n\t\t[tables, tableName],\n\t);\n\n\t// Synchronous render-time reset: clear cursors and state BEFORE pageQueries useMemo reads them.\n\t// This follows the React 18+ \"storing information from previous renders\" pattern where setState\n\t// during render causes React to discard the current render and retry with updated state.\n\t// On retry, the condition is false (refs already updated) so no infinite loop occurs.\n\tconst tableChanged = prevTableNameRef.current !== tableName;\n\tconst optionsChanged = prevStableKeyRef.current !== stableOptionsKey;\n\n\tif (tableChanged || optionsChanged) {\n\t\t// Clear cursors synchronously — must happen before pageQueries useMemo\n\t\tcursorChainRef.current.clear();\n\t\ttotalCountRef.current = 0;\n\n\t\t// Bump generation so in-flight queryFn closures from the old context\n\t\t// will skip writing their stale cursors into cursorChainRef\n\t\tgenerationRef.current += 1;\n\n\t\t// Update tracking refs so condition is false on retry render\n\t\tprevTableNameRef.current = tableName;\n\t\tprevStableKeyRef.current = stableOptionsKey;\n\n\t\t// Flag cache invalidation for the subsequent useEffect\n\t\tneedsInvalidationRef.current = true;\n\n\t\t// Trigger state update — React discards current render and retries\n\t\tsetCursorChainVersion(0);\n\t\tsetRequestedPages(new Set([0]));\n\t}\n\n\t// Cache invalidation is a side effect and must stay in useEffect\n\tuseEffect(() => {\n\t\tif (needsInvalidationRef.current) {\n\t\t\tneedsInvalidationRef.current = false;\n\t\t\tqueryClient.invalidateQueries({\n\t\t\t\tqueryKey: sheetsInfiniteTableKeys.all(scopeKey, tableName),\n\t\t\t});\n\t\t}\n\t}, [tableName, stableOptionsKey, queryClient, scopeKey]);\n\n\t// Helper to get page data from React Query cache\n\tconst getPageDataFromCache = useCallback(\n\t\t(pageIndex: number): PageData<T> | undefined => {\n\t\t\treturn queryClient.getQueryData<PageData<T>>(\n\t\t\t\tsheetsInfiniteTableKeys.page(scopeKey, tableName, pageIndex, stableOptionsKey),\n\t\t\t);\n\t\t},\n\t\t[queryClient, scopeKey, tableName, stableOptionsKey],\n\t);\n\n\t// Create query options for each requested page\n\tconst pageQueries = useMemo(() => {\n\t\tif (!table || !enabled) return [];\n\t\t// Force recompute when cursor chain advances\n\t\tvoid cursorChainVersion;\n\n\t\t// Capture generation at useMemo time — queryFn closures use this to detect\n\t\t// if the query context has changed (table/options reset) before they write cursors\n\t\tconst queryGeneration = generationRef.current;\n\n\t\treturn Array.from(requestedPages).map((pageIndex) => {\n\t\t\t// Determine pagination strategy\n\t\t\tconst isFirstPage = pageIndex === 0;\n\t\t\tconst previousCursor = pageIndex > 0 ? cursorChainRef.current.get(pageIndex - 1) : undefined;\n\t\t\t// Pages:\n\t\t\t// - 0: always fetch\n\t\t\t// - 1: wait for cursor from page 0 (prefer cursor-based)\n\t\t\t// - 2+: allow offset fallback (supports scrollbar jumps without loading all intermediate pages)\n\t\t\tconst canUseOffsetFallback = pageIndex >= 2;\n\t\t\tconst canFetch = isFirstPage || previousCursor !== undefined || canUseOffsetFallback;\n\n\t\t\treturn {\n\t\t\t\tqueryKey: sheetsInfiniteTableKeys.page(scopeKey, tableName, pageIndex, stableOptionsKey),\n\t\t\t\tqueryFn: async (): Promise<PageData<T>> => {\n\t\t\t\t\tif (!table) {\n\t\t\t\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Build query options. `includePageInfo` is always set so the cursor\n\t\t\t\t\t// chain works on every page (page 0 has no `after` to imply pageInfo).\n\t\t\t\t\tconst queryOptions: QueryOptions = {\n\t\t\t\t\t\tfirst: pageSize,\n\t\t\t\t\t\torderBy,\n\t\t\t\t\t\twhere: where as QueryOptions['where'],\n\t\t\t\t\t\tfieldSelection,\n\t\t\t\t\t\tincludePageInfo: true, // Always include for cursor chain\n\t\t\t\t\t};\n\n\t\t\t\t\t// Prefer cursor-based pagination when possible; allow offset fallback for deep jumps.\n\t\t\t\t\tif (!isFirstPage) {\n\t\t\t\t\t\tif (previousCursor) {\n\t\t\t\t\t\t\tqueryOptions.after = previousCursor;\n\t\t\t\t\t\t} else if (canUseOffsetFallback) {\n\t\t\t\t\t\t\tqueryOptions.offset = pageIndex * pageSize;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Cache-bound resolution stays in the hook. The orderBy validation mutates\n\t\t\t\t\t// `variables.orderBy` (PostGraphile enum strings) in place; we fold that\n\t\t\t\t\t// result back into the `{ field, direction }[]` orderBy we hand the adapter,\n\t\t\t\t\t// so the adapter rebuilds an identical (validated) variables payload.\n\t\t\t\t\tconst variables = transformToPostGraphileVariables(table, queryOptions);\n\n\t\t\t\t\tconst [relationFieldMap] = await Promise.all([\n\t\t\t\t\t\tresolveRelationFieldMap({\n\t\t\t\t\t\t\ttable,\n\t\t\t\t\t\t\tfieldSelection: queryOptions.fieldSelection,\n\t\t\t\t\t\t\tscopeKey,\n\t\t\t\t\t\t\tqueryClient,\n\t\t\t\t\t\t\texecute,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tvalidateOrderByVariables(variables, table, scopeKey, queryClient, execute),\n\t\t\t\t\t]);\n\n\t\t\t\t\tconst validatedOrderByEnum = new Set((variables.orderBy as string[] | undefined) ?? []);\n\t\t\t\t\tconst availableOrderByFields = new Set(table.fields.map((field) => field.name));\n\t\t\t\t\tconst validatedOrderBy = orderBy?.filter(\n\t\t\t\t\t\t({ field, direction }) =>\n\t\t\t\t\t\t\tavailableOrderByFields.has(field) && validatedOrderByEnum.has(toOrderByEnumValue(field, direction)),\n\t\t\t\t\t);\n\n\t\t\t\t\tconst res = await adapter.listRows<T>(\n\t\t\t\t\t\t{ table, allTables: tables, tableName },\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...queryOptions,\n\t\t\t\t\t\t\torderBy: validatedOrderBy,\n\t\t\t\t\t\t\t// resolveRelationFieldMap yields `string | null` (null = omit field). The\n\t\t\t\t\t\t\t// contract narrows to `string`, but the null values are passed through to\n\t\t\t\t\t\t\t// buildSelect unchanged at runtime — behavior is identical to before.\n\t\t\t\t\t\t\trelationFieldMap: relationFieldMap as Record<string, string>,\n\t\t\t\t\t\t},\n\t\t\t\t\t\texecute,\n\t\t\t\t\t);\n\n\t\t\t\t\tconst rows = res.rows;\n\t\t\t\t\t// The adapter's AdapterPageInfo marks booleans optional; the underlying\n\t\t\t\t\t// PostGraphile connection always populates them (the doc selects all four),\n\t\t\t\t\t// so this narrows to PageInfo exactly as the inline connection cast did.\n\t\t\t\t\tconst pageInfo: PageInfo = (res.pageInfo as PageInfo | undefined) || {\n\t\t\t\t\t\thasNextPage: false,\n\t\t\t\t\t\thasPreviousPage: false,\n\t\t\t\t\t\tendCursor: null,\n\t\t\t\t\t\tstartCursor: null,\n\t\t\t\t\t};\n\n\t\t\t\t\t// Guard: only write refs if this queryFn's generation matches the current one.\n\t\t\t\t\t// In-flight queries from a previous table/options context will have a stale\n\t\t\t\t\t// generation and their writes are silently discarded.\n\t\t\t\t\tconst isCurrentGeneration = queryGeneration === generationRef.current;\n\n\t\t\t\t\t// Update total count ref\n\t\t\t\t\tif (res.totalCount !== undefined && isCurrentGeneration) {\n\t\t\t\t\t\ttotalCountRef.current = res.totalCount;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Store cursor for next page (and bump version so dependent pages can enable)\n\t\t\t\t\tif (pageInfo.endCursor && isCurrentGeneration) {\n\t\t\t\t\t\tconst prev = cursorChainRef.current.get(pageIndex);\n\t\t\t\t\t\tif (prev !== pageInfo.endCursor) {\n\t\t\t\t\t\t\tcursorChainRef.current.set(pageIndex, pageInfo.endCursor);\n\t\t\t\t\t\t\tsetCursorChainVersion((v) => v + 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst pageData: PageData<T> = {\n\t\t\t\t\t\trows,\n\t\t\t\t\t\tpageInfo,\n\t\t\t\t\t\tpageIndex,\n\t\t\t\t\t\ttotalCount: res.totalCount,\n\t\t\t\t\t};\n\n\t\t\t\t\treturn pageData;\n\t\t\t\t},\n\t\t\t\tenabled: enabled && !!table && canFetch,\n\t\t\t\t// Reuse a page across sort/filter/page-size key changes only while the\n\t\t\t\t// endpoint, database, and authenticated identity remain unchanged.\n\t\t\t\tplaceholderData: (\n\t\t\t\t\tpreviousData: PageData<T> | undefined,\n\t\t\t\t\tpreviousQuery: { queryKey: readonly unknown[] } | undefined,\n\t\t\t\t) =>\n\t\t\t\t\treuseSheetsPlaceholderData(previousData, previousQuery?.queryKey, scopeKey),\n\t\t\t\tstaleTime: 5 * 60 * 1000, // 5 minutes\n\t\t\t\tgcTime: 10 * 60 * 1000, // 10 minutes\n\t\t\t};\n\t\t});\n\t\t}, [\n\t\t\ttable,\n\t\t\ttables,\n\t\t\ttableName,\n\t\t\tenabled,\n\t\t\tscopeKey,\n\t\t\tqueryClient,\n\t\t\texecute,\n\t\t\tadapter,\n\t\t\trequestedPages,\n\t\t\tstableOptionsKey,\n\t\t\tpageSize,\n\t\torderBy,\n\t\twhere,\n\t\tfieldSelection,\n\t\tcursorChainVersion,\n\t]);\n\n\t// Execute all page queries\n\tconst queryResults = useQueries({ queries: pageQueries });\n\n\t// Sync cursor chain from React Query cache on mount/rehydration\n\t// This restores cursors for pages that were cached but cursor chain was lost.\n\t// Guarded by generation to avoid restoring stale cursors during a reset transition.\n\tuseEffect(() => {\n\t\tif (!enabled || !table) return;\n\n\t\tconst gen = generationRef.current;\n\n\t\t// Check React Query cache for existing page data and restore cursors\n\t\tfor (let i = 0; i < 100; i++) {\n\t\t\t// Bail if generation changed (a reset happened while this effect was running)\n\t\t\tif (gen !== generationRef.current) break;\n\n\t\t\t// Check up to 100 pages\n\t\t\tconst cachedData = getPageDataFromCache(i);\n\t\t\tif (cachedData?.pageInfo?.endCursor && !cursorChainRef.current.has(i)) {\n\t\t\t\tcursorChainRef.current.set(i, cachedData.pageInfo.endCursor);\n\t\t\t}\n\t\t\tif (cachedData?.totalCount !== undefined) {\n\t\t\t\ttotalCountRef.current = cachedData.totalCount;\n\t\t\t}\n\t\t\tif (!cachedData) break; // Stop at first missing page\n\t\t}\n\t}, [enabled, table, getPageDataFromCache]);\n\n\t// Compute loading states\n\tconst isLoading = queryResults.some((result) => result.isLoading);\n\n\t// Check if we have initial data - either from current query or from cache\n\tconst hasInitialData = useMemo(() => {\n\t\t// Check query results first\n\t\tconst page0Query = queryResults.find((_, idx) => Array.from(requestedPages)[idx] === 0);\n\t\tif (page0Query?.data) return true;\n\n\t\t// Fall back to cache check\n\t\tconst cachedPage0 = getPageDataFromCache(0);\n\t\treturn cachedPage0 !== undefined;\n\t}, [queryResults, requestedPages, getPageDataFromCache]);\n\n\tconst error = queryResults.find((result) => result.error)?.error ?? null;\n\n\t// Get row at index - reads from React Query cache\n\t// IMPORTANT: Always read from cache first since optimistic updates use setQueryData\n\t// which updates cache but doesn't immediately update queryResults references\n\tconst getRowAtIndex = useCallback(\n\t\t(rowIndex: number): T | null => {\n\t\t\tconst pageIndex = Math.floor(rowIndex / pageSize);\n\t\t\tconst rowIndexInPage = rowIndex % pageSize;\n\n\t\t\t// Always read from React Query cache first - this ensures we get optimistically\n\t\t\t// updated data from setQueryData calls (used in updateRowAtIndex)\n\t\t\tconst cachedData = getPageDataFromCache(pageIndex);\n\t\t\tif (cachedData) {\n\t\t\t\treturn cachedData.rows[rowIndexInPage] ?? null;\n\t\t\t}\n\n\t\t\t// Fall back to query results if cache miss (shouldn't happen normally)\n\t\t\tconst queryIndex = Array.from(requestedPages).indexOf(pageIndex);\n\t\t\tif (queryIndex !== -1 && queryResults[queryIndex]?.data) {\n\t\t\t\tconst pageData = queryResults[queryIndex].data;\n\t\t\t\treturn pageData.rows[rowIndexInPage] ?? null;\n\t\t\t}\n\n\t\t\treturn null;\n\t\t},\n\t\t[pageSize, getPageDataFromCache, requestedPages, queryResults],\n\t);\n\n\t// Check if row is loaded - reads from cache first for consistency with getRowAtIndex\n\tconst isRowLoaded = useCallback(\n\t\t(rowIndex: number): boolean => {\n\t\t\tconst pageIndex = Math.floor(rowIndex / pageSize);\n\t\t\tconst rowIndexInPage = rowIndex % pageSize;\n\n\t\t\t// Check cache first (consistent with getRowAtIndex)\n\t\t\tconst cachedData = getPageDataFromCache(pageIndex);\n\t\t\tif (cachedData) {\n\t\t\t\treturn rowIndexInPage < cachedData.rows.length;\n\t\t\t}\n\n\t\t\t// Fallback to query results\n\t\t\tconst queryIndex = Array.from(requestedPages).indexOf(pageIndex);\n\t\t\tif (queryIndex !== -1 && queryResults[queryIndex]?.data) {\n\t\t\t\treturn rowIndexInPage < queryResults[queryIndex].data.rows.length;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t},\n\t\t[pageSize, getPageDataFromCache, requestedPages, queryResults],\n\t);\n\n\t// Check if page is loading\n\tconst isPageLoading = useCallback(\n\t\t(pageIndex: number): boolean => {\n\t\t\tconst queryIndex = Array.from(requestedPages).indexOf(pageIndex);\n\t\t\tif (queryIndex === -1) return false;\n\t\t\treturn queryResults[queryIndex]?.isLoading ?? false;\n\t\t},\n\t\t[requestedPages, queryResults],\n\t);\n\n\t// Ensure rows in range are loaded\n\tconst ensureRowsLoaded = useCallback(\n\t\t(startRow: number, endRow: number) => {\n\t\t\tconst startPage = Math.floor(Math.max(0, startRow) / pageSize);\n\t\t\tconst endPage = Math.floor(Math.max(0, endRow - 1) / pageSize);\n\n\t\t\tconst minPage = Math.max(0, startPage);\n\t\t\tconst maxPage = endPage;\n\n\t\t\tsetRequestedPages((prev) => {\n\t\t\t\tconst next = new Set(prev);\n\t\t\t\tlet changed = false;\n\n\t\t\t\tconst maxPossiblePage =\n\t\t\t\t\ttotalCountRef.current > 0 ? Math.max(0, Math.ceil(totalCountRef.current / pageSize) - 1) : null;\n\t\t\t\tconst cappedMaxPage = maxPossiblePage === null ? maxPage : Math.min(maxPage, maxPossiblePage);\n\n\t\t\t\tfor (let page = minPage; page <= cappedMaxPage; page++) {\n\t\t\t\t\tif (!next.has(page)) {\n\t\t\t\t\t\tnext.add(page);\n\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn changed ? next : prev;\n\t\t\t});\n\t\t},\n\t\t[pageSize],\n\t);\n\n\t// Build loadedPages map from React Query cache for backward compatibility\n\tconst loadedPages = useMemo(() => {\n\t\tconst map = new Map<number, PageData<T>>();\n\n\t\t// Add data from current query results\n\t\tArray.from(requestedPages).forEach((pageIndex, idx) => {\n\t\t\tconst result = queryResults[idx];\n\t\t\tif (result?.data) {\n\t\t\t\tmap.set(pageIndex, result.data);\n\t\t\t}\n\t\t});\n\n\t\treturn map;\n\t}, [requestedPages, queryResults]);\n\n\t// Compute total count from query results or ref\n\tconst totalCount = useMemo(() => {\n\t\t// Try to get from latest query result\n\t\tfor (const result of queryResults) {\n\t\t\tif (result.data?.totalCount !== undefined) {\n\t\t\t\treturn result.data.totalCount;\n\t\t\t}\n\t\t}\n\t\treturn totalCountRef.current;\n\t}, [queryResults]);\n\n\t// Invalidate all pages\n\tconst invalidate = useCallback(() => {\n\t\t// Clear cursor chain and bump generation to discard in-flight stale cursors\n\t\tcursorChainRef.current.clear();\n\t\ttotalCountRef.current = 0;\n\t\tgenerationRef.current += 1;\n\t\tsetCursorChainVersion(0);\n\n\t\t// Reset to page 0\n\t\tsetRequestedPages(new Set([0]));\n\n\t\t// Invalidate React Query cache\n\t\tqueryClient.invalidateQueries({ queryKey: sheetsInfiniteTableKeys.all(scopeKey, tableName) });\n\t}, [queryClient, scopeKey, tableName]);\n\n\t// Reset to initial state\n\tconst reset = useCallback(() => {\n\t\tinvalidate();\n\t}, [invalidate]);\n\n\t// Optimistically update a single row in the React Query cache\n\tconst updateRowAtIndex = useCallback(\n\t\t(rowIndex: number, patch: Partial<T>): boolean => {\n\t\t\tconst pageIndex = Math.floor(rowIndex / pageSize);\n\t\t\tconst rowIndexInPage = rowIndex % pageSize;\n\n\t\t\tconst queryKey = sheetsInfiniteTableKeys.page(scopeKey, tableName, pageIndex, stableOptionsKey);\n\t\t\tconst cachedData = queryClient.getQueryData<PageData<T>>(queryKey);\n\n\t\t\tif (!cachedData || !cachedData.rows[rowIndexInPage]) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Update the cache optimistically\n\t\t\tqueryClient.setQueryData<PageData<T>>(queryKey, (old) => {\n\t\t\t\tif (!old) return old;\n\n\t\t\t\tconst newRows = [...old.rows];\n\t\t\t\tnewRows[rowIndexInPage] = { ...newRows[rowIndexInPage], ...patch } as T;\n\n\t\t\t\treturn {\n\t\t\t\t\t...old,\n\t\t\t\t\trows: newRows,\n\t\t\t\t};\n\t\t\t});\n\n\t\t\treturn true;\n\t\t},\n\t\t[pageSize, queryClient, scopeKey, tableName, stableOptionsKey],\n\t);\n\n\treturn {\n\t\tgetRowAtIndex,\n\t\ttotalCount,\n\t\tisRowLoaded,\n\t\tisPageLoading,\n\t\tensureRowsLoaded,\n\t\tloadedPages,\n\t\tpageSize,\n\t\tisLoading,\n\t\thasInitialData,\n\t\terror: error as Error | null,\n\t\tinvalidate,\n\t\treset,\n\t\tupdateRowAtIndex,\n\t};\n}\n\n/**\n * Export query keys for external cache management\n */\nexport { sheetsInfiniteTableKeys };\n","import { useMemo } from 'react';\nimport type { ReactNode } from 'react';\n\nimport { assessTableWriteCapability, getRowIdentityDefinition } from '@constructive-io/data';\nimport type { FieldSelection, MetaField, MetaQuery, QueryOptions, TableWriteCapability } from '@constructive-io/data';\n\nimport { useSheetsContext } from '../../context/sheets-context';\nimport { useSheetsMeta } from '../../hooks/use-sheets-meta';\nimport { useSheetsTable, type UseTableResult } from '../../hooks/use-sheets-table';\nimport { getAllRelationFields } from '../../utils/relation-utils';\nimport { createColumnSchemaFromMeta } from '../../cell-types/type-mapping';\nimport type { TableSchema, ColumnSchema } from '../../cell-types/types';\nimport { resolveSheetsRowIdentity } from '../../row-identity';\n\ntype MetaTable = NonNullable<NonNullable<NonNullable<MetaQuery['_meta']>['tables']>[number]>;\ntype RowRecord = Record<string, unknown>;\ntype TableOperations = Pick<UseTableResult<RowRecord>, 'update' | 'delete'>;\ntype CreatedRow = Record<string, unknown>;\n\n// Data loading context type\nexport interface DataLoadingContextValue {\n\t// Table data\n\tdata: RowRecord[];\n\ttotalCount: number;\n\t// Loading states\n\tisLoading: boolean;\n\tisError: boolean;\n\terror: Error | null;\n\t// CRUD operations\n\tupdate: TableOperations['update'];\n\tcreate: (data: Record<string, unknown>) => Promise<{ createdRow?: CreatedRow | null }>;\n\tdelete: TableOperations['delete'];\n\t// Refetch the table query (used by the error-state retry)\n\trefetch: () => Promise<unknown>;\n\t// Meta information\n\tmeta: MetaQuery | undefined;\n\ttableMeta: MetaTable | null;\n\twriteCapability: TableWriteCapability | null;\n\ttableSchema: TableSchema | null;\n\tfieldMetaMap: Map<string, MetaField>;\n\tallRelationFields: string[];\n}\n\n// Data loading hook configuration\nexport interface UseDataLoadingConfig {\n\ttableName: string;\n\tenabled?: boolean;\n\tqueryOptions: {\n\t\tlimit?: number;\n\t\toffset?: number;\n\t\torderBy?: Array<{ field: string; direction: 'asc' | 'desc' }>;\n\t\twhere?: QueryOptions['where'];\n\t};\n}\n\n/**\n * Apply field type overrides from SheetsConfig to field metadata.\n *\n * In the admin app, this was handled by `buildEnhancedFieldMetaMap` which\n * merged smartTags.pgAlias from schema-builder. In sheets, the consumer\n * passes `config.fieldTypeOverrides` as a Record<string, string> where\n * key is \"tableName.fieldName\" and value is the cell type override (pgAlias).\n */\nfunction buildFieldMetaMap(\n\tfields: MetaField[],\n\ttableName: string,\n\tfieldTypeOverrides?: Record<string, string>,\n): Map<string, MetaField> {\n\tconst map = new Map<string, MetaField>();\n\n\tif (!fields || fields.length === 0) return map;\n\n\tfor (const field of fields) {\n\t\tif (!field?.name) continue;\n\n\t\t// Check for field type override\n\t\tconst overrideKey = `${tableName}.${field.name}`;\n\t\tconst overridePgAlias = fieldTypeOverrides?.[overrideKey];\n\n\t\tif (overridePgAlias && field.type?.pgAlias !== overridePgAlias) {\n\t\t\t// Apply override\n\t\t\tmap.set(field.name, {\n\t\t\t\t...field,\n\t\t\t\ttype: {\n\t\t\t\t\t...field.type,\n\t\t\t\t\tpgAlias: overridePgAlias,\n\t\t\t\t},\n\t\t\t} as MetaField);\n\t\t} else {\n\t\t\tmap.set(field.name, field);\n\t\t}\n\t}\n\n\treturn map;\n}\n\n// Main data loading hook\nexport function useDataLoading({\n\ttableName,\n\tenabled = true,\n\tqueryOptions,\n}: UseDataLoadingConfig) {\n\t// Meta data for table information\n\tconst { data: meta, isLoading: isMetaLoading, error: metaError } = useSheetsMeta({ enabled });\n\tconst { config } = useSheetsContext();\n\n\tconst tableMeta = useMemo<MetaTable | null>(() => {\n\t\tconst candidate = meta?._meta?.tables?.find((t) => t?.name === tableName) as MetaTable | undefined;\n\t\treturn candidate ?? null;\n\t}, [meta, tableName]);\n\n\t// Table schema for form integration\n\tconst tableSchema = useMemo<TableSchema | null>(() => buildTableSchema(tableMeta), [tableMeta]);\n\tconst writeCapability = useMemo<TableWriteCapability | null>(\n\t\t() => tableMeta ? assessTableWriteCapability(tableMeta) : null,\n\t\t[tableMeta],\n\t);\n\n\t// Field metadata map for quick lookup, enhanced with field type overrides\n\tconst fieldMetaMap = useMemo(() => {\n\t\tconst candidate = meta?._meta?.tables?.find((t) => t?.name === tableName) as MetaTable | undefined;\n\t\tconst fields = (candidate?.fields as MetaField[]) || [];\n\t\treturn buildFieldMetaMap(fields, tableName, config.fieldTypeOverrides);\n\t}, [meta, tableName, config.fieldTypeOverrides]);\n\n\tconst metaTables = meta?._meta?.tables;\n\tconst allRelationFields = useMemo(\n\t\t() => {\n\t\t\tconst rawTables = metaTables?.filter((t): t is NonNullable<typeof t> => t != null);\n\t\t\treturn getAllRelationFields(tableMeta?.relations, rawTables);\n\t\t},\n\t\t[tableMeta, metaTables],\n\t);\n\n\tconst relationSelection = useMemo<FieldSelection>(() => {\n\t\treturn allRelationFields.length > 0 ? { includeRelations: allRelationFields } : 'all';\n\t}, [allRelationFields]);\n\n\tconst tableData = useSheetsTable<RowRecord>(tableName, {\n\t\t...queryOptions,\n\t\t// Leverage field selection to include relation fields when requested\n\t\tselect: relationSelection,\n\t\tenabled,\n\t});\n\tconst {\n\t\tdata = [],\n\t\ttotalCount,\n\t\tupdate: updateRow,\n\t\tcreate: createRow,\n\t\tdelete: deleteRow,\n\t\tisLoading: isTableLoading,\n\t\terror: tableError,\n\t\trefetch,\n\t} = tableData;\n\n\tconst create: DataLoadingContextValue['create'] = async (payload) => {\n\t\tconst result = await createRow(payload);\n\t\tconst createdRow = result?.createdRow;\n\t\tif (!createdRow || typeof createdRow !== 'object' || !tableMeta) {\n\t\t\tthrow new Error(`Create mutation for '${tableName}' did not return a row identity.`);\n\t\t}\n\t\tconst identity = resolveSheetsRowIdentity(tableMeta, createdRow);\n\t\tif (identity.status !== 'identified') {\n\t\t\tthrow new Error(`Create mutation for '${tableName}' returned an incomplete primary-key identity.`);\n\t\t}\n\n\t\treturn { createdRow: createdRow as CreatedRow };\n\t};\n\n\t// Combined loading and error states\n\tconst isLoading = isMetaLoading || isTableLoading;\n\tconst isError = !!metaError || !!tableError;\n\tconst error = (metaError as Error | null) || (tableError as Error | null) || null;\n\n\tconst contextValue: DataLoadingContextValue = useMemo(\n\t\t() => ({\n\t\t\tdata,\n\t\t\ttotalCount,\n\t\t\tisLoading,\n\t\t\tisError,\n\t\t\terror,\n\t\t\tupdate: updateRow,\n\t\t\tcreate,\n\t\t\tdelete: deleteRow,\n\t\t\trefetch,\n\t\t\tmeta,\n\t\t\ttableMeta,\n\t\t\twriteCapability,\n\t\t\ttableSchema,\n\t\t\tfieldMetaMap,\n\t\t\tallRelationFields,\n\t\t}),\n\t\t[\n\t\t\tdata,\n\t\t\ttotalCount,\n\t\t\tisLoading,\n\t\t\tisError,\n\t\t\terror,\n\t\t\tupdateRow,\n\t\t\tcreate,\n\t\t\tdeleteRow,\n\t\t\trefetch,\n\t\t\tmeta,\n\t\t\ttableMeta,\n\t\t\twriteCapability,\n\t\t\ttableSchema,\n\t\t\tfieldMetaMap,\n\t\t\tallRelationFields,\n\t\t],\n\t);\n\n\treturn {\n\t\tcontextValue,\n\t\tProvider: ({ children }: { children: ReactNode }) => children,\n\t};\n}\n\nfunction buildTableSchema(metaTable: MetaTable | null): TableSchema | null {\n\tif (!metaTable) return null;\n\n\tconst columns: ColumnSchema[] = [];\n\tfor (const field of metaTable.fields ?? []) {\n\t\tif (!field) continue;\n\t\tcolumns.push(createColumnSchemaFromMeta(field));\n\t}\n\n\tconst identity = getRowIdentityDefinition(metaTable);\n\tconst primaryKeyFields = identity.status === 'keyed'\n\t\t? identity.fields.map((field) => field.fieldName)\n\t\t: [];\n\n\tconst inflection = metaTable.inflection;\n\n\tconst metadata: TableSchema['metadata'] = {\n\t\tlabel: metaTable.name ?? undefined,\n\t\tdescription: inflection?.tableType ?? inflection?.allRows ?? undefined,\n\t\tprimaryKey: primaryKeyFields.length > 0 ? primaryKeyFields : undefined,\n\t};\n\n\treturn {\n\t\tid: metaTable.name ?? 'unknown-table',\n\t\tname: metaTable.name ?? 'unknown-table',\n\t\tcolumns,\n\t\tmetadata,\n\t};\n}\n\n// Convenience hooks for accessing specific parts of the context\nexport function useTableData(): null {\n\treturn null;\n}\nexport function useTableOperations(): null {\n\treturn null;\n}\nexport function useTableMeta(): null {\n\treturn null;\n}\n","// The TanStack Table v9 instance for the DOM port.\n//\n// This is a STATE-MIRROR over already-server-processed rows — NOT a layout\n// layer (TanStack Virtual does layout in S4) and NOT a data layer (useSheets\n// does data). The hook takes EXPLICIT params (it never calls useSheets) so it\n// is unit-testable with hand-fed data.\n//\n// Controlled state (S1): v8-style `state` partial + per-feature `on*Change`\n// callbacks. The CALLER owns the slices (useGridState / the store) — the table\n// is never a second writer, so there is no echo loop.\n//\n// manualSorting / manualFiltering / manualPagination / rowCount are OMITTED:\n// they live only on the sorting/filtering/pagination feature option types,\n// which we do not register, so those keys are not in our TableOptions and\n// passing them is a TS error (S1 verdict).\nimport { useMemo } from 'react';\nimport { createColumnHelper, useTable } from '@tanstack/react-table';\nimport type {\n\tColumnDef,\n\tColumnPinningState,\n\tColumnResizeMode,\n\tColumnSizingState,\n\tOnChangeFn,\n\tRowSelectionState\n} from '@tanstack/react-table';\n\nimport type { SheetsRow } from '../grid/row-model';\nimport { sheetsTableFeatures, type SheetsTableFeatures } from './features';\n\n/** Smallest column descriptor the instance needs — key + header label (+ optional width). */\nexport interface SheetsColumnDescriptor {\n\tkey: string;\n\tname: string;\n\tsize?: number;\n}\n\nexport type SheetsColumnDef = ColumnDef<SheetsTableFeatures, SheetsRow>;\n\nexport interface UseSheetsTableInstanceParams {\n\t/** Render-column descriptors (header label + key), in display order. */\n\tcolumns: SheetsColumnDescriptor[];\n\t/** Rows fed AS-IS — already server sorted/filtered/paginated by useSheets. */\n\tdata: SheetsRow[];\n\t/** Committed column widths (caller-owned). */\n\tcolumnSizing: ColumnSizingState;\n\t/** Logical start/end column pins (caller-owned). */\n\tcolumnPinning: ColumnPinningState;\n\t/** Row selection map (caller-owned). */\n\trowSelection: RowSelectionState;\n\tonColumnSizingChange: OnChangeFn<ColumnSizingState>;\n\tonColumnPinningChange: OnChangeFn<ColumnPinningState>;\n\tonRowSelectionChange: OnChangeFn<RowSelectionState>;\n\t/** Stable row id from the server primary key / draft meta. Defaults to `row.id`. */\n\tgetRowId?: (row: SheetsRow, index: number) => string;\n}\n\nfunction defaultGetRowId(row: SheetsRow, index: number): string {\n\t// In infinite-scroll mode `data` is the null-backed proxy from useSheets: indices not yet\n\t// fetched read back as `null`. TanStack Table v9 builds its row model over EVERY index\n\t// (getRowId is called per row, eagerly), so guard the null placeholder and key it on the\n\t// index — the stable id an unloaded slot should carry until its page resolves.\n\treturn row?.id != null ? String(row.id) : String(index);\n}\n\n/**\n * Build a v9 table instance wired with {@link sheetsTableFeatures} and the\n * caller-owned controlled state. The column defs carry only a minimal value\n * accessor (`row[key]`); the actual cell RENDER is the S5 host's job, so no\n * `cell` renderer is duplicated here.\n */\nexport function useSheetsTableInstance(params: UseSheetsTableInstanceParams) {\n\tconst {\n\t\tcolumns,\n\t\tdata,\n\t\tcolumnSizing,\n\t\tcolumnPinning,\n\t\trowSelection,\n\t\tonColumnSizingChange,\n\t\tonColumnPinningChange,\n\t\tonRowSelectionChange,\n\t\tgetRowId = defaultGetRowId\n\t} = params;\n\n\tconst columnDefs = useMemo<SheetsColumnDef[]>(() => {\n\t\tconst helper = createColumnHelper<SheetsTableFeatures, SheetsRow>();\n\t\t// accessor-FUNCTION branch (value by key) → requires an explicit `id`. Null-guard the row:\n\t\t// v9 evaluates accessors eagerly while building the row model, and in infinite-scroll mode\n\t\t// `data` is the null-backed proxy (unloaded indices read as `null`). The DOM cell host paints\n\t\t// those slots from `getSheetsCellContent` (→ loading skeleton), so this accessor value is only\n\t\t// a placeholder; returning `undefined` for a null row keeps the eager build from throwing.\n\t\treturn columns.map((col) => helper.accessor((row) => row?.[col.key], { id: col.key, header: col.name, size: col.size }));\n\t}, [columns]);\n\n\t// The v9 pinning feature reads `state.columnPinning.{start,end}` directly (no defaulting\n\t// when a partial object is supplied), so `column.getIsPinned()` throws on a bare `{}`.\n\t// Normalize to a complete shape so callers may pass `{}` for \"nothing pinned\".\n\tconst normalizedPinning = useMemo<ColumnPinningState>(\n\t\t() => ({ start: columnPinning.start ?? [], end: columnPinning.end ?? [] }),\n\t\t[columnPinning]\n\t);\n\n\treturn useTable({\n\t\tfeatures: sheetsTableFeatures,\n\t\tcolumns: columnDefs,\n\t\tdata,\n\t\tgetRowId,\n\t\tenableColumnPinning: true,\n\t\tenableColumnResizing: true,\n\t\tenableRowSelection: true,\n\t\tcolumnResizeMode: 'onChange' as ColumnResizeMode,\n\t\t// Controlled: our reducer/store is the source of truth for these slices.\n\t\tstate: { columnSizing, columnPinning: normalizedPinning, rowSelection },\n\t\tonColumnSizingChange,\n\t\tonColumnPinningChange,\n\t\tonRowSelectionChange\n\t\t// Subscribe to NOTHING (`() => null`). v9 `useTable` runs `table.setOptions(...)` DURING render\n\t\t// to sync the controlled `state` above into its @tanstack/store atoms; a broad selector would make\n\t\t// THIS component a store subscriber, so that render-phase write notifies it synchronously →\n\t\t// `forceStoreRerender` → React's \"Cannot update a component while rendering\" warning. The slices\n\t\t// are caller-owned (the shell is the single source of truth) and the DOM grid reads layout via direct\n\t\t// table methods (getRowModel/getSize/getIsPinned), not `table.state`, so no subscription is needed —\n\t\t// the grid already re-renders from the shell's own state. (TanStack production-readiness: prefer\n\t\t// `() => null` + `table.Subscribe` over a broad `() => state` selector.)\n\t}, (): null => null);\n}\n","// The TanStack Table v9 feature set for the DOM port — EXACTLY the four\n// client-state features (S1). No sort/filter/pagination features and no\n// row-model factories: rows arrive already server-sorted/filtered/paginated\n// from useSheets, so this instance is a pure column + selection state-mirror.\n//\n// Built at module scope so the feature object has a stable identity across\n// renders (a fresh tableFeatures({...}) per render would churn the table).\nimport {\n\tcolumnSizingFeature, // committed column widths -> state.columnSizing\n\tcolumnResizingFeature, // transient drag-resize -> state.columnResizing\n\tcolumnPinningFeature, // logical start/end pin -> state.columnPinning\n\trowSelectionFeature, // row selection -> state.rowSelection\n\ttableFeatures\n} from '@tanstack/react-table';\n\nexport const sheetsTableFeatures = tableFeatures({\n\tcolumnSizingFeature,\n\tcolumnResizingFeature,\n\tcolumnPinningFeature,\n\trowSelectionFeature\n});\n\nexport type SheetsTableFeatures = typeof sheetsTableFeatures;\n","// The DOM viewport for the TanStack port — where LAYOUT happens (the v9 table\n// instance from S3 is a pure state-mirror; this is the dual-axis TanStack\n// Virtual shell that paints it).\n//\n// VERTICAL virtualizer over rows (dynamic height via measureElement), HORIZONTAL\n// virtualizer over columns. The STICKY column (start-pinned via columnPinning, or\n// the first column when nothing is pinned) is painted OUTSIDE the horizontal\n// virtual window — a separate `left: 0` element per row — so it stays put under\n// horizontal scroll. The horizontal virtualizer still counts it (so column start\n// offsets stay correct), but the item loop SKIPS the sticky index; it is never\n// double-painted.\n//\n// A sticky HEADER band (S1) sits at the top of the scroll content, reusing the\n// SAME column layout as the body (sticky-col header + the virtualized non-sticky\n// headers at the identical translateX offsets). Each header carries a sort caret\n// (clickable -> onHeaderClick) and a drag-resize handle on its right edge.\n//\n// `renderCell` is injected so S4 stays host-decoupled and testable: S5 supplies\n// the real cell host. The root carries `data-impl=\"dom\"` so tests / Chrome can\n// assert the DOM path is live.\nimport { useImperativeHandle, useMemo, useRef } from 'react';\nimport type { Ref } from 'react';\nimport { useVirtualizer } from '@tanstack/react-virtual';\nimport type { Cell, Column, Row, Table } from '@tanstack/react-table';\n\nimport { Checkbox } from '@constructive-io/ui/checkbox';\n\nimport { cn } from '../utils/cn';\nimport type { SheetsRow } from '../grid/row-model';\nimport type { SelectionRect } from '../selection/selection-model';\nimport type { SheetsTableFeatures } from './features';\n\n/** Comfortable density default (DESIGN_SPEC §5). Drives the v-virtualizer estimate,\n * range-band / fill-nub geometry, and hit-testing — change here propagates everywhere. */\nconst ESTIMATED_ROW_HEIGHT = 44;\n/** Extra rows rendered above/below the visible window — fewer blank rows on fast vertical scroll. */\nconst ROW_OVERSCAN = 12;\n/** Extra columns rendered left/right of the visible window — fewer blank cells on fast horizontal scroll. */\nconst COLUMN_OVERSCAN = 6;\n/** Header band height (DESIGN_SPEC §5 comfortable) — slightly shorter than the body row. */\nconst HEADER_HEIGHT = 40;\n/** Width of the optional leading row-marker (checkbox) column — glide's rowMarker analogue. */\nconst MARKER_WIDTH = 40;\n\n// Row-hover tint for the PINNED (sticky) cells. The pinned column/marker sit OVER the\n// horizontally-scrolled body, so their hover background must be fully OPAQUE — a translucent\n// `bg-muted/50` (as used on the row itself) would let the scrolled-away cells bleed through the\n// pinned column on hover. `color-mix` precomputes the SAME tint as opaque: 50% muted over the\n// surface, so the pinned column matches the row exactly while staying solid. Theme-safe (the raw\n// `--muted`/`--background` vars flip in dark mode). Uses raw vars, not `--color-*`, because the UI\n// theme is `@theme inline` (the `--color-*` aliases aren't emitted at runtime).\nconst PINNED_HOVER_BG = 'group-hover:bg-[color-mix(in_oklab,var(--muted)_50%,var(--background))]';\n\ntype SheetsTable = Table<SheetsTableFeatures, SheetsRow>;\ntype SheetsTableCell = Cell<SheetsTableFeatures, SheetsRow, unknown>;\ntype SheetsTableColumn = Column<SheetsTableFeatures, SheetsRow, unknown>;\n\n/** Sorting state mirror (the shell owns it via useGridState — `id:null` = unsorted). */\nexport interface GridViewportSorting {\n\tid: string | null;\n\tdesc: boolean;\n}\n\n/** Per-cell layout context handed to the host alongside the v9 cell. */\nexport interface RenderCellContext {\n\trowIndex: number;\n\tcolumnIndex: number;\n\t/** True for the sticky column, painted outside the h-virtual window. */\n\tisStickyColumn: boolean;\n\t/** True when this cell is the active (keyboard cursor) cell. Drives the focus ring. */\n\tisActive: boolean;\n}\n\nexport type RenderCell = (cell: SheetsTableCell, ctx: RenderCellContext) => React.ReactNode;\n\n/** Imperative handle for the later SheetsHandle scrollToRow path. */\nexport interface GridViewportHandle {\n\tscrollToIndex: (rowIndex: number) => void;\n\t/** Scroll the given cell into view (row + column virtualizers). Used by keyboard nav. */\n\tscrollToCell: (columnIndex: number, rowIndex: number) => void;\n}\n\n/** Visible row window (overscan-inclusive) reported to the shell for infinite-scroll prefetch. */\nexport interface VisibleRange {\n\tstartIndex: number;\n\tendIndex: number;\n}\n\nexport interface GridViewportProps {\n\ttable: SheetsTable;\n\trenderCell: RenderCell;\n\thandleRef?: Ref<GridViewportHandle>;\n\t/**\n\t * Fired on the scroll root's `scroll`. The DOM grid uses this to close (commit-or-\n\t * dismiss) any open overlay editor: a virtualized cell anchor can unmount under\n\t * scroll, so Phase-4 closes rather than re-positions against a stale rect.\n\t */\n\tonScroll?: (e: React.UIEvent<HTMLDivElement>) => void;\n\t/** Sort caret state for the header. Defaults to unsorted (`{ id: null, desc: false }`). */\n\tsorting?: GridViewportSorting;\n\t/** Toggle sort for a column. The shell wires this to onHeaderClicked / toggleSorting. */\n\tonHeaderClick?: (colKey: string) => void;\n\t/**\n\t * Commit a column width from the header drag-resize handle. When provided, the handle\n\t * drives a manual pointer-drag against this (shell sizing lives in useGridState). When\n\t * omitted, the handle falls back to the v9 `header.getResizeHandler()` (columnResizeMode\n\t * 'onChange' feeds the table's own columnSizing state).\n\t */\n\tonResize?: (colKey: string, width: number) => void;\n\t/**\n\t * Total row count for the VERTICAL virtualizer. Defaults to the table's row-model length.\n\t * Infinite scroll passes the server total here so the scrollbar spans every (lazily loaded)\n\t * row — the table's `data` is the same-length proxy, so this matches `rows.length` in practice\n\t * but is threaded explicitly so the shell stays the single source of truth for row count.\n\t */\n\tcount?: number;\n\t/**\n\t * Fired (effect-free, via the row virtualizer's `onChange`) with the current overscan-inclusive\n\t * visible window. The shell maps this to the canvas `onVisibleRegionChanged({ y, height })` so\n\t * infinite-scroll prefetch runs identically. Omitted in paginated mode.\n\t */\n\tonVisibleRangeChange?: (range: VisibleRange) => void;\n\t/**\n\t * Optional leading checkbox / select-all column (glide's `rowMarkers` analogue). When supplied,\n\t * a sticky MARKER column (fixed {@link MARKER_WIDTH}px) is painted to the LEFT of the sticky col0,\n\t * driving the canonical {@link SheetsSelection} RangeSet. When OMITTED, the grid renders exactly as\n\t * before (no marker column) so existing tests/stories that pass no rowMarker are unaffected.\n\t */\n\trowMarker?: RowMarker;\n\t/** Active (keyboard cursor) cell `[col, row]`. Drives the per-cell focus ring + aria-activedescendant. */\n\tactiveCell?: [number, number];\n\t/** Active range (cell coords) — rendered as an inert pointer-events-none band overlay. P2 populates it. */\n\tactiveRange?: SelectionRect;\n\t/** Keydown handler for the grid root — the shell owns spreadsheet nav (arrows / Enter / F2). */\n\tonGridKeyDown?: (e: React.KeyboardEvent) => void;\n\t/**\n\t * Native clipboard handlers for the grid root. They fire only when the root (tabIndex=0) holds\n\t * focus and an overlay editor is NOT open (the editor owns its own clipboard while editing). The\n\t * shell routes each to the `clipboard.copy`/`cut`/`paste` command through the ONE dispatch pipeline.\n\t */\n\tonCopy?: (e: React.ClipboardEvent) => void;\n\tonCut?: (e: React.ClipboardEvent) => void;\n\tonPaste?: (e: React.ClipboardEvent) => void;\n\t/** DOM id of the active cell node, mirrored to `aria-activedescendant` on the grid root. */\n\tactiveDescendantId?: string;\n\t/**\n\t * Fired on a fill-handle (nub) drag RELEASE when the dropped cell extends the source range.\n\t * `sourceRange` is the active range (or a 1×1 rect at the active cell) the drag started from;\n\t * `target` is the `[col,row]` under the pointer at release (clamped to grid bounds). The shell\n\t * routes this to the `fill.drag` command. Omitted = no nub rendered.\n\t */\n\tonFillDrag?: (sourceRange: SelectionRect, target: [number, number]) => void;\n\tclassName?: string;\n}\n\n/** Selection wiring for the leading checkbox column. The shell derives this from SheetsSelection. */\nexport interface RowMarker {\n\t/** True when row `rowIndex` is in the canonical selection. */\n\tisSelected: (rowIndex: number) => boolean;\n\t/** Toggle row `rowIndex`; `shiftKey` requests a contiguous range-select from the last anchor. */\n\tonToggleRow: (rowIndex: number, shiftKey: boolean) => void;\n\t/** Every row selected — the header checkbox shows checked. */\n\tallSelected: boolean;\n\t/** Some (but not all) rows selected — the header checkbox shows indeterminate. */\n\tsomeSelected: boolean;\n\t/** Select-all / clear-all from the header checkbox. */\n\tonToggleAll: () => void;\n}\n\nfunction cellForColumnIndex(row: Row<SheetsTableFeatures, SheetsRow>, columnIndex: number): SheetsTableCell {\n\treturn row.getAllCells()[columnIndex];\n}\n\n/**\n * Project a half-open active {@link SelectionRect} (cell coords) into px box geometry for\n * the inert range-band overlay. X/width sum `columns[i].getSize()` across the spanned cols\n * (honoring the leading `markerWidth` offset); Y/height use the uniform ESTIMATED_ROW_HEIGHT.\n * INERT in P1 (nothing sets `activeRange`); wired so P2 just populates `current.range`.\n */\nfunction rangeBandStyle(range: SelectionRect, columns: SheetsTableColumn[], markerWidth: number): React.CSSProperties {\n\tlet left = markerWidth;\n\tfor (let i = 0; i < range.x && i < columns.length; i++) left += columns[i].getSize();\n\tlet width = 0;\n\tfor (let i = range.x; i < range.x + range.width && i < columns.length; i++) width += columns[i].getSize();\n\treturn {\n\t\ttransform: `translate(${left}px, ${range.y * ESTIMATED_ROW_HEIGHT}px)`,\n\t\twidth,\n\t\theight: range.height * ESTIMATED_ROW_HEIGHT\n\t};\n}\n\n/** Side of the square fill-handle nub (px). Centered on the source rect's bottom-right corner. */\nconst FILL_NUB_SIZE = 8;\n\n/**\n * Position the fill-handle nub centered on the BOTTOM-RIGHT corner of the source {@link SelectionRect}.\n * Reuses {@link rangeBandStyle}'s left/width math (column-width sum + markerWidth) so the nub tracks\n * scroll in the SAME body coordinate space as the range band; the corner is `(left+width, top+height)`.\n */\nfunction fillNubStyle(source: SelectionRect, columns: SheetsTableColumn[], markerWidth: number): React.CSSProperties {\n\tlet left = markerWidth;\n\tfor (let i = 0; i < source.x && i < columns.length; i++) left += columns[i].getSize();\n\tlet width = 0;\n\tfor (let i = source.x; i < source.x + source.width && i < columns.length; i++) width += columns[i].getSize();\n\tconst right = left + width;\n\tconst bottom = (source.y + source.height) * ESTIMATED_ROW_HEIGHT;\n\treturn {\n\t\ttransform: `translate(${right - FILL_NUB_SIZE / 2}px, ${bottom - FILL_NUB_SIZE / 2}px)`,\n\t\twidth: FILL_NUB_SIZE,\n\t\theight: FILL_NUB_SIZE\n\t};\n}\n\n/**\n * Hit-test a client pointer position to a `[col, row]` cell index over the virtualized body.\n *\n * Converts to CONTENT space (add the scroll element's scroll offset, subtract its bounding-rect\n * origin), then: X walks the per-column widths from the leading `markerWidth` to find the column\n * whose band the pointer is over; Y subtracts the sticky `headerHeight` and floors by the uniform\n * `rowHeight`. Both axes CLAMP to `[0, count-1]` so a drag past the grid edge lands on the last\n * cell. PURE (takes the geometry, returns indices) — testable without a DOM.\n */\nexport function hitTestCell(\n\tclientX: number,\n\tclientY: number,\n\tgeom: {\n\t\trect: { left: number; top: number };\n\t\tscrollLeft: number;\n\t\tscrollTop: number;\n\t\tmarkerWidth: number;\n\t\theaderHeight: number;\n\t\trowHeight: number;\n\t\tcolWidths: readonly number[];\n\t\trowCount: number;\n\t},\n): [number, number] {\n\tconst { rect, scrollLeft, scrollTop, markerWidth, headerHeight, rowHeight, colWidths, rowCount } = geom;\n\t// Column: walk widths in content space from the marker offset.\n\tconst localX = clientX - rect.left + scrollLeft - markerWidth;\n\tlet col = 0;\n\tlet acc = 0;\n\tfor (let i = 0; i < colWidths.length; i++) {\n\t\tacc += colWidths[i];\n\t\tif (localX < acc) {\n\t\t\tcol = i;\n\t\t\tbreak;\n\t\t}\n\t\tcol = i;\n\t}\n\tcol = Math.max(0, Math.min(col, colWidths.length - 1));\n\t// Row: subtract the sticky header, floor by the uniform row height.\n\tconst localY = clientY - rect.top + scrollTop - headerHeight;\n\tlet row = Math.floor(localY / rowHeight);\n\trow = Math.max(0, Math.min(row, rowCount - 1));\n\treturn [col, row];\n}\n\n/** Index of the start-pinned column, else the first column (sticky-by-default). */\nfunction findStickyColumnIndex(columns: SheetsTableColumn[]): number {\n\tconst pinned = columns.findIndex((col) => col.getIsPinned() === 'start');\n\treturn pinned >= 0 ? pinned : columns.length > 0 ? 0 : -1;\n}\n\n/** Header label: shell meta title -> string header -> column id. `meta` is the empty v9 type, so read it loosely. */\nfunction columnTitle(column: SheetsTableColumn): string {\n\tconst meta = column.columnDef.meta as { title?: string } | undefined;\n\tif (meta?.title) return meta.title;\n\tconst header = column.columnDef.header;\n\tif (typeof header === 'string') return header;\n\treturn column.id;\n}\n\ninterface HeaderCellProps {\n\tcolumn: SheetsTableColumn;\n\theader: import('@tanstack/react-table').Header<SheetsTableFeatures, SheetsRow, unknown>;\n\tsorting: GridViewportSorting;\n\tonHeaderClick?: (colKey: string) => void;\n\tonResize?: (colKey: string, width: number) => void;\n}\n\n/** A single header cell: title + sort caret (click toggles) + right-edge resize handle. */\nfunction HeaderCell({ column, header, sorting, onHeaderClick, onResize }: HeaderCellProps) {\n\tconst isSorted = sorting.id === column.id;\n\tconst direction: 'asc' | 'desc' | 'none' = isSorted ? (sorting.desc ? 'desc' : 'asc') : 'none';\n\n\tfunction onResizePointerDown(e: React.PointerEvent<HTMLDivElement>) {\n\t\t// Don't toggle sort while grabbing the handle, and don't select header text.\n\t\te.preventDefault();\n\t\te.stopPropagation();\n\t\tif (onResize) {\n\t\t\tconst startX = e.clientX;\n\t\t\tconst startWidth = column.getSize();\n\t\t\tconst onMove = (move: PointerEvent) => onResize(column.id, Math.max(40, startWidth + (move.clientX - startX)));\n\t\t\tconst onUp = () => {\n\t\t\t\twindow.removeEventListener('pointermove', onMove);\n\t\t\t\twindow.removeEventListener('pointerup', onUp);\n\t\t\t};\n\t\t\twindow.addEventListener('pointermove', onMove);\n\t\t\twindow.addEventListener('pointerup', onUp);\n\t\t\treturn;\n\t\t}\n\t\t// Fall back to the v9 feature handler (columnResizeMode 'onChange').\n\t\theader.getResizeHandler()(e.nativeEvent);\n\t}\n\n\treturn (\n\t\t<div\n\t\t\trole='columnheader'\n\t\t\tdata-part-id='sheets-header-cell'\n\t\t\tdata-col-key={column.id}\n\t\t\taria-sort={direction === 'asc' ? 'ascending' : direction === 'desc' ? 'descending' : 'none'}\n\t\t\tonClick={() => onHeaderClick?.(column.id)}\n\t\t\tclassName={cn(\n\t\t\t\t'group relative flex h-full w-full select-none items-center gap-1 border-b border-border bg-background px-3 text-xs font-medium text-muted-foreground',\n\t\t\t\tonHeaderClick && 'cursor-pointer hover:bg-muted/50 hover:text-foreground'\n\t\t\t)}\n\t\t>\n\t\t\t<span className='truncate'>{columnTitle(column)}</span>\n\t\t\t<SortCaret direction={direction} />\n\t\t\t<div\n\t\t\t\trole='separator'\n\t\t\t\taria-orientation='vertical'\n\t\t\t\tdata-part-id='sheets-resize-handle'\n\t\t\t\tonClick={(e) => e.stopPropagation()}\n\t\t\t\tonPointerDown={onResizePointerDown}\n\t\t\t\tclassName='absolute right-0 top-0 h-full w-1 cursor-col-resize touch-none select-none bg-transparent hover:bg-primary/50'\n\t\t\t/>\n\t\t</div>\n\t);\n}\n\n/** Up/down/neutral sort caret (inline SVG, no icon-lib dep — matches the package's glyph style). */\nfunction SortCaret({ direction }: { direction: 'asc' | 'desc' | 'none' }) {\n\treturn (\n\t\t<svg\n\t\t\tdata-part-id='sheets-sort-caret'\n\t\t\tdata-direction={direction}\n\t\t\twidth='8'\n\t\t\theight='8'\n\t\t\tviewBox='0 0 8 8'\n\t\t\taria-hidden='true'\n\t\t\tclassName={cn('ml-auto shrink-0', direction === 'none' && 'opacity-30')}\n\t\t>\n\t\t\t{direction === 'desc' ? <path d='M0 2 L4 6 L8 2 Z' fill='currentColor' /> : <path d='M0 6 L4 2 L8 6 Z' fill='currentColor' />}\n\t\t</svg>\n\t);\n}\n\n/** Header marker cell: the select-all checkbox (checked = all, indeterminate = some). */\nfunction RowMarkerHeaderCell({ rowMarker }: { rowMarker: RowMarker }) {\n\treturn (\n\t\t<div\n\t\t\trole='columnheader'\n\t\t\tdata-part-id='sheets-row-marker-header'\n\t\t\tdata-slot='row-marker-header'\n\t\t\tclassName='flex h-full w-full select-none items-center justify-center border-b border-border bg-background'\n\t\t>\n\t\t\t<Checkbox\n\t\t\t\tchecked={rowMarker.allSelected}\n\t\t\t\tindeterminate={rowMarker.someSelected}\n\t\t\t\tonClick={() => rowMarker.onToggleAll()}\n\t\t\t\taria-label={rowMarker.allSelected ? 'Deselect all rows' : 'Select all rows'}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n\n/** Body marker cell per row: a checkbox reflecting selection; click (with shiftKey) drives the toggle. */\nfunction RowMarkerCell({ rowIndex, rowMarker }: { rowIndex: number; rowMarker: RowMarker }) {\n\tconst selected = rowMarker.isSelected(rowIndex);\n\t// Reveal-on-hover (DESIGN_SPEC §9): checkbox is hidden until the row is hovered, but stays\n\t// visible once this row is checked OR any selection is active (so multi-select stays legible).\n\tconst reveal = selected || rowMarker.someSelected || rowMarker.allSelected;\n\treturn (\n\t\t<div\n\t\t\tdata-part-id='sheets-row-marker-cell'\n\t\t\tdata-slot='row-marker-cell'\n\t\t\t// Stop the click from bubbling into the row (which would also start a cell edit).\n\t\t\tonClick={(e) => e.stopPropagation()}\n\t\t\tonDoubleClick={(e) => e.stopPropagation()}\n\t\t\tclassName={`flex h-full w-full select-none items-center justify-center bg-background ${PINNED_HOVER_BG}`}\n\t\t>\n\t\t\t<Checkbox\n\t\t\t\tchecked={selected}\n\t\t\t\t// base-ui Checkbox renders a <button>; onClick carries the native shiftKey for range-select.\n\t\t\t\tonClick={(e) => rowMarker.onToggleRow(rowIndex, e.shiftKey)}\n\t\t\t\taria-label={`Select row ${rowIndex}`}\n\t\t\t\tclassName={cn(!reveal && 'opacity-0 transition-opacity group-hover:opacity-100 motion-reduce:transition-none')}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n\nexport function GridViewport({\n\ttable,\n\trenderCell,\n\thandleRef,\n\tonScroll,\n\tsorting = { id: null, desc: false },\n\tonHeaderClick,\n\tonResize,\n\tcount,\n\tonVisibleRangeChange,\n\trowMarker,\n\tactiveCell,\n\tactiveRange,\n\tonGridKeyDown,\n\tonCopy,\n\tonCut,\n\tonPaste,\n\tactiveDescendantId,\n\tonFillDrag,\n\tclassName\n}: GridViewportProps) {\n\tconst scrollRef = useRef<HTMLDivElement>(null);\n\n\tconst rows = table.getRowModel().rows;\n\tconst columns = table.getAllLeafColumns();\n\n\t// Report the visible window WITHOUT an effect: the virtualizer's `onChange` fires on every\n\t// recompute (scroll/resize/measure) with the live instance, whose `.range` is the overscan-\n\t// inclusive {startIndex,endIndex}. Keep the ref current each render so the latch never goes stale.\n\tconst onVisibleRangeChangeRef = useRef(onVisibleRangeChange);\n\tonVisibleRangeChangeRef.current = onVisibleRangeChange;\n\n\tconst rowVirtualizer = useVirtualizer({\n\t\tcount: count ?? rows.length,\n\t\tgetScrollElement: () => scrollRef.current,\n\t\testimateSize: () => ESTIMATED_ROW_HEIGHT,\n\t\toverscan: ROW_OVERSCAN,\n\t\tonChange: (instance) => {\n\t\t\tconst range = instance.range;\n\t\t\tif (range) onVisibleRangeChangeRef.current?.({ startIndex: range.startIndex, endIndex: range.endIndex });\n\t\t}\n\t});\n\n\tconst columnVirtualizer = useVirtualizer({\n\t\thorizontal: true,\n\t\tcount: columns.length,\n\t\tgetScrollElement: () => scrollRef.current,\n\t\testimateSize: (index) => columns[index].getSize(),\n\t\tgetItemKey: (index) => columns[index]?.id ?? index,\n\t\toverscan: COLUMN_OVERSCAN\n\t});\n\n\tuseImperativeHandle(\n\t\thandleRef,\n\t\t() => ({\n\t\t\tscrollToIndex: (rowIndex: number) => rowVirtualizer.scrollToIndex(rowIndex),\n\t\t\tscrollToCell: (columnIndex: number, rowIndex: number) => {\n\t\t\t\trowVirtualizer.scrollToIndex(rowIndex);\n\t\t\t\tcolumnVirtualizer.scrollToIndex(columnIndex);\n\t\t\t}\n\t\t}),\n\t\t[rowVirtualizer, columnVirtualizer]\n\t);\n\n\tconst stickyIndex = findStickyColumnIndex(columns);\n\tconst hasStickyColumn = stickyIndex >= 0;\n\tconst stickyColumn = hasStickyColumn ? columns[stickyIndex] : undefined;\n\tconst stickyWidth = stickyColumn ? stickyColumn.getSize() : 0;\n\tconst stickyHeader = stickyColumn ? table.getLeafHeaders().find((h) => h.column.id === stickyColumn.id) : undefined;\n\tconst headersByColumnId = useMemo(() => new Map(table.getLeafHeaders().map((h) => [h.column.id, h])), [table, columns]);\n\n\tconst totalWidth = columnVirtualizer.getTotalSize();\n\tconst virtualColumns = columnVirtualizer.getVirtualItems();\n\n\t// The optional leading marker column shifts EVERYTHING right by MARKER_WIDTH: the sticky col0\n\t// pins at `left: markerWidth` (the marker owns `left: 0`), virtualized columns translate by an\n\t// extra markerWidth, and the header/body content width grows by markerWidth. When no rowMarker\n\t// is supplied, markerWidth is 0 and the layout is byte-identical to before.\n\tconst markerWidth = rowMarker ? MARKER_WIDTH : 0;\n\tconst contentWidth = totalWidth + markerWidth;\n\n\t// Fill-handle SOURCE rect: the active range, else a 1×1 rect at the active cell. Drives the nub\n\t// position (its bottom-right corner) and is the `from` handed to onFillDrag. Absent when neither.\n\tconst fillSource: SelectionRect | undefined = onFillDrag\n\t\t? activeRange ?? (activeCell ? { x: activeCell[0], y: activeCell[1], width: 1, height: 1 } : undefined)\n\t\t: undefined;\n\n\tfunction onFillNubPointerDown(e: React.PointerEvent<HTMLDivElement>) {\n\t\t// Don't start a cell selection / text-select while grabbing the nub.\n\t\te.preventDefault();\n\t\te.stopPropagation();\n\t\tif (!onFillDrag || !fillSource) return;\n\t\tconst source = fillSource;\n\t\tconst scrollEl = scrollRef.current;\n\t\tif (!scrollEl) return;\n\t\tconst colWidths = columns.map((c) => c.getSize());\n\t\tlet target: [number, number] = [source.x + source.width - 1, source.y + source.height - 1];\n\t\tconst onMove = (move: PointerEvent) => {\n\t\t\tconst rect = scrollEl.getBoundingClientRect();\n\t\t\ttarget = hitTestCell(move.clientX, move.clientY, {\n\t\t\t\trect: { left: rect.left, top: rect.top },\n\t\t\t\tscrollLeft: scrollEl.scrollLeft,\n\t\t\t\tscrollTop: scrollEl.scrollTop,\n\t\t\t\tmarkerWidth,\n\t\t\t\theaderHeight: HEADER_HEIGHT,\n\t\t\t\trowHeight: ESTIMATED_ROW_HEIGHT,\n\t\t\t\tcolWidths,\n\t\t\t\trowCount: count ?? rows.length\n\t\t\t});\n\t\t};\n\t\tconst onUp = () => {\n\t\t\twindow.removeEventListener('pointermove', onMove);\n\t\t\twindow.removeEventListener('pointerup', onUp);\n\t\t\tonFillDrag(source, target);\n\t\t};\n\t\twindow.addEventListener('pointermove', onMove);\n\t\twindow.addEventListener('pointerup', onUp);\n\t}\n\n\treturn (\n\t\t<div\n\t\t\tref={scrollRef}\n\t\t\tdata-impl='dom'\n\t\t\tdata-part-id='sheets-viewport'\n\t\t\trole='grid'\n\t\t\ttabIndex={0}\n\t\t\tonScroll={onScroll}\n\t\t\tonKeyDown={(e) => onGridKeyDown?.(e)}\n\t\t\tonCopy={onCopy}\n\t\t\tonCut={onCut}\n\t\t\tonPaste={onPaste}\n\t\t\taria-activedescendant={activeDescendantId}\n\t\t\taria-rowcount={count ?? rows.length}\n\t\t\taria-colcount={columns.length}\n\t\t\tclassName={cn('relative h-full w-full overflow-auto outline-none', className)}\n\t\t>\n\t\t\t{/* Sticky HEADER band — same column layout as the body. */}\n\t\t\t<div\n\t\t\t\trole='row'\n\t\t\t\tdata-part-id='sheets-header-row'\n\t\t\t\tclassName='sticky top-0 z-30 flex bg-background'\n\t\t\t\tstyle={{ height: HEADER_HEIGHT, width: contentWidth }}\n\t\t\t>\n\t\t\t\t{rowMarker && (\n\t\t\t\t\t<div className='sticky left-0 z-40 flex shrink-0' style={{ width: markerWidth, height: '100%' }}>\n\t\t\t\t\t\t<RowMarkerHeaderCell rowMarker={rowMarker} />\n\t\t\t\t\t</div>\n\t\t\t\t)}\n\t\t\t\t{stickyColumn && stickyHeader && (\n\t\t\t\t\t<div className='sticky z-40 flex shrink-0 border-r border-border' style={{ left: markerWidth, width: stickyWidth, height: '100%' }}>\n\t\t\t\t\t\t<HeaderCell\n\t\t\t\t\t\t\tcolumn={stickyColumn}\n\t\t\t\t\t\t\theader={stickyHeader}\n\t\t\t\t\t\t\tsorting={sorting}\n\t\t\t\t\t\t\tonHeaderClick={onHeaderClick}\n\t\t\t\t\t\t\tonResize={onResize}\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>\n\t\t\t\t)}\n\t\t\t\t{virtualColumns.map((virtualCol) => {\n\t\t\t\t\tif (virtualCol.index === stickyIndex) return null; // sticky header painted above\n\t\t\t\t\tconst column = columns[virtualCol.index];\n\t\t\t\t\tconst header = headersByColumnId.get(column.id);\n\t\t\t\t\tif (!header) return null;\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tkey={virtualCol.key}\n\t\t\t\t\t\t\tclassName='absolute top-0 flex'\n\t\t\t\t\t\t\tstyle={{ transform: `translateX(${virtualCol.start + markerWidth}px)`, width: virtualCol.size, height: '100%' }}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<HeaderCell\n\t\t\t\t\t\t\t\tcolumn={column}\n\t\t\t\t\t\t\t\theader={header}\n\t\t\t\t\t\t\t\tsorting={sorting}\n\t\t\t\t\t\t\t\tonHeaderClick={onHeaderClick}\n\t\t\t\t\t\t\t\tonResize={onResize}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t);\n\t\t\t\t})}\n\t\t\t</div>\n\n\t\t\t{/* BODY — virtualized rows × columns. */}\n\t\t\t<div style={{ height: rowVirtualizer.getTotalSize(), width: contentWidth, position: 'relative' }}>\n\t\t\t\t{rowVirtualizer.getVirtualItems().map((virtualRow) => {\n\t\t\t\t\tconst row = rows[virtualRow.index];\n\t\t\t\t\t// Defensive: when `count` (server total) leads the loaded `rows` window, the proxy\n\t\t\t\t\t// should still back every index — but guard the off-by-one race rather than crash.\n\t\t\t\t\tif (!row) return null;\n\t\t\t\t\tconst rowSelected = rowMarker?.isSelected(virtualRow.index) ?? false;\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tkey={virtualRow.key}\n\t\t\t\t\t\t\trole='row'\n\t\t\t\t\t\t\tdata-index={virtualRow.index}\n\t\t\t\t\t\t\tdata-row={virtualRow.index}\n\t\t\t\t\t\t\tdata-selected={rowSelected || undefined}\n\t\t\t\t\t\t\taria-rowindex={virtualRow.index + 1}\n\t\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t'group absolute left-0 top-0 flex border-b border-border',\n\t\t\t\t\t\t\trowSelected ? 'bg-primary/5' : 'hover:bg-muted/50'\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t\tstyle={{ transform: `translateY(${virtualRow.start}px)`, height: ESTIMATED_ROW_HEIGHT, width: '100%' }}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{rowMarker && (\n\t\t\t\t\t\t\t\t<div className='sticky left-0 z-20 flex shrink-0' style={{ width: markerWidth }}>\n\t\t\t\t\t\t\t\t\t<RowMarkerCell rowIndex={virtualRow.index} rowMarker={rowMarker} />\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t{hasStickyColumn && (\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclassName={`sticky z-10 flex shrink-0 border-r border-border bg-background ${PINNED_HOVER_BG}`}\n\t\t\t\t\t\t\t\t\tdata-col={stickyIndex}\n\t\t\t\t\t\t\t\t\taria-colindex={stickyIndex + 1}\n\t\t\t\t\t\t\t\t\tstyle={{ left: markerWidth, width: stickyWidth }}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{renderCell(cellForColumnIndex(row, stickyIndex), {\n\t\t\t\t\t\t\t\t\t\trowIndex: virtualRow.index,\n\t\t\t\t\t\t\t\t\t\tcolumnIndex: stickyIndex,\n\t\t\t\t\t\t\t\t\t\tisStickyColumn: true,\n\t\t\t\t\t\t\t\t\t\tisActive: activeCell?.[0] === stickyIndex && activeCell?.[1] === virtualRow.index\n\t\t\t\t\t\t\t\t\t})}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t{virtualColumns.map((virtualCol) => {\n\t\t\t\t\t\t\t\tif (virtualCol.index === stickyIndex) return null; // sticky col painted by the element above\n\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\tkey={virtualCol.key}\n\t\t\t\t\t\t\t\t\t\tclassName='absolute top-0 flex'\n\t\t\t\t\t\t\t\t\t\tdata-col={virtualCol.index}\n\t\t\t\t\t\t\t\t\t\taria-colindex={virtualCol.index + 1}\n\t\t\t\t\t\t\t\t\t\tstyle={{ transform: `translateX(${virtualCol.start + markerWidth}px)`, width: virtualCol.size, height: '100%' }}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{renderCell(cellForColumnIndex(row, virtualCol.index), {\n\t\t\t\t\t\t\t\t\t\t\trowIndex: virtualRow.index,\n\t\t\t\t\t\t\t\t\t\t\tcolumnIndex: virtualCol.index,\n\t\t\t\t\t\t\t\t\t\t\tisStickyColumn: false,\n\t\t\t\t\t\t\t\t\t\t\tisActive: activeCell?.[0] === virtualCol.index && activeCell?.[1] === virtualRow.index\n\t\t\t\t\t\t\t\t\t\t})}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t})}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t);\n\t\t\t\t})}\n\t\t\t\t{activeRange && (\n\t\t\t\t\t<div\n\t\t\t\t\t\tdata-part-id='sheets-range-band'\n\t\t\t\t\t\taria-hidden='true'\n\t\t\t\t\t\tclassName='pointer-events-none absolute z-[5] border border-primary/50 bg-primary/10'\n\t\t\t\t\t\tstyle={rangeBandStyle(activeRange, columns, markerWidth)}\n\t\t\t\t\t/>\n\t\t\t\t)}\n\t\t\t\t{fillSource && (\n\t\t\t\t\t<div\n\t\t\t\t\t\tdata-part-id='sheets-fill-handle'\n\t\t\t\t\t\trole='button'\n\t\t\t\t\t\taria-label='Fill handle'\n\t\t\t\t\t\tonPointerDown={onFillNubPointerDown}\n\t\t\t\t\t\tclassName='absolute z-10 cursor-crosshair touch-none select-none rounded-[1px] border border-background bg-primary'\n\t\t\t\t\t\tstyle={fillNubStyle(fillSource, columns, markerWidth)}\n\t\t\t\t\t/>\n\t\t\t\t)}\n\t\t\t</div>\n\t\t</div>\n\t);\n}\n","// The DOM cell host — the `getCellContent` → React port. Given a v9 cell it asks\n// the injected resolver for the {@link SheetsCellResolution} ({ cell, component? })\n// and renders the consumer component when present, else dispatches on the neutral\n// `kind` to the matching built-in view (cell-model/views/*).\n//\n// Phase 3 replaces the Phase-1 value→kind STOPGAP (`deriveSheetsCell`) with\n// registry-driven resolution: the host no longer guesses a kind from the JS value\n// — `getSheetsCellContent(rowIndex, colKey)` runs the full `createCellContent` →\n// `toSheetsCell` routing and (when the consumer registered a `cellComponent` for\n// the resolved typeKey) hands back the component to render instead of a built-in\n// view. SheetsDomInner injects the resolver via the `renderCell` closure.\n//\n// The kind→view map covers every native SheetsCellKind. datetime/interval cells\n// carry kind 'text' (formatted text in v1), so they route through TextCellView\n// alongside the grid-internal kinds (loading/draft-action/custom); their dedicated\n// DateTimeCellView/IntervalCellView stay exported for per-typeKey use later.\n// Dependency-light: local `cn` only, with no shared primitive dependency.\nimport { memo, useCallback, useRef } from 'react';\nimport type React from 'react';\nimport type { Cell } from '@tanstack/react-table';\n\nimport { cn } from '../utils/cn';\nimport { getDraftMeta, type SheetsRow } from '../grid/row-model';\nimport { DRAFT_ACTION_COLUMN_KEY } from '../grid/sheets.constants';\nimport type { SheetsTableFeatures } from '../table/features';\nimport type { RenderCellContext } from '../table/grid-viewport';\nimport type { CellProps } from '../cell-model/cell-props';\nimport { BadgesCellView } from '../cell-model/views/badges-view';\nimport { BooleanCellView } from '../cell-model/views/boolean-view';\nimport { DraftActionCellView, type DraftActionStatus } from '../cell-model/views/draft-action-view';\nimport { GeometryCellView } from '../cell-model/views/geometry-view';\nimport { ImageCellView } from '../cell-model/views/image-view';\nimport { LoadingCellView } from '../cell-model/views/loading-view';\nimport { NumberCellView } from '../cell-model/views/number-view';\nimport { RelationCellView } from '../cell-model/views/relation-view';\nimport { TextCellView } from '../cell-model/views/text-view';\nimport { UriCellView } from '../cell-model/views/uri-view';\nimport { InlineCellEditor } from './inline-cell-editor';\nimport type { SheetsCellResolution } from './use-sheets-content';\n\ntype SheetsTableCell = Cell<SheetsTableFeatures, SheetsRow, unknown>;\n\n/** Native DOM content resolver injected by the shell — mirrors `getCellContent`. */\nexport type GetSheetsCellContent = (rowIndex: number, colKey: string) => SheetsCellResolution;\n\n/**\n * Open the native overlay editor for a cell. Threaded from `SheetsDomInner` through\n * `renderCell` so only the host knows the cell's DOM node (it measures the anchor\n * rect off `getBoundingClientRect`). Phase-4 additive — the canvas path is untouched.\n */\nexport type OpenEditor = (rowIndex: number, colKey: string, anchorRect: DOMRect, initialText?: string) => void;\n\n/**\n * Submit a client-side draft row by its draft id. Threaded from `SheetsDomInner` (the\n * shell's `submitDraftRow`) so the draft-action cell's REAL `<Button>` can wire its\n * onClick. Phase-7 Stage-4 consumes it; Stage-2 only plumbs it through.\n */\nexport type SubmitDraftRow = (draftRowId: string) => Promise<unknown>;\n\n// COMPLETE kind→view map. `loading` routes to its skeleton view; `draft-action` is\n// special-cased UPSTREAM (rendered as DraftActionCellView with explicit props, never\n// reaching here), so it — like `custom`/`text` — falls back to TextCellView if it ever does.\nfunction renderKindView(props: CellProps) {\n\tswitch (props.cell.kind) {\n\t\tcase 'number':\n\t\t\treturn <NumberCellView {...props} />;\n\t\tcase 'boolean':\n\t\t\treturn <BooleanCellView {...props} />;\n\t\tcase 'badges':\n\t\t\treturn <BadgesCellView {...props} />;\n\t\tcase 'uri':\n\t\t\treturn <UriCellView {...props} />;\n\t\tcase 'image':\n\t\t\treturn <ImageCellView {...props} />;\n\t\tcase 'geometry':\n\t\t\treturn <GeometryCellView {...props} />;\n\t\tcase 'relation':\n\t\t\treturn <RelationCellView {...props} />;\n\t\tcase 'loading':\n\t\t\treturn <LoadingCellView {...props} />;\n\t\tcase 'text':\n\t\tcase 'draft-action':\n\t\tcase 'custom':\n\t\tdefault:\n\t\t\treturn <TextCellView {...props} />;\n\t}\n}\n\n/** Explicit draft-action descriptor for a draft row, derived from its DraftMeta. */\ninterface DraftActionInfo {\n\tdraftRowId: string;\n\tstatus: DraftActionStatus;\n\terrored: boolean;\n\tdisabled: boolean;\n}\n\n/**\n * Derive the draft-action cell's props from a row's draft metadata — the DOM analogue\n * of the canvas draft-action-cell reading the draft slice. `errored`/`disabled` mirror\n * the canvas: an error status surfaces the red dot but keeps the button live (the canvas\n * painter never disabled on error); `saving` disables (DraftActionCellView also self-locks).\n */\nfunction deriveDraftActionInfo(row: SheetsRow | undefined): DraftActionInfo | null {\n\tconst meta = getDraftMeta(row);\n\tif (!meta) return null;\n\tconst status: DraftActionStatus = meta.status;\n\treturn { draftRowId: meta.draftRowId, status, errored: status === 'error', disabled: status === 'saving' };\n}\n\ninterface SheetsCellHostInnerProps {\n\tresolution: SheetsCellResolution;\n\trowId: string;\n\tcolKey: string;\n\trowIndex: number;\n\tcolumnIndex: number;\n\tvalue: unknown;\n\tisEditing: boolean;\n\t/** True when this is the active (keyboard cursor) cell — drives the focus ring + aria-selected + id. */\n\tisActive: boolean;\n\t/** Open the overlay editor for this cell; undefined on render paths without editing (e.g. tests). */\n\topenEditor?: OpenEditor;\n\t/** Type-to-edit seed for the inline editor (only meaningful when `isEditing`). */\n\tinlineInitialText?: string;\n\t/** Commit an inline (in-cell) edit. Set on the inline-edit render path; reuses the host's\n\t * value-commit pipeline (bulk-or-single). */\n\tonInlineCommit?: (rowIndex: number, colKey: string, value: unknown) => void;\n\t/** Cancel an inline (in-cell) edit — discards and closes. */\n\tonInlineCancel?: () => void;\n\t/** Park the active cell on this cell (click-to-activate). `shiftKey` extends the range from the\n\t * anchor instead of resetting it. Undefined on render paths without nav. */\n\tonActivateCell?: (col: number, row: number, shiftKey?: boolean) => void;\n\t/** Right-click this cell — opens the grid context menu anchored at the pointer. The grid first\n\t * activates the cell when it is outside the current selection, so the menu acts on it. */\n\tonContextMenu?: (col: number, row: number, clientX: number, clientY: number) => void;\n\t/** Submit a draft row by id — wired to the draft-action cell's Button (Stage 4). */\n\tonSubmitDraftRow?: SubmitDraftRow;\n\t/** Draft-action descriptor when this is the draft-action column of a draft row; null otherwise. */\n\tdraftAction?: DraftActionInfo | null;\n\tclassName?: string;\n}\n\n/** Build the full {@link CellProps} for a resolved cell. `onStartEdit` is supplied by the host. */\nfunction toCellProps(props: SheetsCellHostInnerProps, onStartEdit: () => void): CellProps {\n\tconst { cell } = props.resolution;\n\treturn {\n\t\tcell,\n\t\tvalue: props.value,\n\t\tcolKey: props.colKey,\n\t\trowId: props.rowId,\n\t\trowIndex: props.rowIndex,\n\t\tcolumn: { key: props.colKey, name: props.colKey, cellType: cell.meta?.cellType ?? 'unknown' },\n\t\tisEditing: props.isEditing,\n\t\tonStartEdit,\n\t\tdisabled: false,\n\t};\n}\n\n// Memoized on (rowId, colKey, value, isEditing, openEditor) — the DOM analogue of\n// glide's `updateCells`: only the changed cell re-renders, never the whole window.\n// The resolution is derived from the first four inputs, so they fully gate the\n// output; openEditor is added so the wrapper's handlers stay current.\nconst SheetsCellHostInner = memo(\n\tfunction SheetsCellHostInner(props: SheetsCellHostInnerProps) {\n\t\tconst wrapperRef = useRef<HTMLDivElement | null>(null);\n\n\t\t// Start editing anchored to THIS cell's DOM node — the host is the only place\n\t\t// that knows the cell's rect (read off getBoundingClientRect, viewport coords,\n\t\t// matching the OverlayManager's window.innerHeight assumption). No-op when the\n\t\t// cell is readonly or no openEditor was threaded in.\n\t\tconst startEdit = useCallback(() => {\n\t\t\tconst open = props.openEditor;\n\t\t\tconst el = wrapperRef.current;\n\t\t\tif (!open || !el || props.resolution.cell.readonly) return;\n\t\t\topen(props.rowIndex, props.colKey, el.getBoundingClientRect());\n\t\t}, [props.openEditor, props.rowIndex, props.colKey, props.resolution.cell.readonly]);\n\n\t\t// Click parks the active cell here (the grid root owns keys via aria-activedescendant).\n\t\t// A shift-click EXTENDS the cell range from the latched anchor instead of resetting it.\n\t\tconst onActivateCell = props.onActivateCell;\n\t\tconst columnIndex = props.columnIndex;\n\t\tconst cellRowIndex = props.rowIndex;\n\t\tconst activate = useCallback((e: React.MouseEvent) => {\n\t\t\tonActivateCell?.(columnIndex, cellRowIndex, e.shiftKey);\n\t\t}, [onActivateCell, columnIndex, cellRowIndex]);\n\n\t\t// Right-click: open the grid context menu at the pointer. preventDefault suppresses the\n\t\t// browser menu; the grid handler activates this cell first when it is outside the selection.\n\t\tconst onContextMenu = props.onContextMenu;\n\t\tconst contextMenu = useCallback((e: React.MouseEvent) => {\n\t\t\tif (!onContextMenu) return;\n\t\t\te.preventDefault();\n\t\t\tonContextMenu(columnIndex, cellRowIndex, e.clientX, e.clientY);\n\t\t}, [onContextMenu, columnIndex, cellRowIndex]);\n\n\t\tconst onSubmitDraftRow = props.onSubmitDraftRow;\n\t\tconst draftAction = props.draftAction;\n\t\tconst submitDraft = useCallback(() => {\n\t\t\tif (draftAction && onSubmitDraftRow) void onSubmitDraftRow(draftAction.draftRowId);\n\t\t}, [draftAction, onSubmitDraftRow]);\n\n\t\tconst cellProps = toCellProps(props, startEdit);\n\t\tconst Component = props.resolution.component;\n\t\tconst styleHint = props.resolution.cell.styleHint;\n\t\t// DOM equivalent of applyDraftDisabledStyle / applyDraftErrorStyle: a draft cell\n\t\t// fades (muted text + tinted bg); a per-cell error overrides with a red bg/text.\n\t\tconst draftClasses = cn(\n\t\t\tstyleHint?.draft && 'bg-muted/40 text-muted-foreground',\n\t\t\tstyleHint?.error && 'bg-destructive/10 text-destructive',\n\t\t);\n\t\t// The draft-action column renders the REAL <Button> (DraftActionCellView), which\n\t\t// takes its own prop shape — bypass the kind→view map and the value/editor wiring.\n\t\tconst isDraftActionCell = props.colKey === DRAFT_ACTION_COLUMN_KEY || props.resolution.cell.kind === 'draft-action';\n\t\t// Border wrapper carries the mouse activation handlers (click parks the active cell,\n\t\t// double-click opens the editor). Keys are owned by the grid root (aria-activedescendant\n\t\t// pattern), so the wrapper is NOT individually focusable. The gridcell role lives on the\n\t\t// built-in view (or the consumer component) inside, so the host adds no second role=\"gridcell\".\n\t\treturn (\n\t\t\t<div\n\t\t\t\tref={wrapperRef}\n\t\t\t\tid={`sheets-cell-${props.rowIndex}-${props.columnIndex}`}\n\t\t\t\taria-selected={props.isActive || undefined}\n\t\t\t\tonClick={activate}\n\t\t\t\tonDoubleClick={startEdit}\n\t\t\t\tonContextMenu={contextMenu}\n\t\t\t\tclassName={cn(\n\t\t\t\t\t'relative h-full w-full overflow-hidden outline-none',\n\t\t\t\t\tprops.isActive && 'z-20 ring-2 ring-inset ring-primary',\n\t\t\t\t\tdraftClasses,\n\t\t\t\t\tprops.className,\n\t\t\t\t)}\n\t\t\t>\n\t\t\t\t{isDraftActionCell ? (\n\t\t\t\t\tdraftAction ? (\n\t\t\t\t\t\t<DraftActionCellView\n\t\t\t\t\t\t\tstatus={draftAction.status}\n\t\t\t\t\t\t\terrored={draftAction.errored}\n\t\t\t\t\t\t\tdisabled={draftAction.disabled}\n\t\t\t\t\t\t\tonSubmit={submitDraft}\n\t\t\t\t\t\t/>\n\t\t\t\t\t) : null\n\t\t\t\t) : props.isEditing ? (\n\t\t\t\t\t// Inline (in-cell) edit for the simple text-representable types — a bare <input>\n\t\t\t\t\t// overlaying the view. `isEditing` is set true ONLY for inline-edit intents (the\n\t\t\t\t\t// shell short-circuits inline-toggle/overlay/none before here), so the cell kind is\n\t\t\t\t\t// always text or number → derive the numeric variant from it.\n\t\t\t\t\t<InlineCellEditor\n\t\t\t\t\t\tariaLabel={`Edit ${props.resolution.fieldMeta?.name ?? props.colKey}`}\n\t\t\t\t\t\tvalue={props.value}\n\t\t\t\t\t\tinitialText={props.inlineInitialText}\n\t\t\t\t\t\tnumeric={props.resolution.cell.kind === 'number'}\n\t\t\t\t\t\tonCommit={(next) => props.onInlineCommit?.(props.rowIndex, props.colKey, next)}\n\t\t\t\t\t\tonCancel={() => props.onInlineCancel?.()}\n\t\t\t\t\t/>\n\t\t\t\t) : Component ? (\n\t\t\t\t\t<Component {...cellProps} />\n\t\t\t\t) : (\n\t\t\t\t\trenderKindView(cellProps)\n\t\t\t\t)}\n\t\t\t</div>\n\t\t);\n\t},\n\t(prev, next) =>\n\t\tprev.rowId === next.rowId &&\n\t\tprev.colKey === next.colKey &&\n\t\tprev.value === next.value &&\n\t\tprev.isEditing === next.isEditing &&\n\t\t// initialText seeds the inline editor on open; it only differs for the editing cell.\n\t\tprev.inlineInitialText === next.inlineInitialText &&\n\t\tprev.onInlineCommit === next.onInlineCommit &&\n\t\tprev.onInlineCancel === next.onInlineCancel &&\n\t\t// isActive must gate the memo or the focus ring will not move between cells.\n\t\tprev.isActive === next.isActive &&\n\t\tprev.openEditor === next.openEditor &&\n\t\tprev.onActivateCell === next.onActivateCell &&\n\t\tprev.onContextMenu === next.onContextMenu &&\n\t\tprev.onSubmitDraftRow === next.onSubmitDraftRow &&\n\t\t// styleHint.draft/error and the draft-action status can flip while `value` is\n\t\t// unchanged (validation result arrives, save in flight), so gate on them too.\n\t\tprev.resolution.cell.styleHint?.draft === next.resolution.cell.styleHint?.draft &&\n\t\tprev.resolution.cell.styleHint?.error === next.resolution.cell.styleHint?.error &&\n\t\tsameDraftAction(prev.draftAction, next.draftAction)\n);\n\n/** Draft-action equality for the memo gate — status/errored/disabled drive the Button. */\nfunction sameDraftAction(a: DraftActionInfo | null | undefined, b: DraftActionInfo | null | undefined): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\treturn a.draftRowId === b.draftRowId && a.status === b.status && a.errored === b.errored && a.disabled === b.disabled;\n}\n\nexport interface SheetsCellHostProps {\n\tcell: SheetsTableCell;\n\tctx: RenderCellContext;\n\tgetSheetsCellContent: GetSheetsCellContent;\n\t/** Open the overlay editor for the activated cell (double-click; grid root owns Enter / F2). */\n\topenEditor?: OpenEditor;\n\t/** True when this cell is being edited IN PLACE (inline-edit intent); renders the bare <input>. */\n\tisEditing?: boolean;\n\t/** Type-to-edit seed for the inline editor (only meaningful when `isEditing`). */\n\tinlineInitialText?: string;\n\t/** Commit an inline (in-cell) edit — reuses the host value-commit pipeline. */\n\tonInlineCommit?: (rowIndex: number, colKey: string, value: unknown) => void;\n\t/** Cancel an inline (in-cell) edit. */\n\tonInlineCancel?: () => void;\n\t/** Park the active cell on click; `shiftKey` extends the cell range from the anchor. */\n\tonActivateCell?: (col: number, row: number, shiftKey?: boolean) => void;\n\t/** Right-click → open the grid context menu anchored at the pointer. */\n\tonContextMenu?: (col: number, row: number, clientX: number, clientY: number) => void;\n\t/** Submit a draft row by id — wired to the draft-action cell's Button (Stage 4). */\n\tonSubmitDraftRow?: SubmitDraftRow;\n\tclassName?: string;\n}\n\n/**\n * Render a v9 cell as DOM. Wire via the {@link GridViewport} `renderCell` closure,\n * which injects the shell's resolver: `(c, ctx) => <SheetsCellHost cell={c} ctx={ctx}\n * getSheetsCellContent={getSheetsCellContent} openEditor={openEditor} />`.\n */\nexport function SheetsCellHost({ cell, ctx, getSheetsCellContent, openEditor, isEditing, inlineInitialText, onInlineCommit, onInlineCancel, onActivateCell, onContextMenu, onSubmitDraftRow, className }: SheetsCellHostProps) {\n\tconst rowIndex = cell.row.index;\n\tconst colKey = cell.column.id;\n\tconst value = cell.getValue();\n\tconst resolution = getSheetsCellContent(rowIndex, colKey);\n\t// Only the draft-action column needs the row's draft status; for every other column\n\t// this is null and the inner skips the Button branch. `cell.row.original` carries the\n\t// Symbol-keyed DraftMeta (it's the live row ref, never spread away by the table).\n\tconst draftAction = colKey === DRAFT_ACTION_COLUMN_KEY ? deriveDraftActionInfo(cell.row.original) : null;\n\treturn (\n\t\t<SheetsCellHostInner\n\t\t\tresolution={resolution}\n\t\t\trowId={cell.row.id}\n\t\t\tcolKey={colKey}\n\t\t\trowIndex={rowIndex}\n\t\t\tcolumnIndex={ctx.columnIndex}\n\t\t\tvalue={value}\n\t\t\tisEditing={!!isEditing}\n\t\t\tinlineInitialText={inlineInitialText}\n\t\t\tonInlineCommit={onInlineCommit}\n\t\t\tonInlineCancel={onInlineCancel}\n\t\t\tisActive={ctx.isActive}\n\t\t\topenEditor={openEditor}\n\t\t\tonActivateCell={onActivateCell}\n\t\t\tonContextMenu={onContextMenu}\n\t\t\tonSubmitDraftRow={onSubmitDraftRow}\n\t\t\tdraftAction={draftAction}\n\t\t\tclassName={className}\n\t\t/>\n\t);\n}\n","// The badge / category color system (DESIGN_SPEC §7) — the signature element.\n//\n// Category pills render as a tinted chip: a soft same-hue background paired with\n// saturated same-hue text. The DEFAULT tone is `neutral`; color is OPT-IN. The\n// consumer assigns a tone per value via a `Record<string, BadgeTone>` overrides\n// map (exact value -> tone) or a `(value) => BadgeTone | undefined` resolver\n// (e.g. CRM grids letting users color their own categories). There is NO\n// automatic hashing — an unconfigured grid stays calm and on-brand, resolving\n// every value to `neutral`.\n//\n// `neutral` is the only tone built from semantic tokens (so it themes for free);\n// the 8-hue categorical palette below is intentional data-viz color and ships\n// explicit `dark:` pairs — the one sanctioned exception to the tokens-not-palette\n// law (§6).\n\nexport type BadgeTone = 'neutral' | 'blue' | 'green' | 'amber' | 'red' | 'purple' | 'pink' | 'teal';\n\nexport const BADGE_TONES: Record<BadgeTone, string> = {\n\tneutral: 'bg-muted text-muted-foreground',\n\tblue: 'bg-blue-50 text-blue-700 dark:bg-blue-500/15 dark:text-blue-300',\n\tgreen: 'bg-emerald-50 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300',\n\tamber: 'bg-amber-50 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300',\n\tred: 'bg-rose-50 text-rose-700 dark:bg-rose-500/15 dark:text-rose-300',\n\tpurple: 'bg-violet-50 text-violet-700 dark:bg-violet-500/15 dark:text-violet-300',\n\tpink: 'bg-pink-50 text-pink-700 dark:bg-pink-500/15 dark:text-pink-300',\n\tteal: 'bg-teal-50 text-teal-700 dark:bg-teal-500/15 dark:text-teal-300',\n};\n\n/**\n * Resolve a badge value to its tone. Resolution order (first hit wins):\n * 1. `overrides[value]` — exact value -> tone map.\n * 2. `resolver?.(value)` — programmatic resolver.\n * 3. `'neutral'` — the default; color is neutral-until-configured.\n *\n * No automatic hashing: an unmapped value is always `neutral`.\n */\nexport function resolveBadgeTone(\n\tvalue: string,\n\toverrides?: Record<string, BadgeTone>,\n\tresolver?: (v: string) => BadgeTone | undefined,\n): BadgeTone {\n\treturn overrides?.[value] ?? resolver?.(value) ?? 'neutral';\n}\n","// Default DOM view for the `badges` SheetsCell family — the native analogue of\n// v1's glide BubbleCell render. Dependency-light: plain JSX + Tailwind v4 + a\n// local `cn`, with no shared primitive dependency. Reads the string[] off\n// `props.cell.data` (the badges payload) and renders one tonal chip per item per\n// DESIGN_SPEC §7; an empty array renders an empty cell.\n//\n// Chips default to the `neutral` tone — the palette is wired for opt-in color\n// later (consumer-supplied tone map / resolver); an unconfigured grid stays calm.\n\nimport { BADGE_TONES, resolveBadgeTone } from '../badge-tones';\nimport { cn } from '../../utils/cn';\nimport type { CellProps } from '../cell-props';\n\nexport function BadgesCellView(props: CellProps) {\n\tconst items = Array.isArray(props.cell.data) ? (props.cell.data as string[]) : [];\n\n\treturn (\n\t\t<div\n\t\t\trole=\"gridcell\"\n\t\t\tdata-slot=\"badges-cell\"\n\t\t\tclassName={cn(\n\t\t\t\t'flex h-full w-full items-center gap-1 overflow-hidden px-3',\n\t\t\t\t// Single row in the fixed-height cell (no vertical cramming): pills that run\n\t\t\t\t// past the right edge fade out, signalling more items beyond the cut (DESIGN_SPEC §7).\n\t\t\t\t// The mask only bites when content actually reaches the right edge, so a short list\n\t\t\t\t// (nothing near the edge) shows no fade.\n\t\t\t\t'[mask-image:linear-gradient(to_right,black,black_calc(100%_-_1.5rem),transparent)]',\n\t\t\t)}\n\t\t>\n\t\t\t{items.map((item, index) => (\n\t\t\t\t<span\n\t\t\t\t\tkey={`${index}-${item}`}\n\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t'inline-flex shrink-0 items-center rounded-md px-2 py-0.5 text-xs font-medium',\n\t\t\t\t\t\tBADGE_TONES[resolveBadgeTone(item)],\n\t\t\t\t\t)}\n\t\t\t\t>\n\t\t\t\t\t{item}\n\t\t\t\t</span>\n\t\t\t))}\n\t\t</div>\n\t);\n}\n","// Default DOM view for the boolean family. A boolean column IS a checkbox column,\n// so it renders the design-system Checkbox as a\n// READ-ONLY status indicator: checked for true, unchecked for false, empty cell for\n// null/undefined. `pointer-events-none` keeps the existing double-click-to-toggle model\n// intact — clicks pass through to the host cell wrapper; the checkbox is display only.\n// Keyed off the boolean payload in `cell.data` (NOT displayData — the factory leaves\n// displayData '' for parity).\n\nimport { Checkbox } from '@constructive-io/ui/checkbox';\n\nimport type { CellProps } from '../cell-props';\n\nexport function BooleanCellView(props: CellProps) {\n\tconst value = props.cell.data;\n\tconst hasValue = value === true || value === false;\n\n\treturn (\n\t\t<div role=\"gridcell\" data-slot=\"boolean-cell\" className=\"flex h-full w-full items-center px-3\">\n\t\t\t{hasValue ? (\n\t\t\t\t<Checkbox checked={value === true} readOnly tabIndex={-1} className=\"pointer-events-none\" />\n\t\t\t) : null}\n\t\t</div>\n\t);\n}\n","// Native DOM view for the `draft-action` column — the REAL <Button> that replaces\n// the canvas fake-button painter (grid/custom-cells/draft-action-cell.tsx, which\n// snapshot-captured design-system button styles into a canvas paint via\n// captureButtonStyle/BUTTON_STYLE_CACHE). Mirrors that painter's states 1:1:\n// - idle -> outline button labelled \"Save\"\n// - saving -> disabled, spinner + \"Saving...\" (canvas drew an animated arc)\n// - errored -> red dot indicator top-right; the button stays interactive\n// (the canvas painter never disabled on `errored`)\n// The host special-cases this column and passes these explicit props instead of the\n// generic CellProps, so the view stays a dumb presenter and onClick -> onSubmit().\n\nimport { LoaderIcon } from 'lucide-react';\n\nimport { Button } from '@constructive-io/ui/button';\nimport { cn } from '../../utils/cn';\n\nexport type DraftActionStatus = 'idle' | 'saving' | 'error';\n\nexport interface DraftActionCellViewProps {\n\tstatus?: DraftActionStatus;\n\tdisabled?: boolean;\n\terrored?: boolean;\n\tonSubmit?: () => void;\n}\n\nconst SAVE_LABEL = 'Save';\nconst SAVING_LABEL = 'Saving...';\n\nexport function DraftActionCellView(props: DraftActionCellViewProps) {\n\tconst status = props.status ?? 'idle';\n\tconst isSaving = status === 'saving';\n\t// Saving locks the button so a real DOM click can't double-submit mid-flight;\n\t// the canvas relied on the shell to guard, the DOM disables outright.\n\tconst isDisabled = Boolean(props.disabled) || isSaving;\n\n\treturn (\n\t\t<div className=\"flex h-full w-full items-center justify-center px-2\">\n\t\t\t<Button\n\t\t\t\ttype=\"button\"\n\t\t\t\tvariant=\"outline\"\n\t\t\t\tsize=\"sm\"\n\t\t\t\tdisabled={isDisabled}\n\t\t\t\tonClick={props.onSubmit}\n\t\t\t\tdata-slot=\"draft-action-cell\"\n\t\t\t\tclassName=\"relative\"\n\t\t\t>\n\t\t\t\t{isSaving && <LoaderIcon className=\"animate-spin\" aria-hidden=\"true\" />}\n\t\t\t\t{isSaving ? SAVING_LABEL : SAVE_LABEL}\n\t\t\t\t{props.errored && (\n\t\t\t\t\t<span\n\t\t\t\t\t\tdata-slot=\"draft-action-error\"\n\t\t\t\t\t\trole=\"status\"\n\t\t\t\t\t\taria-label=\"Save failed\"\n\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t'absolute -top-1 -right-1 size-2 rounded-full bg-destructive',\n\t\t\t\t\t\t\t'ring-2 ring-background',\n\t\t\t\t\t\t)}\n\t\t\t\t\t/>\n\t\t\t\t)}\n\t\t\t</Button>\n\t\t</div>\n\t);\n}\n","// DOM view for geometry cells — the native analogue of the canvas geometry\n// painter (grid/custom-cells/geometry-cell.tsx). Instead of a plain monospace\n// preview it paints a geo ICON tinted by geometry category (point/line/polygon/\n// collection), plus an ABBREVIATED type label, mirroring the canvas `draw`.\n//\n// The geometry TYPE is derived without a leaflet/geojson dependency: prefer an\n// explicit hint (`cell.meta.geometryType`, or a `{ geometryType }` object set by a\n// `deriveGeometry` builder — v1 `createGeometryCell`), else sniff the GeoJSON\n// `\"type\":\"…\"` token out of the compact preview string the factory put in\n// `cell.data` / `cell.displayData`. Dependency-light: plain JSX + inline SVG +\n// Tailwind v4 + local `cn`, with no shared primitive dependency.\n\nimport type { CellProps } from '../cell-props';\nimport { cn } from '../../utils/cn';\n\ntype GeometryCategory = 'point' | 'line' | 'polygon' | 'collection' | 'invalid';\n\n// Canvical-cell category buckets keyed by GeoJSON type — mirrors geometry-cell.tsx\n// ICON_COLORS grouping (point/line/polygon families share a colour).\nconst TYPE_CATEGORY: Record<string, GeometryCategory> = {\n\tPoint: 'point',\n\tMultiPoint: 'point',\n\tLineString: 'line',\n\tMultiLineString: 'line',\n\tPolygon: 'polygon',\n\tMultiPolygon: 'polygon',\n\tGeometryCollection: 'collection',\n};\n\n// Tints mirror geometry-cell.tsx ICON_COLORS (blue/purple/green/amber, red for invalid).\nconst CATEGORY_COLOR: Record<GeometryCategory, string> = {\n\tpoint: '#3b82f6',\n\tline: '#8b5cf6',\n\tpolygon: '#10b981',\n\tcollection: '#f59e0b',\n\tinvalid: '#ef4444',\n};\n\n// Abbreviated labels — the narrowest candidate from geometry-cell.tsx TYPE_LABELS\n// (the DOM cell has no canvas measure loop, so pick the compact form up front).\nconst TYPE_LABEL: Record<string, string> = {\n\tPoint: 'Point',\n\tMultiPoint: 'MPt',\n\tLineString: 'Line',\n\tMultiLineString: 'MLine',\n\tPolygon: 'Poly',\n\tMultiPolygon: 'MPoly',\n\tGeometryCollection: 'GColl',\n};\n\nconst GEOJSON_TYPE_RE = /\"type\"\\s*:\\s*\"([A-Za-z]+)\"/;\n\n/** Read an explicit geometry type from the cell hint (meta or a derived data object). */\nfunction readHintedType(cell: CellProps['cell']): string | undefined {\n\tconst fromMeta = cell.meta?.geometryType;\n\tif (typeof fromMeta === 'string' && fromMeta) return fromMeta;\n\tconst data = cell.data;\n\tif (data && typeof data === 'object') {\n\t\tconst gt = (data as { geometryType?: unknown }).geometryType;\n\t\tif (typeof gt === 'string' && gt) return gt;\n\t}\n\treturn undefined;\n}\n\n/** Sniff the GeoJSON `type` token out of the compact preview string. */\nfunction sniffTypeFromText(cell: CellProps['cell']): string | undefined {\n\tconst source =\n\t\ttypeof cell.data === 'string' ? cell.data : typeof cell.displayData === 'string' ? cell.displayData : '';\n\treturn GEOJSON_TYPE_RE.exec(source)?.[1];\n}\n\n/** The single-line preview text the factory emitted (copy/display parity). */\nfunction readDisplayText(cell: CellProps['cell']): string {\n\tif (typeof cell.displayData === 'string' && cell.displayData) return cell.displayData;\n\tif (typeof cell.data === 'string') return cell.data;\n\treturn '';\n}\n\nfunction categorize(geometryType: string | undefined): GeometryCategory {\n\tif (!geometryType) return 'invalid';\n\treturn TYPE_CATEGORY[geometryType] ?? 'invalid';\n}\n\nfunction labelFor(geometryType: string | undefined, category: GeometryCategory): string {\n\tif (!geometryType) return 'Invalid';\n\treturn TYPE_LABEL[geometryType] ?? (category === 'invalid' ? 'Invalid' : geometryType);\n}\n\n// Inline SVG geo icons — one per category, tinted via `color`. A point is a map\n// pin; line/polygon/collection use a map glyph; invalid is a warning triangle.\nfunction GeometryIcon({ category, color }: { category: GeometryCategory; color: string }) {\n\tconst common = {\n\t\twidth: 14,\n\t\theight: 14,\n\t\tviewBox: '0 0 24 24',\n\t\tfill: 'none',\n\t\tstroke: color,\n\t\tstrokeWidth: 2,\n\t\tstrokeLinecap: 'round' as const,\n\t\tstrokeLinejoin: 'round' as const,\n\t\t'aria-hidden': true,\n\t\tclassName: 'shrink-0',\n\t};\n\tif (category === 'point') {\n\t\treturn (\n\t\t\t<svg {...common} data-geometry-icon=\"point\">\n\t\t\t\t<path d=\"M12 21s-6-5.686-6-10a6 6 0 1 1 12 0c0 4.314-6 10-6 10z\" />\n\t\t\t\t<circle cx=\"12\" cy=\"11\" r=\"2\" />\n\t\t\t</svg>\n\t\t);\n\t}\n\tif (category === 'invalid') {\n\t\treturn (\n\t\t\t<svg {...common} data-geometry-icon=\"invalid\">\n\t\t\t\t<path d=\"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z\" />\n\t\t\t\t<line x1=\"12\" y1=\"9\" x2=\"12\" y2=\"13\" />\n\t\t\t\t<line x1=\"12\" y1=\"17\" x2=\"12.01\" y2=\"17\" />\n\t\t\t</svg>\n\t\t);\n\t}\n\t// line / polygon / collection — a folded map glyph.\n\treturn (\n\t\t<svg {...common} data-geometry-icon={category}>\n\t\t\t<polygon points=\"1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6\" />\n\t\t\t<line x1=\"8\" y1=\"2\" x2=\"8\" y2=\"18\" />\n\t\t\t<line x1=\"16\" y1=\"6\" x2=\"16\" y2=\"22\" />\n\t\t</svg>\n\t);\n}\n\nexport function GeometryCellView(props: CellProps) {\n\tconst { cell } = props;\n\tconst text = readDisplayText(cell);\n\n\t// Empty cell — nothing to paint, matching the canvas `isEmpty` early-return.\n\tif (!text && !readHintedType(cell)) {\n\t\treturn <div data-slot=\"geometry-cell\" role=\"gridcell\" className=\"h-full w-full\" />;\n\t}\n\n\tconst geometryType = readHintedType(cell) ?? sniffTypeFromText(cell);\n\tconst category = categorize(geometryType);\n\tconst color = CATEGORY_COLOR[category];\n\tconst label = labelFor(geometryType, category);\n\n\treturn (\n\t\t<div\n\t\t\tdata-slot=\"geometry-cell\"\n\t\t\tdata-geometry-category={category}\n\t\t\trole=\"gridcell\"\n\t\t\ttitle={text}\n\t\t\tclassName={cn('flex h-full w-full items-center gap-1.5 overflow-hidden px-3')}\n\t\t>\n\t\t\t<GeometryIcon category={category} color={color} />\n\t\t\t<span className={cn('truncate text-xs font-medium', category === 'invalid' && 'text-foreground/60')}>\n\t\t\t\t{label}\n\t\t\t</span>\n\t\t</div>\n\t);\n}\n","// Default native DOM view for the `image` SheetsCell kind. Dependency-light: plain\n// JSX + Tailwind v4 + local `cn`, with no shared primitive dependency. Reads the URL\n// from the factory payload (`cell.data` is `[url]`).\n//\n// Mirrors the canvas painter (`grid/draw-image-cell.ts`): a uniform SQUARE\n// thumbnail with object-fit:cover (center-crop, NOT contain) and rounded corners,\n// inset by a small pad. A muted box sits UNDER the <img> so it shows through\n// while the image loads AND stands alone when the url is empty (the canvas drew\n// the same placeholder for both the loading and missing-url branches).\n//\n// Virtualization destroys off-screen rows, so the body <img> is recreated on every\n// scroll-back. We retain successfully-loaded URLs in a module LRU (`warmImage`) to\n// keep them warm in memory — a remounted <img> paints without a re-fetch. No\n// `loading=\"lazy\"` (it forces a fetch-after-mount on every remount).\n\nimport { FileIcon } from 'lucide-react';\n\nimport type { CellProps } from '../cell-props';\nimport { cn } from '../../utils/cn';\nimport { getImageMetadata } from '../../utils/file.utils';\nimport { warmImage } from '../image-cache';\n\nfunction readUrl(data: unknown): string {\n\tif (Array.isArray(data) && typeof data[0] === 'string') return data[0];\n\treturn '';\n}\n\n/** Last path segment of a url (sans query/hash), to label a file chip that has no filename. */\nfunction basename(url: string): string {\n\tconst path = url.split(/[?#]/)[0];\n\tconst seg = path.slice(path.lastIndexOf('/') + 1);\n\treturn seg || url;\n}\n\n/**\n * On a non-`image` media column (file/video/audio/upload), render a file chip UNLESS we KNOW\n * the value is an image (an `image/*` mime). Non-image mimes, unknown mimes and bare URL\n * strings all chip — mirroring the editor's stored-value preview so the grid never shows a\n * broken <img> for a document. The `image` column is unaffected (always a thumbnail).\n */\nfunction isNonImageFile(cellType: string, value: unknown): boolean {\n\tif (cellType === 'image' || value == null) return false;\n\tconst mime = getImageMetadata(value)?.mime;\n\treturn !(mime && mime !== 'unknown' && mime.startsWith('image/'));\n}\n\nexport function ImageCellView(props: CellProps) {\n\tconst url = readUrl(props.cell.data);\n\n\tif (url && isNonImageFile(props.column.cellType, props.value)) {\n\t\tconst meta = getImageMetadata(props.value);\n\t\tconst filename = meta?.filename && meta.filename !== 'Unknown' ? meta.filename : basename(url);\n\t\treturn (\n\t\t\t<div\n\t\t\t\tdata-slot=\"file-cell\"\n\t\t\t\trole=\"gridcell\"\n\t\t\t\tclassName={cn('flex h-full w-full items-center gap-1.5 overflow-hidden px-2')}\n\t\t\t>\n\t\t\t\t<FileIcon className=\"size-3.5 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n\t\t\t\t<span className=\"truncate text-sm\" title={filename}>\n\t\t\t\t\t{filename}\n\t\t\t\t</span>\n\t\t\t</div>\n\t\t);\n\t}\n\n\treturn (\n\t\t<div\n\t\t\tdata-slot=\"image-cell\"\n\t\t\trole=\"gridcell\"\n\t\t\tclassName={cn('flex h-full w-full items-center overflow-hidden p-1')}\n\t\t>\n\t\t\t<div className={cn('relative aspect-square h-full max-h-full overflow-hidden rounded-sm bg-muted')}>\n\t\t\t\t{url ? (\n\t\t\t\t\t<img\n\t\t\t\t\t\tsrc={url}\n\t\t\t\t\t\tdecoding=\"async\"\n\t\t\t\t\t\talt=\"\"\n\t\t\t\t\t\tonLoad={() => warmImage(url)}\n\t\t\t\t\t\tclassName={cn('absolute inset-0 h-full w-full rounded-sm object-cover')}\n\t\t\t\t\t/>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t</div>\n\t);\n}\n","// Bounded module-level LRU that RETAINS decoded images by URL so they stay warm in\n// the browser's in-memory cache across unmount/remount. In a virtualized grid the\n// body <img> is destroyed when its row scrolls off-screen; without a live reference\n// the decoded bitmap is dropped and a remounted <img src> refetches/repaints (flicker,\n// pop-in). Holding a decoded Image reference keeps the URL warm — a remounted <img>\n// paints from memory instead of refetching, even for no-cache/short-lived URLs.\n\nconst CAP = 256;\nconst cache = new Map<string, HTMLImageElement>(); // Map preserves insertion order → LRU.\n\nexport function warmImage(url: string): void {\n\tif (!url || typeof Image === 'undefined') return; // SSR / empty-url guard.\n\n\tif (cache.has(url)) {\n\t\t// Mark most-recently-used: re-insert moves it to the end of the iteration order.\n\t\tconst img = cache.get(url)!;\n\t\tcache.delete(url);\n\t\tcache.set(url, img);\n\t\treturn;\n\t}\n\n\tconst img = new Image();\n\timg.decoding = 'async';\n\timg.src = url;\n\tcache.set(url, img);\n\n\twhile (cache.size > CAP) {\n\t\t// Evict the oldest (front of insertion order).\n\t\tconst oldest = cache.keys().next().value;\n\t\tif (oldest === undefined) break;\n\t\tcache.delete(oldest);\n\t}\n}\n","// Default DOM view for the grid-internal `loading` SheetsCell kind — the cell an\n// infinite-scroll row shows while its page is still in flight (getRowAtIndex is\n// null, so there is no value to render). The native analogue of v1's canvas\n// loading skeleton: a subtle `animate-pulse` placeholder bar filling the cell.\n// Dependency-light: plain JSX + Tailwind v4 + local `cn`, with no shared primitive dependency.\n\nimport type { CellProps } from '../cell-props';\nimport { cn } from '../../utils/cn';\n\nexport function LoadingCellView(_props: CellProps) {\n\treturn (\n\t\t<div\n\t\t\trole=\"gridcell\"\n\t\t\tdata-slot=\"loading-cell\"\n\t\t\taria-busy=\"true\"\n\t\t\tclassName={cn('flex h-full w-full items-center px-3')}\n\t\t>\n\t\t\t<span\n\t\t\t\taria-hidden=\"true\"\n\t\t\t\tclassName={cn('h-3 w-3/5 max-w-full rounded-full bg-muted', 'animate-pulse')}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n","// Default DOM view for the number SheetsCell family. Dependency-light: plain JSX\n// + Tailwind v4 + a `data-slot` hook, with no shared primitive dependency. Numbers\n// render right-aligned with tabular figures so digits line up column-wise. Reads\n// the already-formatted string off `props.cell.displayData` (the factory put\n// String(numValue) | '' there); the view does no numeric formatting itself.\n\nimport type { CellProps } from '../cell-props';\nimport { cn } from '../../utils/cn';\n\nexport function NumberCellView(props: CellProps) {\n\tconst { cell } = props;\n\treturn (\n\t\t<div\n\t\t\trole=\"gridcell\"\n\t\t\tdata-slot=\"number-cell\"\n\t\t\tclassName={cn('flex h-full w-full items-center justify-end truncate px-3 text-right text-sm tabular-nums text-foreground')}\n\t\t>\n\t\t\t{cell.displayData}\n\t\t</div>\n\t);\n}\n","// Default DOM view for the `relation` SheetsCell family. Dependency-light: plain\n// JSX + Tailwind v4 + a local `cn`, with no shared primitive dependency. Reads the\n// render payload off `props.cell` (produced by relationSheetsCellFactory):\n// - list relation -> cell.data is string[] (chips, possibly a trailing \"+N\")\n// - single relation -> cell.data is a string label\n// The factory already truncated labels and computed overflow; the view only paints.\n//\n// PARITY (canvas grid/draw-relation-badge.ts): for a list relation, paint a leading\n// COUNT BADGE pill — the number of related items — before the chips, mirroring the\n// canvas `drawRelationBadge`. Item count matches the canvas `getRelationCount`: the\n// trailing \"+N\" overflow chip means count = (chips − 1) + N, otherwise chips.length.\n// The single-relation (string) path stays plain text.\n\nimport React from 'react';\n\nimport { cn } from '../../utils/cn';\nimport type { CellProps } from '../cell-props';\n\n// Mirrors canvas `getRelationCount` for the Bubble (list) branch: a trailing \"+N\"\n// element is an overflow indicator, so the true count is (visible chips) + N.\nfunction getListRelationCount(chips: unknown[]): number {\n\tconst last = chips[chips.length - 1];\n\tif (typeof last === 'string' && last.startsWith('+')) {\n\t\tconst overflow = parseInt(last.slice(1), 10);\n\t\tif (!isNaN(overflow)) return chips.length - 1 + overflow;\n\t}\n\treturn chips.length;\n}\n\nexport function RelationCellView(props: CellProps): React.JSX.Element {\n\tconst { cell } = props;\n\tconst isList = Array.isArray(cell.data);\n\n\tif (!isList) {\n\t\treturn (\n\t\t\t<div\n\t\t\t\tdata-slot=\"relation-cell\"\n\t\t\t\trole=\"gridcell\"\n\t\t\t\tclassName=\"flex h-full w-full items-center gap-1 overflow-hidden px-3 text-sm\"\n\t\t\t>\n\t\t\t\t<span className=\"truncate text-foreground\">{String(cell.data ?? '')}</span>\n\t\t\t</div>\n\t\t);\n\t}\n\n\tconst chips = cell.data as unknown[];\n\tconst count = getListRelationCount(chips);\n\n\treturn (\n\t\t<div\n\t\t\tdata-slot=\"relation-cell\"\n\t\t\trole=\"gridcell\"\n\t\t\tclassName=\"flex h-full w-full items-center gap-1 overflow-hidden px-3 text-sm\"\n\t\t>\n\t\t\t{count > 0 ? (\n\t\t\t\t<span\n\t\t\t\t\tdata-slot=\"relation-count-badge\"\n\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t'inline-flex shrink-0 items-center rounded-sm border border-border bg-muted',\n\t\t\t\t\t\t'px-1 text-[10px] font-medium text-muted-foreground tabular-nums',\n\t\t\t\t\t)}\n\t\t\t\t>\n\t\t\t\t\t{count}\n\t\t\t\t</span>\n\t\t\t) : null}\n\t\t\t{chips.map((chip, index) => (\n\t\t\t\t<span\n\t\t\t\t\tkey={index}\n\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t'inline-flex shrink-0 items-center rounded-md bg-muted px-1.5 py-0.5',\n\t\t\t\t\t\t'text-xs font-medium text-muted-foreground',\n\t\t\t\t\t)}\n\t\t\t\t>\n\t\t\t\t\t{String(chip)}\n\t\t\t\t</span>\n\t\t\t))}\n\t\t</div>\n\t);\n}\n","// Default DOM view for the text family (the fallback). v1 renders the value as\n// plain truncated text inside the canvas; the native analogue is a single\n// truncated span. Dependency-light: plain JSX + Tailwind v4 + local `cn`, no\n// shared primitive dependency. Reads the rendered string off the SheetsCell\n// payload (`cell.displayData`) so it stays in lockstep with the factory.\n\nimport type { CellProps } from '../cell-props';\nimport { cn } from '../../utils/cn';\n\nexport function TextCellView(props: CellProps) {\n\tconst text = props.cell.displayData;\n\n\treturn (\n\t\t<div\n\t\t\trole=\"gridcell\"\n\t\t\tdata-slot=\"text-cell\"\n\t\t\ttitle={text}\n\t\t\tclassName={cn('flex h-full w-full items-center truncate px-3 text-sm')}\n\t\t>\n\t\t\t<span className=\"truncate\">{text}</span>\n\t\t</div>\n\t);\n}\n","// Native DOM view for the URI family (url | email). Dependency-light: plain JSX\n// + Tailwind v4 + local `cn`. Reads the render payload off `props.cell`\n// (`data` -> href, `displayData` -> visible label). The view owns the click\n// (v1's UriCellFactory dropped its onClickUri side-effect): the anchor opens in\n// a new tab. Empty cells (`data === ''`) render inert text, not a dead link.\n\nimport type { CellProps } from '../cell-props';\nimport { cn } from '../../utils/cn';\n\nexport function UriCellView(props: CellProps) {\n\tconst { cell } = props;\n\tconst href = String(cell.data ?? '');\n\tconst label = cell.displayData;\n\tconst hasHref = href.length > 0;\n\n\treturn (\n\t\t<div role=\"gridcell\" data-slot=\"uri-cell\" className=\"flex h-full w-full min-w-0 items-center px-3 text-sm\">\n\t\t\t{hasHref ? (\n\t\t\t\t<a\n\t\t\t\t\thref={href}\n\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\trel=\"noreferrer\"\n\t\t\t\t\ttitle={label}\n\t\t\t\t\tclassName={cn('truncate text-info underline-offset-2 hover:underline', 'focus-visible:outline-hidden')}\n\t\t\t\t>\n\t\t\t\t\t{label}\n\t\t\t\t</a>\n\t\t\t) : (\n\t\t\t\t<span className=\"truncate text-muted-foreground\">{label}</span>\n\t\t\t)}\n\t\t</div>\n\t);\n}\n","'use client';\n\n// Inline (in-cell) editor — a bare single-line <input> rendered DIRECTLY inside the\n// cell for the SIMPLE text-representable types (text-like + number-like). The\n// non-overlay counterpart of the portal editors: there is no card, no Save button and\n// no React portal — the input fills the cell (`absolute inset-0`) and overlays the\n// cell view while editing. Routed here by `resolveEditIntent` → `{ mode: 'inline-edit' }`\n// (url/inet/json/date/relation/… keep their specialised overlay editors).\n//\n// COMMIT MODEL (mirrors the overlay text/number editors, minus the chrome):\n// • Enter / blur (click-away) → commit. Escape → cancel. A numeric field that does\n// not parse blocks Enter (stay editing) and discards on blur (never clobbers the\n// value with garbage) — same guard as the overlay NumberEditor.\n// • `doneRef` makes commit/cancel idempotent: the explicit path returns focus to the\n// grid root (so keyboard nav resumes), and the blur THAT focus shift triggers is\n// short-circuited so it never double-fires.\n// • Pointer events stopPropagation so selecting text with the mouse does not trip the\n// cell's click-to-activate / range-drag handlers on the host wrapper.\n\nimport { useLayoutEffect, useRef, useState } from 'react';\n\nimport { cn } from '../utils/cn';\n\ninterface InlineCellEditorProps {\n\t/** Accessible name derived from the owning column. */\n\tariaLabel: string;\n\t/** The cell's committed value — seeds the input unless `initialText` overrides (type-to-edit). */\n\tvalue: unknown;\n\t/** Type-to-edit seed (OVERWRITE): a printable char that opened the editor replaces the value. */\n\tinitialText?: string;\n\t/** Number-like cell — parse to a finite number (or null) on commit and right-align like the view. */\n\tnumeric?: boolean;\n\t/** Commit the next raw value (string, or number|null when numeric). */\n\tonCommit: (next: unknown) => void;\n\t/** Discard — Escape, or an unparseable numeric field on blur. */\n\tonCancel: () => void;\n}\n\n/** Seed the input text from the raw value (anything stringifiable), else ''. */\nfunction seedText(value: unknown): string {\n\tif (value === null || value === undefined) return '';\n\treturn String(value);\n}\n\n/** Parse numeric input: '' → null (a valid clear); else a finite number, or `ok:false` for garbage. */\nfunction parseNumeric(text: string): { ok: boolean; value: number | null } {\n\tconst trimmed = text.trim();\n\tif (trimmed === '') return { ok: true, value: null };\n\tconst n = Number(trimmed);\n\treturn Number.isFinite(n) ? { ok: true, value: n } : { ok: false, value: null };\n}\n\nexport function InlineCellEditor({ ariaLabel, value, initialText, numeric, onCommit, onCancel }: InlineCellEditorProps) {\n\tconst [text, setText] = useState(() => (initialText != null ? initialText : seedText(value)));\n\tconst inputRef = useRef<HTMLInputElement | null>(null);\n\t// The grid root (role=grid, tabIndex=0) — focus returns here on commit/cancel so arrow-key\n\t// nav resumes (the input unmounts and would otherwise drop focus to <body>). Captured once.\n\tconst gridRef = useRef<HTMLElement | null>(null);\n\t// Guards commit/cancel idempotency: set before the explicit focus-return so the resulting\n\t// blur skips its commit-on-blur (no double commit, no commit-after-Escape).\n\tconst doneRef = useRef(false);\n\n\tuseLayoutEffect(() => {\n\t\tconst el = inputRef.current;\n\t\tgridRef.current = (el?.closest('[role=\"grid\"]') as HTMLElement | null) ?? null;\n\t\t// Seeded from the cell value (Enter / F2 / double-click) → select all so the first keystroke\n\t\t// replaces. A type-to-edit seed already IS the replacement, so leave the caret at the end.\n\t\tif (el && initialText == null) el.select();\n\t}, [initialText]);\n\n\tfunction finish(commit: boolean) {\n\t\tif (doneRef.current) return;\n\t\tdoneRef.current = true;\n\t\t// Return focus to the grid BEFORE the input unmounts; doneRef makes the blur a no-op.\n\t\tgridRef.current?.focus();\n\t\tif (!commit) {\n\t\t\tonCancel();\n\t\t\treturn;\n\t\t}\n\t\tif (numeric) {\n\t\t\tconst parsed = parseNumeric(text);\n\t\t\tif (!parsed.ok) {\n\t\t\t\tonCancel(); // unparseable on commit-by-blur → discard rather than clobber\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tonCommit(parsed.value);\n\t\t\treturn;\n\t\t}\n\t\tonCommit(text);\n\t}\n\n\tfunction handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {\n\t\tif (e.key === 'Enter') {\n\t\t\te.preventDefault();\n\t\t\t// Unparseable number on Enter → stay editing (mirror the overlay editor's Enter no-op).\n\t\t\tif (numeric && !parseNumeric(text).ok) return;\n\t\t\tfinish(true);\n\t\t\treturn;\n\t\t}\n\t\tif (e.key === 'Escape') {\n\t\t\te.preventDefault();\n\t\t\tfinish(false);\n\t\t}\n\t\t// Other keys (incl. arrows / Home / End) act on the input text. They bubble to the grid\n\t\t// root, which ignores keys while an editor is active, so they never move the grid cursor.\n\t}\n\n\treturn (\n\t\t<input\n\t\t\taria-label={ariaLabel}\n\t\t\tref={inputRef}\n\t\t\tvalue={text}\n\t\t\tonChange={(e) => setText(e.target.value)}\n\t\t\tonKeyDown={handleKeyDown}\n\t\t\tonBlur={() => finish(true)}\n\t\t\tonPointerDown={(e) => e.stopPropagation()}\n\t\t\tonClick={(e) => e.stopPropagation()}\n\t\t\tonDoubleClick={(e) => e.stopPropagation()}\n\t\t\tinputMode={numeric ? 'decimal' : undefined}\n\t\t\tspellCheck={false}\n\t\t\tdata-slot='inline-cell-editor'\n\t\t\tclassName={cn(\n\t\t\t\t'bg-background ring-primary absolute inset-0 h-full w-full px-3 font-sans text-sm outline-none ring-2 ring-inset',\n\t\t\t\tnumeric && 'text-right tabular-nums',\n\t\t\t)}\n\t\t\tautoFocus\n\t\t/>\n\t);\n}\n","// Native overlay open/close state machine. The Phase-4 analogue of glide's\n// imperative editor activation, but as a tiny React hook with NO heavy effects:\n// `open(cell)` records the active cell (rect captured by the caller from the cell\n// DOM node), `close()` clears it. `handleKeyDown` is a host-attachable helper —\n// Enter/F2 open (the caller supplies the cell to open, since only the host knows\n// which DOM node is focused), Escape closes.\n//\n// TODO(Phase 7): Tab should commit-and-open-next; today Tab is left to default.\n\nimport { useCallback, useState } from 'react';\n\nexport interface OverlayCell {\n\trowIndex: number;\n\tcolKey: string;\n\tanchorRect: DOMRect;\n\t/** Type-to-edit seed: when set, value editors initialize the input to this char (overwrite). */\n\tinitialText?: string;\n\t/**\n\t * Edit surface for this active cell. `'overlay'` (default when omitted) renders the portal\n\t * editor; `'inline'` edits IN PLACE inside the cell (no portal — the cell host renders the\n\t * input) yet still rides this controller so nav/clipboard suppression + scroll commit-on-unmount\n\t * are shared. The portal (`OverlayManager` / `editorNode`) is skipped for `'inline'`.\n\t */\n\tmode?: 'overlay' | 'inline';\n}\n\nexport interface OverlayController {\n\tactive: OverlayCell | null;\n\tisOpen: boolean;\n\topen: (cell: OverlayCell) => void;\n\tclose: () => void;\n\t/**\n\t * Re-anchor the open overlay to a freshly-measured rect WITHOUT changing the active\n\t * cell — the editor-follows-cell-on-scroll path (Stage B). No-op when closed. Keeps\n\t * the same {@link OverlayCell} identity for every field except `anchorRect`, so the\n\t * editor's local state (in-progress value, focus) survives the reposition.\n\t */\n\treanchor: (anchorRect: DOMRect) => void;\n\t/**\n\t * Host key handler. Enter/F2 open the cell returned by `resolveCell` (the host\n\t * resolves the focused cell + measures its rect); Escape closes. `resolveCell`\n\t * may return null (nothing focused / not editable) — then the open is skipped.\n\t */\n\thandleKeyDown: (e: React.KeyboardEvent, resolveCell: () => OverlayCell | null) => void;\n}\n\nexport function useOverlayController(): OverlayController {\n\tconst [active, setActive] = useState<OverlayCell | null>(null);\n\n\tconst open = useCallback((cell: OverlayCell) => {\n\t\tsetActive(cell);\n\t}, []);\n\n\tconst close = useCallback(() => {\n\t\tsetActive(null);\n\t}, []);\n\n\tconst reanchor = useCallback((anchorRect: DOMRect) => {\n\t\tsetActive((prev) => (prev ? { ...prev, anchorRect } : prev));\n\t}, []);\n\n\tconst handleKeyDown = useCallback(\n\t\t(e: React.KeyboardEvent, resolveCell: () => OverlayCell | null) => {\n\t\t\tif (e.key === 'Enter' || e.key === 'F2') {\n\t\t\t\tconst cell = resolveCell();\n\t\t\t\tif (!cell) return;\n\t\t\t\te.preventDefault();\n\t\t\t\tsetActive(cell);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (e.key === 'Escape') {\n\t\t\t\te.preventDefault();\n\t\t\t\tsetActive(null);\n\t\t\t}\n\t\t\t// TODO(Phase 7): Tab -> commit current + open next cell.\n\t\t},\n\t\t[],\n\t);\n\n\treturn { active, isOpen: active != null, open, close, reanchor, handleKeyDown };\n}\n","'use client';\n\n// Native (DOM React-portal) overlay container — the Phase-4 analogue of glide's\n// `#portal` fixed host, but it anchors off the cell DOM node's measured rect and\n// portals straight into `document.body` (viewport coords, matching the\n// `window.innerHeight` assumption in `computeOverlayGeometry`). It REUSES the pure\n// flip math + `EditorFocusTrap` + `EditorErrorGuard` + overlay-preset width class.\n// It NEVER mutates `.gdg-clip-region` — that DOM coupling stays in the canvas\n// `OverlayViewportGuard` so the glide path is untouched.\n\nimport React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\n\nimport { computeOverlayGeometry, OverlayMeasureContext } from '../../grid/editors/overlay-viewport-guard';\nimport { EditorFocusTrap } from '../../grid/editors/editor-focus-trap';\nimport { EditorErrorGuard } from '../../grid/feedback/editor-error-boundary';\nimport { cn } from '../../utils/cn';\n\nconst MARGIN_PX = 12;\nconst MIN_BELOW_PX = 320;\n\n// Nested floating layers an editor MIGHT portal outside the overlay (Base UI / Radix\n// / Floating UI popover, select, menu, dialog, tooltip). A pointerdown inside one of\n// these must NOT dismiss the overlay. The current editors render their pickers inline\n// inside the overlay, so this is a forward-looking safety net.\nconst FLOATING_LAYER_SELECTOR =\n\t'[role=\"listbox\"],[role=\"menu\"],[role=\"dialog\"],[role=\"tooltip\"],[data-floating-ui-portal],[data-base-ui-positioner],[data-radix-popper-content-wrapper]';\n\ninterface OverlayManagerProps {\n\tanchorRect: DOMRect | null;\n\topen: boolean;\n\tpresetClass?: string;\n\tonCancel: () => void;\n\t/**\n\t * Outside-pointerdown policy (Stage B). `'cancel'` (default) dismisses with no write\n\t * — for editors that DON'T commit-on-blur (relation/date/json/url/inet/…). `'commit'`\n\t * — for the commit-on-blur value editors (text/number) — instead BLURS the focused\n\t * element inside the overlay so its `onBlur → onCommit` fires (commit-on-click-away),\n\t * rather than cancelling. The blur path then commits AND closes; the manager does NOT\n\t * also call onCancel, so there is exactly one dismiss per click-away.\n\t */\n\tdismissMode?: 'cancel' | 'commit';\n\tchildren: React.ReactNode;\n}\n\nexport function OverlayManager({ anchorRect, open, presetClass, onCancel, dismissMode = 'cancel', children }: OverlayManagerProps): React.ReactNode {\n\tconst containerRef = useRef<HTMLDivElement | null>(null);\n\t// Measured, viewport-clamped position (both axes). Null until the overlay has been\n\t// measured once, so first paint stays hidden rather than flashing at an unclamped\n\t// spot. Covers the FLIP (no room below -> open above) AND the horizontal shift (an\n\t// anchor near the right edge -> slide left so the overlay stays on-screen instead of\n\t// overflowing off the viewport, e.g. the last column's editor).\n\tconst [pos, setPos] = useState<{ left: number; top: number } | null>(null);\n\n\tconst targetY = anchorRect?.top;\n\tconst targetH = anchorRect?.height;\n\tconst vh = typeof window !== 'undefined' ? window.innerHeight : 800;\n\tconst { shouldFlip, maxHeight } = computeOverlayGeometry(vh, targetY, targetH, MARGIN_PX, MIN_BELOW_PX);\n\n\t// Geometry an editor needs to self-bound its internal scroll areas (the canvas path\n\t// supplied this via OverlayViewportGuard; the DOM host must too). WITHOUT it, editors\n\t// that read OverlayMeasureContext (relation/image/geometry) see the default maxHeight:0,\n\t// skip their scroll-budget effect, and render UNBOUNDED lists — so a relation editor's\n\t// infinite \"related records\" sentinel stays permanently in view and pages continuously.\n\tconst overlayMeasure = useMemo(() => ({ maxHeight, shouldFlip }), [maxHeight, shouldFlip]);\n\n\t// Measure the rendered overlay, then position it: vertically below the anchor (or\n\t// flipped above when there's no room), horizontally left-aligned to the anchor (or\n\t// shifted left to stay on-screen), clamped into the viewport on BOTH axes. DOM-read\n\t// only — mirrors the canvas guard's layout-effect measure; no hasMounted flag.\n\tuseLayoutEffect(() => {\n\t\tif (!open || !anchorRect) {\n\t\t\tsetPos(null);\n\t\t\treturn;\n\t\t}\n\t\tconst el = containerRef.current;\n\t\tif (!el) return;\n\t\tconst rect = el.getBoundingClientRect();\n\t\tconst vw = window.innerWidth;\n\t\tconst vhNow = window.innerHeight;\n\n\t\tlet left = anchorRect.left;\n\t\tleft = Math.max(MARGIN_PX, Math.min(left, vw - MARGIN_PX - rect.width));\n\t\tif (!Number.isFinite(left)) left = MARGIN_PX;\n\n\t\tlet top = shouldFlip ? anchorRect.top - rect.height : anchorRect.bottom;\n\t\ttop = Math.max(MARGIN_PX, Math.min(top, vhNow - MARGIN_PX - rect.height));\n\t\tif (!Number.isFinite(top)) top = MARGIN_PX;\n\n\t\tsetPos({ left, top });\n\t}, [open, shouldFlip, anchorRect, maxHeight]);\n\n\t// Dismiss on a pointerdown OUTSIDE the overlay — standard popover behaviour. The\n\t// overlay was previously only closable via Esc / commit / scroll, so a click in the\n\t// grid or page left it stuck open. Attached in an effect (after commit) so the\n\t// activating double-click that OPENED the overlay has fully settled and cannot\n\t// self-dismiss; capture phase so an inner editor that stops propagation can't\n\t// suppress it. Clicks inside the overlay (or a nested floating layer it portals)\n\t// are ignored.\n\tuseEffect(() => {\n\t\tif (!open) return;\n\t\tconst onPointerDown = (e: PointerEvent) => {\n\t\t\tconst el = containerRef.current;\n\t\t\tconst target = e.target as Node | null;\n\t\t\tif (!el || (target && el.contains(target))) return;\n\t\t\tif (target instanceof Element && target.closest(FLOATING_LAYER_SELECTOR)) return;\n\t\t\t// COMMIT-ON-CLICK-AWAY (Stage B): for commit-on-blur editors, move DOM focus out of\n\t\t\t// the overlay so the focused input's `onBlur → onCommit` fires (commit, then close).\n\t\t\t// We DON'T also call onCancel — the blur path closes the overlay, so this is exactly\n\t\t\t// one dismiss. A bare outside element may not be focusable (so a natural focus shift\n\t\t\t// wouldn't fire), hence we blur explicitly. Falls back to onCancel when nothing in the\n\t\t\t// overlay is focused. `'cancel'` editors discard as before.\n\t\t\tif (dismissMode === 'commit') {\n\t\t\t\tconst focused = document.activeElement;\n\t\t\t\tif (focused instanceof HTMLElement && el.contains(focused)) {\n\t\t\t\t\tfocused.blur();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tonCancel();\n\t\t};\n\t\tdocument.addEventListener('pointerdown', onPointerDown, true);\n\t\treturn () => document.removeEventListener('pointerdown', onPointerDown, true);\n\t}, [open, onCancel, dismissMode]);\n\n\tif (!open || !anchorRect || typeof document === 'undefined') return null;\n\n\t// Animate only once the measured, viewport-clamped position is applied, so the\n\t// entrance transform never fights the layout-effect measure.\n\tconst positioned = pos !== null;\n\tconst style: React.CSSProperties = {\n\t\tposition: 'fixed',\n\t\t// Pre-measure default = the ANCHOR position (below, or above when flipping), NOT a\n\t\t// screen corner. So an overlay that fits (the common case) renders at its FINAL spot\n\t\t// with zero left/top change once measured — no travel. It stays hidden until measured\n\t\t// and `transition-none` keeps the rare off-screen clamp instant, so the overlay is\n\t\t// never seen sliding to the anchor (the correction happens off-screen, pre-reveal).\n\t\tleft: pos ? pos.left : anchorRect.left,\n\t\ttop: pos ? pos.top : shouldFlip ? anchorRect.top : anchorRect.bottom,\n\t\tmaxHeight,\n\t\t// Hidden until measured to avoid a 1-frame flash at an unclamped position.\n\t\tvisibility: positioned ? 'visible' : 'hidden',\n\t\t// Join the shared design-system overlay layer instead of an\n\t\t// arbitrary z, so the editor and any popover/tooltip it opens (e.g. the relation\n\t\t// \"Record Data\" popover, which portals into #portal-root) stack coherently.\n\t\tzIndex: 'var(--z-layer-floating)',\n\t};\n\n\t// Portal into the app's shared floating-overlay host (#portal-root) so the editor and\n\t// nested UI popovers live in the SAME stacking context (siblings) — fixing the\n\t// host-dependent z-index race where the editor could paint OVER a popover opened from\n\t// within it. Fall back to <body> when no portal root is mounted (e.g. tests). The host\n\t// has pointer-events:none, so the overlay opts back in with pointer-events-auto.\n\tconst portalHost = document.getElementById('portal-root') ?? document.body;\n\n\treturn createPortal(\n\t\t<div\n\t\t\tref={containerRef}\n\t\t\tstyle={style}\n\t\t\tclassName={cn(\n\t\t\t\t// `transition-none`: the entrance is an ANIMATION (scale + fade); left/top must NEVER\n\t\t\t\t// transition, or measuring/clamping the position would visibly slide the overlay across\n\t\t\t\t// the screen to its anchor. This keeps the position application instant.\n\t\t\t\t'pointer-events-auto transition-none',\n\t\t\t\t// Origin-aware entrance (DESIGN_SPEC §10 / Emil standards): subtle scale + fade from the\n\t\t\t\t// cell corner, reusing the UI popover's tw-animate utilities for a consistent feel. Gated\n\t\t\t\t// on `positioned` so the overlay animates only after its measured position is applied.\n\t\t\t\tpositioned && 'animate-in fade-in-0 zoom-in-95 duration-150 ease-out motion-reduce:animate-none',\n\t\t\t\tshouldFlip ? 'origin-bottom-left' : 'origin-top-left'\n\t\t\t)}\n\t\t>\n\t\t\t{/* Provide the overlay geometry so editors (relation/image/geometry) can self-bound their\n\t\t\t internal scroll lists; without it they read maxHeight:0 and render unbounded (the\n\t\t\t relation infinite-scroll bug). Mirrors the canvas OverlayViewportGuard's provider. */}\n\t\t\t<OverlayMeasureContext.Provider value={overlayMeasure}>\n\t\t\t\t<EditorErrorGuard onClose={onCancel}>\n\t\t\t\t\t{/* overflow-VISIBLE, never auto/hidden: each editor renders its own rounded card with a\n\t\t\t\t\t `shadow-lg`, and a clipping wrapper the same size as the card squares off that shadow\n\t\t\t\t\t into the \"weird halo\" around the rounded corners. Editors self-bound their height\n\t\t\t\t\t (relation/image/json scroll internally), so the wrapper never needs to scroll. */}\n\t\t\t\t\t<EditorFocusTrap onEscape={onCancel} className={cn('overflow-visible', presetClass)}>\n\t\t\t\t\t\t{children}\n\t\t\t\t\t</EditorFocusTrap>\n\t\t\t\t</EditorErrorGuard>\n\t\t\t</OverlayMeasureContext.Provider>\n\t\t</div>,\n\t\tportalHost,\n\t);\n}\n","'use client';\n\nimport { Component, type ErrorInfo, type ReactNode } from 'react';\n\nimport { useSheetsContext } from '../../context/sheets-context';\nimport { sheetsLogger } from '../../utils/sheets-logger';\n\ntype SheetsOnError = (\n\terror: unknown,\n\tctx?: { source?: 'grid' | 'editor' | 'mutation' | 'upload'; tableName?: string },\n) => void;\n\ninterface EditorErrorBoundaryProps {\n\tchildren: ReactNode;\n\t/** Closes the overlay so the grid stays interactive after a failure. */\n\tonClose: () => void;\n\t/** Called when a render/chunk-load error is caught. Mirrors SheetsConfig.onError. */\n\tonError?: SheetsOnError;\n}\n\ninterface EditorErrorBoundaryState {\n\terror: unknown;\n}\n\n/**\n * Per-overlay-editor error boundary. Catches render throws AND React.lazy\n * chunk-load rejections inside a single overlay editor so they never reach the\n * grid-level SheetsErrorBoundary (which blanks the whole grid). It must wrap the\n * editor's own Suspense so lazy rejections surface here. Routes the error to the\n * host via onError and renders a tiny inline fallback with a Close button.\n */\nexport class EditorErrorBoundary extends Component<EditorErrorBoundaryProps, EditorErrorBoundaryState> {\n\tstate: EditorErrorBoundaryState = { error: null };\n\n\tstatic getDerivedStateFromError(error: unknown): EditorErrorBoundaryState {\n\t\treturn { error };\n\t}\n\n\tcomponentDidCatch(error: unknown, info: ErrorInfo): void {\n\t\tsheetsLogger().error('[sheets] editor render error', { error, componentStack: info.componentStack });\n\t\tthis.props.onError?.(error, { source: 'editor' });\n\t}\n\n\trender(): ReactNode {\n\t\tif (this.state.error == null) {\n\t\t\treturn this.props.children;\n\t\t}\n\t\treturn (\n\t\t\t<div className='bg-popover text-foreground flex flex-col gap-2 rounded-lg border p-3 text-sm shadow-lg'>\n\t\t\t\t<span className='text-muted-foreground'>Editor failed to load/render</span>\n\t\t\t\t<button\n\t\t\t\t\ttype='button'\n\t\t\t\t\tonClick={this.props.onClose}\n\t\t\t\t\tclassName='border-border/60 hover:bg-muted/60 self-end rounded-md border px-2.5 py-1 text-xs'\n\t\t\t\t>\n\t\t\t\t\tClose\n\t\t\t\t</button>\n\t\t\t</div>\n\t\t);\n\t}\n}\n\ninterface EditorErrorGuardProps {\n\t// Optional so `React.createElement(EditorErrorGuard, { onClose }, child)` type-checks;\n\t// children are forwarded positionally to the class boundary below.\n\tchildren?: ReactNode;\n\tonClose: () => void;\n}\n\n/**\n * Functional shim that sources `onError` from the sheets context. Overlay editors\n * render in Glide's portal but stay within the provider tree (same path the\n * relation/image editors use for `useSheetsContext`), so the host callback is\n * reachable here.\n */\nexport function EditorErrorGuard({ children, onClose }: EditorErrorGuardProps): ReactNode {\n\tconst { config } = useSheetsContext();\n\treturn (\n\t\t<EditorErrorBoundary onClose={onClose} onError={config.onError}>\n\t\t\t{children}\n\t\t</EditorErrorBoundary>\n\t);\n}\n","// The SINGLE edit-intent resolver — the host's one entry point for \"what happens\n// when this cell is activated?\". It replaces the host's brittle\n// `resolveNativeEditor(cell.meta?.cellType ?? 'text')` lookup (which mis-routed\n// EVERY non-text cell to TextEditor) with an AUTHORITATIVE, exhaustive mapping\n// from a `typeKey` (CellType) + the cell's readonly flag to exactly one of:\n// • { mode: 'inline-toggle' } — no overlay; the host commits `!currentBool`.\n// • { mode: 'inline-edit' } — no overlay; the host edits IN PLACE with a bare\n// single-line <input> (the SIMPLE text-representable\n// types: text-like + number-like). url/inet are NOT\n// here — they keep their specialised overlay editors.\n// • { mode: 'overlay', editor } — open the resolved native overlay editor.\n// • { mode: 'none' } — not editable (readonly / non-editable type).\n//\n// EXHAUSTIVENESS is structural: the buckets are DRIVEN OFF the canonical\n// cell-type-groups Sets (BOOLEAN_TYPES / NUMBER_TYPES / DATE_TIME_TYPES /\n// GEOMETRY_TYPES / MEDIA_TYPES / isArrayCellType / NON_EDITABLE_TYPES /\n// VIEWER_ONLY_TYPES), never a hand-maintained list — so adding a member to a\n// group automatically routes it here. Every CellType in cell-types/types.ts lands\n// in exactly one bucket; anything unrecognised falls through to the text default\n// (TextEditor), matching the `unknown` cell-type contract.\n//\n// CONSUMER OVERRIDE: a registered `def.editorComponent` for the typeKey (looked up\n// via the injected `consumer`, i.e. `registry.getEditorComponent`) WINS as the\n// overlay editor for any type that opens an overlay — same precedence the glide\n// path gave `def.editor`. It does NOT override inline-toggle or readonly `none`.\n\nimport type { ComponentType } from 'react';\n\nimport {\n\tBOOLEAN_TYPES,\n\tDATE_TIME_TYPES,\n\tGEOMETRY_TYPES,\n\tMEDIA_TYPES,\n\tNON_EDITABLE_TYPES,\n\tNUMBER_TYPES,\n\tVIEWER_ONLY_TYPES,\n\tisArrayCellType,\n} from '../../cell-types/cell-type-groups';\nimport { DOM_EDITOR_REGISTRY, type NativeEditor } from './editor-registry-dom';\nimport type { EditorProps } from './editor-props';\n\nexport type EditIntent =\n\t| { mode: 'overlay'; editor: NativeEditor }\n\t| { mode: 'inline-toggle' }\n\t| { mode: 'inline-edit' }\n\t| { mode: 'none' };\n\ntype EditorConsumer = (typeKey: string) => ComponentType<EditorProps> | undefined;\n\n/** Build the overlay intent for a typeKey: consumer override wins, else the registry entry. */\nfunction overlay(typeKey: string, consumer: EditorConsumer | undefined): EditIntent {\n\tconst editor = (consumer?.(typeKey) as NativeEditor | undefined) ?? DOM_EDITOR_REGISTRY[typeKey];\n\t// No editor resolved for a type that should open one — degrade to no-edit rather\n\t// than portal an empty overlay. (Cannot happen for the buckets below: every one\n\t// has a DOM_EDITOR_REGISTRY entry.)\n\treturn editor ? { mode: 'overlay', editor } : { mode: 'none' };\n}\n\n/**\n * Simple text-representable types (text-like + number-like) edit IN PLACE with a bare\n * <input> — no overlay. A registered consumer editor for the typeKey still WINS as an\n * overlay editor (same override precedence the overlay types give `def.editor`); only\n * the built-in path becomes inline. The host derives text-vs-number from the cell kind.\n */\nfunction inlineOrOverride(typeKey: string, consumer: EditorConsumer | undefined): EditIntent {\n\tconst editor = consumer?.(typeKey) as NativeEditor | undefined;\n\tif (editor) return { mode: 'overlay', editor };\n\treturn { mode: 'inline-edit' };\n}\n\n/**\n * Resolve the edit intent for a cell.\n *\n * @param typeKey - resolved CellType key (the `SheetsCellResolution.typeKey`).\n * @param opts - `readonly` mirrors the cell's readonly flag (READONLY_CONDITIONS / draft-id / relation-not-inline).\n * @param consumer - optional per-instance editor override (`registry.getEditorComponent`).\n */\nexport function resolveEditIntent(\n\ttypeKey: string,\n\topts: { readonly?: boolean },\n\tconsumer?: EditorConsumer,\n): EditIntent {\n\t// 1) Readonly cell — never editable, regardless of type (matches the host already\n\t// skipping `cell.readonly`). Also covers NON_EDITABLE types that are not viewers.\n\tif (opts.readonly) return { mode: 'none' };\n\n\t// 2) Non-editable types that are NOT viewer-only → no edit. (tsvector is in\n\t// NON_EDITABLE_TYPES but is viewer-only, so it falls through to its viewer\n\t// overlay below; this guard catches any future non-viewer non-editable type.)\n\tif (NON_EDITABLE_TYPES.has(typeKey) && !VIEWER_ONLY_TYPES.has(typeKey)) return { mode: 'none' };\n\n\t// 3) Booleans → inline toggle (no overlay; the host commits `!currentBool`).\n\tif (BOOLEAN_TYPES.has(typeKey)) return { mode: 'inline-toggle' };\n\n\t// 4) Number-like → inline edit (simple text-representable). Overlay families below stay\n\t// overlay, driven off the canonical groups so they stay exhaustive.\n\tif (NUMBER_TYPES.has(typeKey)) return inlineOrOverride(typeKey, consumer);\n\tif (DATE_TIME_TYPES.has(typeKey)) return overlay(typeKey, consumer);\n\tif (isArrayCellType(typeKey)) return overlay(typeKey, consumer);\n\tif (GEOMETRY_TYPES.has(typeKey)) return overlay(typeKey, consumer);\n\tif (MEDIA_TYPES.has(typeKey)) return overlay(typeKey, consumer);\n\n\t// 5) Singleton overlay types (each has a DOM_EDITOR_REGISTRY entry).\n\tif (typeKey === 'interval') return overlay(typeKey, consumer);\n\tif (typeKey === 'json' || typeKey === 'jsonb') return overlay(typeKey, consumer);\n\tif (typeKey === 'inet') return overlay(typeKey, consumer);\n\tif (typeKey === 'relation') return overlay(typeKey, consumer);\n\tif (typeKey === 'url') return overlay(typeKey, consumer);\n\t// tsvector — VIEWER_ONLY, but still opens a read-only viewer overlay.\n\tif (VIEWER_ONLY_TYPES.has(typeKey)) return overlay(typeKey, consumer);\n\n\t// 6) Text-like default (text/textarea/email/phone/citext/bpchar/uuid/color/\n\t// origin/unknown + anything unrecognised) → inline edit. `color` is NOT a real\n\t// backend data type — just a hex/text string — so it edits inline too (no dedicated\n\t// color editor). A consumer override on a text-like typeKey still wins as an overlay\n\t// editor via `inlineOrOverride`; otherwise the cell edits in place.\n\treturn inlineOrOverride(typeKey, consumer);\n}\n","/**\n * Range-value extractor — pulls the matrix of cell values covered by a\n * {@link SelectionRect} out of the (possibly virtualized) row array.\n *\n * PURE + SSR-safe — no React, no DOM. The BOUNDED contract is load-bearing: it\n * reads only the cells inside the rect (w×h), never enumerates `rows.length`, so\n * a paste/fill/copy targeting a few cells of a million-row grid stays O(w·h). An\n * unfetched proxy row (infinite-mode) reads as `null` -> its cells come back as\n * `null`; an out-of-range column reads as `null` too.\n *\n * Reused by P3 (paste/fill writes the same coordinate matrix back) and P4 (copy\n * serializes {@link toTSV}).\n */\n\nimport type { SelectionRect } from './selection-model';\n\n/** The extracted block: a `values[row][col]` matrix plus the row indices + col keys it covers. */\nexport interface ExtractedRange {\n\t/** `values[r][c]` — outer index aligns with `rows[r]`, inner with `cols[c]`. */\n\tvalues: unknown[][];\n\t/** Absolute row indices covered (y .. y+height-1). */\n\trows: number[];\n\t/** Column keys covered (columnKeys[x .. x+width-1]). */\n\tcols: string[];\n}\n\n/**\n * Read every cell inside `range` (half-open: x/width = cols, y/height = rows) from\n * `rows` keyed by `columnKeys`. `getDisplay`, when supplied, maps the raw value to\n * the value to emit (e.g. a display string for copy) — defaults to the raw value.\n * Null-safe for unfetched proxy rows and out-of-range columns.\n */\nexport function getCellsInRange(\n\trange: SelectionRect,\n\trows: readonly unknown[],\n\tcolumnKeys: readonly string[],\n\tgetDisplay?: (value: unknown, rowIndex: number, colKey: string) => unknown,\n): ExtractedRange {\n\tconst cols: string[] = [];\n\tfor (let c = 0; c < range.width; c++) {\n\t\tcols.push(columnKeys[range.x + c]);\n\t}\n\n\tconst rowIndices: number[] = [];\n\tconst values: unknown[][] = [];\n\tfor (let r = 0; r < range.height; r++) {\n\t\tconst rowIndex = range.y + r;\n\t\trowIndices.push(rowIndex);\n\t\tconst rowData = rows[rowIndex] as Record<string, unknown> | null | undefined;\n\t\tconst line: unknown[] = [];\n\t\tfor (let c = 0; c < range.width; c++) {\n\t\t\tconst colKey = cols[c];\n\t\t\tconst raw = rowData && colKey != null ? rowData[colKey] : null;\n\t\t\tconst cellValue = raw === undefined ? null : raw;\n\t\t\tline.push(getDisplay ? getDisplay(cellValue, rowIndex, colKey) : cellValue);\n\t\t}\n\t\tvalues.push(line);\n\t}\n\n\treturn { values, rows: rowIndices, cols };\n}\n\n/**\n * Serialize a value matrix to TSV (tab-joined cols, newline-joined rows). Each value\n * is stringified; `null`/`undefined` become an empty cell. Spreadsheet-paste shape —\n * reused by P4 copy.\n */\nexport function toTSV(values: readonly (readonly unknown[])[]): string {\n\treturn values\n\t\t.map((row) => row.map((cell) => (cell == null ? '' : String(cell))).join('\\t'))\n\t\t.join('\\n');\n}\n","/**\n * Fill-math — REPLICATE a source row/column across a target range (P4 Phase 3).\n *\n * PURE + SSR-safe (no React, no DOM) — the analog of {@link getCellsInRange} on the\n * WRITE side: it reads the seed cells out of the raw `rows` array (null-safe for\n * unfetched proxy rows / out-of-range columns, exactly like the extractor) and emits\n * the {@link CellWrite}[] the command hands to `commitCells` (readonly/UUID skips +\n * undo live inside that batch, never here).\n *\n * SCOPE — value REPLICATION only. Numeric/date SERIES detection (1,2 -> 3,4 ; Jan,Feb\n * -> Mar) is DEFERRED: every filled cell is a verbatim copy of the seed.\n */\n\nimport type { SelectionRect } from './selection-model';\nimport type { CellWrite } from '../grid/hooks/use-batch-commit';\n\n/** Read one raw cell value, null-safe (mirrors getCellsInRange: undefined -> null). */\nfunction readCell(rows: readonly unknown[], rowIndex: number, colKey: string): unknown {\n\tconst rowData = rows[rowIndex] as Record<string, unknown> | null | undefined;\n\tconst raw = rowData && colKey != null ? rowData[colKey] : null;\n\treturn raw === undefined ? null : raw;\n}\n\n/**\n * Fill DOWN: SOURCE = the TOP row of `range` (y). For each col `x..x+width-1`, replicate\n * the seed cell value into every row `y+1..y+height-1`. Returns the writes column-major\n * is not required — emitted row-major (top-to-bottom within each... actually outer loop is\n * target rows, inner is cols) so commitCells coalesces per row. A single-row range yields\n * no writes (nothing below the seed).\n */\nexport function fillDownWrites(\n\trange: SelectionRect,\n\trows: readonly unknown[],\n\tcolumnKeys: readonly string[],\n): CellWrite[] {\n\tconst writes: CellWrite[] = [];\n\tconst sourceRow = range.y;\n\tfor (let targetRow = range.y + 1; targetRow < range.y + range.height; targetRow++) {\n\t\tfor (let c = 0; c < range.width; c++) {\n\t\t\tconst colKey = columnKeys[range.x + c];\n\t\t\tif (colKey == null) continue;\n\t\t\twrites.push({ rowIndex: targetRow, colKey, value: readCell(rows, sourceRow, colKey) });\n\t\t}\n\t}\n\treturn writes;\n}\n\n/**\n * Fill RIGHT: SOURCE = the LEFT column of `range` (x). For each col `x+1..x+width-1`,\n * replicate that column's seed (the value in the LEFT column of the SAME row) rightward\n * across every row `y..y+height-1`. A single-column range yields no writes.\n */\nexport function fillRightWrites(\n\trange: SelectionRect,\n\trows: readonly unknown[],\n\tcolumnKeys: readonly string[],\n): CellWrite[] {\n\tconst writes: CellWrite[] = [];\n\tconst sourceColKey = columnKeys[range.x];\n\tfor (let r = 0; r < range.height; r++) {\n\t\tconst rowIndex = range.y + r;\n\t\tconst seed = sourceColKey == null ? null : readCell(rows, rowIndex, sourceColKey);\n\t\tfor (let c = 1; c < range.width; c++) {\n\t\t\tconst colKey = columnKeys[range.x + c];\n\t\t\tif (colKey == null) continue;\n\t\t\twrites.push({ rowIndex, colKey, value: seed });\n\t\t}\n\t}\n\treturn writes;\n}\n\n/**\n * Bulk-edit: FAN a single committed `value` across every cell of `range` (the classic\n * \"select range, type, commit, fill\" edit). Unlike fill-down/right this reads NO seed\n * out of the data — every cell in the range gets the SAME `value` (per-column coercion\n * happens downstream in commitCells/resolveServerPatch). The write set is the COMPLETE\n * range INCLUDING the active cell, so the caller does ONE commitCells (never a single\n * commit + a separate range commit) — no double-write, one optimistic patch, one undo.\n * Out-of-bounds column slots are skipped (mirrors the other fill writers).\n */\nexport function bulkEditWrites(\n\trange: SelectionRect,\n\tvalue: unknown,\n\tcolumnKeys: readonly string[],\n): CellWrite[] {\n\tconst writes: CellWrite[] = [];\n\tfor (let r = 0; r < range.height; r++) {\n\t\tconst rowIndex = range.y + r;\n\t\tfor (let c = 0; c < range.width; c++) {\n\t\t\tconst colKey = columnKeys[range.x + c];\n\t\t\tif (colKey == null) continue;\n\t\t\twrites.push({ rowIndex, colKey, value });\n\t\t}\n\t}\n\treturn writes;\n}\n\n/**\n * Fill-handle DRAG geometry — extend `from` toward target cell `[col,row]` along the\n * DOMINANT axis (v1 supports one axis at a time). PURE.\n *\n * The axis is chosen by which direction the target overshoots `from` the most: if the\n * vertical overshoot (below the bottom / above the top) exceeds the horizontal one we\n * fill VERTICALLY (the rect's height grows); otherwise HORIZONTALLY (width grows). Ties\n * and a target already inside `from` collapse to `from` (no extension). The off-axis span\n * is left exactly as `from`'s.\n */\nexport function extendedFillRect(from: SelectionRect, target: readonly [number, number]): SelectionRect {\n\tconst [col, row] = target;\n\tconst bottom = from.y + from.height - 1;\n\tconst right = from.x + from.width - 1;\n\t// Overshoot past the source band on each axis (0 when target is within the band).\n\tconst vOver = row > bottom ? row - bottom : from.y - row > 0 ? from.y - row : 0;\n\tconst hOver = col > right ? col - right : from.x - col > 0 ? from.x - col : 0;\n\tif (vOver === 0 && hOver === 0) return from;\n\tif (vOver >= hOver) {\n\t\t// Vertical fill: grow the height toward `row`, keep x/width.\n\t\tconst y = Math.min(from.y, row);\n\t\tconst yEnd = Math.max(bottom, row);\n\t\treturn { x: from.x, y, width: from.width, height: yEnd - y + 1 };\n\t}\n\t// Horizontal fill: grow the width toward `col`, keep y/height.\n\tconst x = Math.min(from.x, col);\n\tconst xEnd = Math.max(right, col);\n\treturn { x, y: from.y, width: xEnd - x + 1, height: from.height };\n}\n\n/**\n * Replicate the SOURCE band `from` across the NEW cells of `extended` (the cells in\n * `extended` that are NOT in `from`). For a vertical extension each new row copies the\n * matching column's value from the NEAREST source row (the band repeats); for a horizontal\n * extension each new column copies the matching row's nearest source column. Value\n * REPLICATION only — SERIES detection DEFERRED. Skips the `from` band (already populated).\n */\nexport function fillDragWrites(\n\tfrom: SelectionRect,\n\textended: SelectionRect,\n\trows: readonly unknown[],\n\tcolumnKeys: readonly string[],\n): CellWrite[] {\n\tconst writes: CellWrite[] = [];\n\tfor (let ty = extended.y; ty < extended.y + extended.height; ty++) {\n\t\tfor (let tx = extended.x; tx < extended.x + extended.width; tx++) {\n\t\t\t// Inside the source band — already has its value, never overwrite.\n\t\t\tif (tx >= from.x && tx < from.x + from.width && ty >= from.y && ty < from.y + from.height) continue;\n\t\t\tconst colKey = columnKeys[tx];\n\t\t\tif (colKey == null) continue;\n\t\t\t// Tile the source band: map the target back into the band on each axis.\n\t\t\tconst srcCol = from.x + ((tx - from.x) % from.width + from.width) % from.width;\n\t\t\tconst srcRow = from.y + ((ty - from.y) % from.height + from.height) % from.height;\n\t\t\tconst srcKey = columnKeys[srcCol];\n\t\t\twrites.push({ rowIndex: ty, colKey, value: srcKey == null ? null : readCell(rows, srcRow, srcKey) });\n\t\t}\n\t}\n\treturn writes;\n}\n","/**\n * TSV parse + tile — the INVERSE of {@link toTSV} (cell-extract.ts), used by the\n * clipboard.paste command. PURE + SSR-safe (no React, no DOM, no clipboard).\n *\n * `parseTSV` round-trips a `toTSV` string back into a `string[][]` matrix (split rows\n * on `\\n`, cols on `\\t`), tolerating ONE trailing newline (a spreadsheet copy ends the\n * last row with `\\n`) so it does not yield a spurious empty trailing row. `tileMatrix`\n * implements spreadsheet fill semantics: a 1×N / N×1 source REPEATS to fill a larger\n * target, otherwise the source is written from the anchor as-is.\n */\n\n/**\n * Parse a TSV string into a `string[][]` matrix (rows × cols). Splits rows on `\\n`\n * (a lone trailing `\\n` is dropped so it does not add an empty row) and cols on `\\t`.\n * `\\r` is stripped so a CRLF clipboard payload parses the same as LF. An empty string\n * yields a single empty cell `[['']]` (mirrors a 1×1 blank paste).\n */\nexport function parseTSV(text: string): string[][] {\n\tconst normalized = text.replace(/\\r\\n?/g, '\\n');\n\t// Drop a single trailing newline so a spreadsheet copy's terminal `\\n` is not an extra row.\n\tconst body = normalized.endsWith('\\n') ? normalized.slice(0, -1) : normalized;\n\treturn body.split('\\n').map((line) => line.split('\\t'));\n}\n\n/**\n * Tile `source` to fill a `targetW × targetH` region (spreadsheet fill semantics):\n * • a 1×N source (single row) repeats DOWN to fill targetH rows.\n * • an N×1 source (single col) repeats ACROSS to fill targetW cols.\n * • a 1×1 source repeats in both axes.\n * • any other (genuinely 2-D) source is returned unchanged — the caller writes it\n * from the anchor as-is (no tiling), matching spreadsheet \"paste block\" behavior.\n *\n * Only repeats when the source is strictly smaller than the target on the repeating\n * axis; a source already >= the target is left intact (clamping is the caller's job).\n */\nexport function tileMatrix(source: string[][], targetW: number, targetH: number): string[][] {\n\tconst srcH = source.length;\n\tconst srcW = srcH > 0 ? source[0].length : 0;\n\tif (srcH === 0 || srcW === 0) return source;\n\n\tconst isSingleRow = srcH === 1;\n\tconst isSingleCol = srcW === 1;\n\t// Only 1×N / N×1 (and 1×1) sources tile; a real 2-D block pastes as-is.\n\tif (!isSingleRow && !isSingleCol) return source;\n\n\tconst outH = isSingleRow && targetH > srcH ? targetH : srcH;\n\tconst outW = isSingleCol && targetW > srcW ? targetW : srcW;\n\n\tconst out: string[][] = [];\n\tfor (let r = 0; r < outH; r++) {\n\t\tconst srcRow = source[r % srcH];\n\t\tconst line: string[] = [];\n\t\tfor (let c = 0; c < outW; c++) {\n\t\t\tline.push(srcRow[c % srcW]);\n\t\t}\n\t\tout.push(line);\n\t}\n\treturn out;\n}\n","/**\n * DEFAULT_COMMANDS + createGridCommandRegistry (P4 Phase 1).\n *\n * Each command body is LIFTED VERBATIM from grid/sheets.tsx's handleGridKeyDown /\n * handleActivateCell / openEditor / openEditorAtActiveCell branches — same dispatcher\n * calls, same anchor resets, same clamp/scroll order. The handler's local guards\n * (`if (rows === 0 || colCount === 0) return`) are preserved as `canRun` where the\n * original returned WITHOUT preventing default, and inline where the original DID\n * prevent default first (Ctrl+A / arrows / nav: the original called preventDefault()\n * before the empty-grid early return, so the no-op must still preventDefault — that is\n * the core's job once the command resolves, and the body simply returns early).\n *\n * Phase 1 is a refactor: these bodies call `ctx.<dispatcher>` (the existing stable fns).\n */\n\nimport { computeKeyNavTarget, emptySheetsSelection, selectAllCells } from '../selection/selection-model';\nimport type { SelectionRect } from '../selection/selection-model';\nimport { parseTSV, tileMatrix } from '../selection/tsv';\nimport { fillDownWrites, fillRightWrites, extendedFillRect, fillDragWrites } from '../selection/fill';\nimport type { CellWrite } from '../grid/hooks/use-batch-commit';\nimport type { GridCommand, GridCommandRegistry } from './types';\nimport type { GridCommandContext, CellMatrix } from './context';\n\n/** Payload for `cell.activate` / `cell.extendToClicked` (pointer). */\nexport interface CellPointerPayload {\n\tcol: number;\n\trow: number;\n}\n\n/** Payload for `editor.open` (dblclick). */\nexport interface EditorOpenPayload {\n\trowIndex: number;\n\tcolKey: string;\n\tanchorRect: DOMRect;\n\tinitialText?: string;\n}\n\n/** Payload for `editor.typeToEdit` (printable key sentinel). */\nexport interface TypeToEditPayload {\n\tchar: string;\n}\n\n/** Payload for `cell.navAbsolute` (Tab/Home/End/PageUp/PageDown). */\nexport interface NavAbsolutePayload {\n\tkey: string;\n\tctrlOrMeta: boolean;\n\tshift: boolean;\n\t/** Visible page span (rows); the funnel derives this from the scroll element clientHeight. */\n\tpageRows: number;\n}\n\n/** Payload for `header.sortToggle`. */\nexport interface SortTogglePayload {\n\tcolKey: string;\n}\n\n/** Payload for `rowmarker.toggleRow`. */\nexport interface ToggleRowPayload {\n\trowIndex: number;\n\tshift: boolean;\n}\n\n/** Payload for `fill.drag` (fill-handle nub release). `from` = source band, `to` = `[col,row]` under the pointer. */\nexport interface FillDragPayload {\n\tfrom: SelectionRect;\n\tto: [number, number];\n}\n\n/**\n * The minimal `DataTransfer` slice the clipboard commands read/write — `ClipboardEvent.clipboardData`\n * conforms (so does a test stub). Kept narrow so the command never depends on the full DOM type.\n */\nexport interface ClipboardLike {\n\tgetData(format: string): string;\n\tsetData(format: string, data: string): void;\n}\n\n/** Payload for `clipboard.copy` / `clipboard.cut` / `clipboard.paste` (native clipboard event). */\nexport interface ClipboardPayload {\n\tclipboard: ClipboardLike | null;\n}\n\n/** Shared empty-grid guard (the original `rows === 0 || colCount === 0` short-circuit). */\nfunction gridNonEmpty(ctx: GridCommandContext): boolean {\n\treturn ctx.rowCount > 0 && ctx.colCount > 0;\n}\n\n/**\n * The cell range the clipboard commands act on: the active selection range when present,\n * else a 1×1 rect at the active cell. `null` when there is no active cell (empty grid /\n * no cursor) — the copy/cut/paste `canRun` guards return false on null.\n */\nfunction clipboardRange(ctx: GridCommandContext): SelectionRect | null {\n\tconst range = ctx.selection?.current?.range;\n\tif (range) return range;\n\tconst cell = ctx.activeCell;\n\tif (!cell) return null;\n\treturn { x: cell[0], y: cell[1], width: 1, height: 1 };\n}\n\n/** Build a `null` write for every cell in `rect` (clamped to the column keys). */\nfunction clearRangeWrites(rect: SelectionRect, columnKeys: readonly string[]): CellWrite[] {\n\tconst writes: CellWrite[] = [];\n\tfor (let r = 0; r < rect.height; r++) {\n\t\tfor (let c = 0; c < rect.width; c++) {\n\t\t\tconst colKey = columnKeys[rect.x + c];\n\t\t\tif (colKey == null) continue;\n\t\t\twrites.push({ rowIndex: rect.y + r, colKey, value: null });\n\t\t}\n\t}\n\treturn writes;\n}\n\n/** True when the async `navigator.clipboard` API is reachable (secure context, browser). */\nfunction navigatorClipboard(): Clipboard | null {\n\treturn typeof navigator !== 'undefined' && navigator.clipboard ? navigator.clipboard : null;\n}\n\n/** The `null` writes that clear every cell of a copied/cut matrix (cut's source clear). */\nfunction cutRangeWrites(matrix: CellMatrix): CellWrite[] {\n\tconst writes: CellWrite[] = [];\n\tfor (let r = 0; r < matrix.rows.length; r++) {\n\t\tfor (let c = 0; c < matrix.cols.length; c++) {\n\t\t\tconst colKey = matrix.cols[c];\n\t\t\tif (colKey == null) continue;\n\t\t\twrites.push({ rowIndex: matrix.rows[r], colKey, value: null });\n\t\t}\n\t}\n\treturn writes;\n}\n\n/**\n * Tile a parsed TSV `source` onto the target and build the clamped writes — the shared body\n * of both paste paths (native event + navigator fallback). `anchor` is the active cell's\n * top-left; `range` (when present + larger than the source) drives tiling.\n */\nfunction pasteWrites(ctx: GridCommandContext, anchor: readonly [number, number], text: string): CellWrite[] {\n\tconst source = parseTSV(text);\n\tconst range = ctx.selection?.current?.range;\n\tconst targetW = range ? range.width : source[0]?.length ?? 0;\n\tconst targetH = range ? range.height : source.length;\n\tconst matrix = tileMatrix(source, targetW, targetH);\n\n\tconst [anchorCol, anchorRow] = anchor;\n\tconst writes: CellWrite[] = [];\n\tfor (let r = 0; r < matrix.length; r++) {\n\t\tconst rowIndex = anchorRow + r;\n\t\tif (rowIndex >= ctx.rowCount) break; // clamp to grid bottom\n\t\tconst line = matrix[r];\n\t\tfor (let c = 0; c < line.length; c++) {\n\t\t\tconst colIndex = anchorCol + c;\n\t\t\tif (colIndex >= ctx.colCount) break; // clamp to grid right\n\t\t\tconst colKey = ctx.columnKeys[colIndex];\n\t\t\tif (colKey == null) continue;\n\t\t\twrites.push({ rowIndex, colKey, value: line[c] });\n\t\t}\n\t}\n\treturn writes;\n}\n\n/**\n * The default command set. Authored as plain objects (no classes). Frozen array so the\n * registry factory can clone it; consumer overrides replace by id (Phase 2 seam).\n */\nexport const DEFAULT_COMMANDS: GridCommand[] = [\n\t// ---- UNDO / REDO (lifted: handleGridKeyDown undo/redo branch) ----\n\t{\n\t\tid: 'edit.undo',\n\t\trun: (ctx) => {\n\t\t\tvoid ctx.undo();\n\t\t},\n\t},\n\t{\n\t\tid: 'edit.redo',\n\t\trun: (ctx) => {\n\t\t\tvoid ctx.redo();\n\t\t},\n\t},\n\n\t// ---- SELECT ALL (lifted: Ctrl/Cmd+A branch) ----\n\t{\n\t\tid: 'selection.all',\n\t\tcanRun: gridNonEmpty,\n\t\trun: (ctx) => {\n\t\t\tctx.setAnchor([0, 0]);\n\t\t\tctx.setSelection(selectAllCells(ctx.selection ?? emptySheetsSelection, ctx.colCount, ctx.rowCount));\n\t\t},\n\t},\n\n\t// ---- CLIPBOARD COPY (serialize range → TSV → clipboard) ----\n\t// Serializes the active range (or the 1×1 active cell) to TSV. TWO paths:\n\t// • NATIVE: `payload.clipboard` is the `copy` event's DataTransfer — write it synchronously.\n\t// preventDefault happens in the dispatch CORE (so the browser does not ALSO copy its own —\n\t// empty — selection).\n\t// • MENU/PROGRAMMATIC: no DataTransfer (the context menu has no native event) — fall back to\n\t// the async `navigator.clipboard.writeText` (rejection caught → no-op; secure-context gated).\n\t// canRun gates on an active cell/range existing.\n\t{\n\t\tid: 'clipboard.copy',\n\t\tcanRun: (ctx) => clipboardRange(ctx) !== null,\n\t\trun: (ctx, payload) => {\n\t\t\tconst range = clipboardRange(ctx);\n\t\t\tif (!range) return;\n\t\t\tconst tsv = ctx.toTSV(ctx.getCellsInRange(range).values);\n\t\t\tconst clipboard = (payload as ClipboardPayload | undefined)?.clipboard;\n\t\t\tif (clipboard) {\n\t\t\t\tclipboard.setData('text/plain', tsv);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst nav = navigatorClipboard();\n\t\t\tif (nav) return nav.writeText(tsv).catch(() => {});\n\t\t},\n\t},\n\n\t// ---- CLIPBOARD CUT (copy serialize + clear the source range) ----\n\t// Runs the copy serialize (native DataTransfer or navigator fallback, same branch as copy),\n\t// then commits `null` across every cell of the source range as ONE undo-aware batch\n\t// (commitCells skips readonly/UUID cells internally). Same range source.\n\t{\n\t\tid: 'clipboard.cut',\n\t\tcanRun: (ctx) => clipboardRange(ctx) !== null,\n\t\trun: (ctx, payload) => {\n\t\t\tconst range = clipboardRange(ctx);\n\t\t\tif (!range) return;\n\t\t\tconst matrix = ctx.getCellsInRange(range);\n\t\t\tconst tsv = ctx.toTSV(matrix.values);\n\t\t\tconst writes = cutRangeWrites(matrix);\n\t\t\tconst clipboard = (payload as ClipboardPayload | undefined)?.clipboard;\n\t\t\tif (clipboard) {\n\t\t\t\tclipboard.setData('text/plain', tsv);\n\t\t\t\tvoid ctx.commitCells(writes);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst nav = navigatorClipboard();\n\t\t\tif (!nav) return;\n\t\t\t// Clear only once the write resolves so a clipboard rejection leaves the source intact.\n\t\t\treturn nav.writeText(tsv).then(() => {\n\t\t\t\tvoid ctx.commitCells(writes);\n\t\t\t}).catch(() => {});\n\t\t},\n\t},\n\n\t// ---- CLIPBOARD PASTE (parse TSV → tile → commitCells) ----\n\t// Parses the clipboard TSV, TILES it onto the target (a 1×N / N×1 source repeats to fill a\n\t// larger selection range; a 2-D block writes from the anchor as-is), clamps to grid bounds, and\n\t// commits ONE batch (single optimistic patch + coalesced per-row mutations + ONE undo entry).\n\t// commitCells skips readonly/UUID cells. The anchor is the active cell's top-left. TWO paths:\n\t// • NATIVE: `payload.clipboard` is the `paste` event's DataTransfer — read it synchronously.\n\t// • MENU/PROGRAMMATIC: no DataTransfer — fall back to async `navigator.clipboard.readText`\n\t// (rejection caught → no-op; secure-context gated).\n\t{\n\t\tid: 'clipboard.paste',\n\t\tcanRun: (ctx) => ctx.activeCell != null,\n\t\trun: (ctx, payload) => {\n\t\t\tconst anchor = ctx.activeCell;\n\t\t\tif (!anchor) return;\n\t\t\tconst clipboard = (payload as ClipboardPayload | undefined)?.clipboard;\n\t\t\tif (clipboard) {\n\t\t\t\tconst text = clipboard.getData('text/plain');\n\t\t\t\tif (!text) return;\n\t\t\t\tconst writes = pasteWrites(ctx, anchor, text);\n\t\t\t\tif (writes.length) void ctx.commitCells(writes);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst nav = navigatorClipboard();\n\t\t\tif (!nav) return;\n\t\t\treturn nav.readText().then((text) => {\n\t\t\t\tif (!text) return;\n\t\t\t\tconst writes = pasteWrites(ctx, anchor, text);\n\t\t\t\tif (writes.length) void ctx.commitCells(writes);\n\t\t\t}).catch(() => {});\n\t\t},\n\t},\n\n\t// ---- CELL CLEAR (Delete / Backspace: write null over the active range) ----\n\t// range = the active selection range, else a 1×1 rect at the active cell. Builds a\n\t// {rowIndex, colKey, value: null} write for every cell in the rect and commits ONE\n\t// undo-aware batch (commitCells skips readonly/UUID internally; non-nullable columns\n\t// reject server-side and the optimistic patch reverts — null is the DB-clear default).\n\t// canRun gates on an active cell/range existing.\n\t{\n\t\tid: 'cell.clear',\n\t\tcanRun: (ctx) => clipboardRange(ctx) !== null,\n\t\trun: (ctx) => {\n\t\t\tconst range = clipboardRange(ctx);\n\t\t\tif (!range) return;\n\t\t\tconst writes = clearRangeWrites(range, ctx.columnKeys);\n\t\t\tif (writes.length) void ctx.commitCells(writes);\n\t\t},\n\t},\n\n\t// ---- FILL DOWN (Mod+D: replicate the TOP row of the range downward) ----\n\t// SOURCE = the range's top row; every lower row in the range gets the seed value of the\n\t// column above it. ONE undo-aware batch via commitCells (readonly/UUID skipped internally).\n\t// SCOPE: value replication only — numeric/date SERIES detection is DEFERRED.\n\t{\n\t\tid: 'fill.down',\n\t\tcanRun: (ctx) => {\n\t\t\tconst range = ctx.selection?.current?.range;\n\t\t\treturn !!range && range.height > 1;\n\t\t},\n\t\trun: (ctx) => {\n\t\t\tconst range = ctx.selection?.current?.range;\n\t\t\tif (!range) return;\n\t\t\tconst writes = fillDownWrites(range, ctx.combinedRows, ctx.columnKeys);\n\t\t\tif (writes.length) void ctx.commitCells(writes);\n\t\t},\n\t},\n\n\t// ---- FILL RIGHT (Mod+R: replicate the LEFT column of the range rightward) ----\n\t// SOURCE = the range's left column; every column to its right gets that row's left-column\n\t// seed. ONE undo-aware batch. SCOPE: value replication only — SERIES detection DEFERRED.\n\t{\n\t\tid: 'fill.right',\n\t\tcanRun: (ctx) => {\n\t\t\tconst range = ctx.selection?.current?.range;\n\t\t\treturn !!range && range.width > 1;\n\t\t},\n\t\trun: (ctx) => {\n\t\t\tconst range = ctx.selection?.current?.range;\n\t\t\tif (!range) return;\n\t\t\tconst writes = fillRightWrites(range, ctx.combinedRows, ctx.columnKeys);\n\t\t\tif (writes.length) void ctx.commitCells(writes);\n\t\t},\n\t},\n\n\t// ---- FILL DRAG (fill-handle nub release: extend `from` toward `to`, tile the source) ----\n\t// The pointer-driven analogue of fill.down/right: extend the SOURCE band toward the dropped\n\t// cell along the dominant axis, REPLICATE the band across the new cells (one undo-aware batch),\n\t// then WIDEN the selection to the extended rect so the band grows to match. canRun gates on a\n\t// payload (from + to) being present. SCOPE: value replication only — SERIES detection DEFERRED.\n\t{\n\t\tid: 'fill.drag',\n\t\tcanRun: (_ctx, payload) => {\n\t\t\tconst p = payload as FillDragPayload | undefined;\n\t\t\treturn !!p && !!p.from && !!p.to;\n\t\t},\n\t\trun: (ctx, payload) => {\n\t\t\tconst { from, to } = payload as FillDragPayload;\n\t\t\tconst extended = extendedFillRect(from, to);\n\t\t\t// Target inside the source band — nothing to extend.\n\t\t\tif (extended.width === from.width && extended.height === from.height && extended.x === from.x && extended.y === from.y)\n\t\t\t\treturn;\n\t\t\tconst writes = fillDragWrites(from, extended, ctx.combinedRows, ctx.columnKeys);\n\t\t\tif (writes.length) void ctx.commitCells(writes);\n\t\t\t// Grow the band: active cell parks on the far corner, range becomes the extended rect.\n\t\t\tconst base = ctx.selection ?? emptySheetsSelection;\n\t\t\tctx.setSelection({\n\t\t\t\t...base,\n\t\t\t\tcurrent: {\n\t\t\t\t\tcell: [extended.x + extended.width - 1, extended.y + extended.height - 1],\n\t\t\t\t\trange: extended,\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t},\n\n\t// ---- ARROW MOVE (plain arrow: setAnchor + moveActiveCell + scroll) ----\n\t// Each direction is its own named command; the funnel resolves the arrow key to it.\n\tmakeMoveCommand('cell.moveUp', 0, -1),\n\tmakeMoveCommand('cell.moveDown', 0, 1),\n\tmakeMoveCommand('cell.moveLeft', -1, 0),\n\tmakeMoveCommand('cell.moveRight', 1, 0),\n\n\t// ---- ARROW EXTEND (shift+arrow: extendToCell + scroll) ----\n\tmakeExtendCommand('cell.extendUp', 0, -1),\n\tmakeExtendCommand('cell.extendDown', 0, 1),\n\tmakeExtendCommand('cell.extendLeft', -1, 0),\n\tmakeExtendCommand('cell.extendRight', 1, 0),\n\n\t// ---- ABSOLUTE NAV (Tab/Home/End/PageUp/PageDown: computeKeyNavTarget) ----\n\t{\n\t\tid: 'cell.navAbsolute',\n\t\tcanRun: gridNonEmpty,\n\t\trun: (ctx, payload) => {\n\t\t\tconst p = payload as NavAbsolutePayload;\n\t\t\tconst base = ctx.selection?.current?.cell ?? [0, 0];\n\t\t\tconst target = computeKeyNavTarget(\n\t\t\t\tp.key,\n\t\t\t\t{ ctrlOrMeta: p.ctrlOrMeta, shift: p.shift },\n\t\t\t\tbase,\n\t\t\t\tctx.colCount,\n\t\t\t\tctx.rowCount,\n\t\t\t\tp.pageRows,\n\t\t\t);\n\t\t\tif (!target) return;\n\t\t\t// Absolute moves are plain activates — reset the range anchor to the landing cell.\n\t\t\tctx.setAnchor([target[0], target[1]]);\n\t\t\tctx.setActiveCell(target[0], target[1]);\n\t\t\tctx.scrollToCell(target[0], target[1]);\n\t\t},\n\t},\n\n\t// ---- OPEN EDITOR AT ACTIVE (Enter / F2) ----\n\t{\n\t\tid: 'editor.openActive',\n\t\t// Mirrors the original `if (openEditorAtActiveCell()) e.preventDefault()`: only\n\t\t// prevent default when an overlay actually opened. canRun probes the same path.\n\t\tcanRun: (ctx) => ctx.openEditorAtActive(),\n\t\trun: () => {\n\t\t\t// canRun already opened the editor (it returns true only when it opened) — running\n\t\t\t// again would double-open, so the effect lives in canRun and run is a no-op. This is\n\t\t\t// the verbatim \"open then conditionally preventDefault\" semantics, expressed through\n\t\t\t// the gate so a non-opening Enter falls through WITHOUT preventDefault.\n\t\t},\n\t},\n\n\t// ---- TYPE-TO-EDIT SENTINEL (printable key: openEditorAtActive(char)) ----\n\t// The LAST-RESOLVED sentinel for printable keys — it goes THROUGH dispatch (so it is\n\t// interceptable), NOT an out-of-band fallback. canRun opens with the seed char and gates\n\t// preventDefault on a real open (readonly cells return false → key falls through).\n\t{\n\t\tid: 'editor.typeToEdit',\n\t\tcanRun: (ctx, payload) => ctx.openEditorAtActive((payload as TypeToEditPayload).char),\n\t\trun: () => {\n\t\t\t// effect performed in canRun (same conditional-preventDefault rationale as openActive).\n\t\t},\n\t},\n\n\t// ---- POINTER ACTIVATE (click: setAnchor + setActiveCell) ----\n\t{\n\t\tid: 'cell.activate',\n\t\trun: (ctx, payload) => {\n\t\t\tconst { col, row } = payload as CellPointerPayload;\n\t\t\tctx.setAnchor([col, row]);\n\t\t\tctx.setActiveCell(col, row);\n\t\t},\n\t},\n\n\t// ---- POINTER SHIFT-EXTEND (shift-click: extendToCell) ----\n\t{\n\t\tid: 'cell.extendToClicked',\n\t\trun: (ctx, payload) => {\n\t\t\tconst { col, row } = payload as CellPointerPayload;\n\t\t\tctx.extendToCell(col, row);\n\t\t},\n\t},\n\n\t// ---- DBLCLICK OPEN (openEditorAt) ----\n\t{\n\t\tid: 'editor.open',\n\t\trun: (ctx, payload) => {\n\t\t\tconst { rowIndex, colKey, anchorRect, initialText } = payload as EditorOpenPayload;\n\t\t\tctx.openEditorAt(rowIndex, colKey, anchorRect, initialText);\n\t\t},\n\t},\n\n\t// ---- STRUCTURAL POINTER (routed through dispatch for invariant completeness) ----\n\t{\n\t\tid: 'header.sortToggle',\n\t\trun: (ctx, payload) => {\n\t\t\tctx.sortToggle((payload as SortTogglePayload).colKey);\n\t\t},\n\t},\n\t{\n\t\tid: 'rowmarker.toggleRow',\n\t\trun: (ctx, payload) => {\n\t\t\tconst { rowIndex, shift } = payload as ToggleRowPayload;\n\t\t\t// Delegated to the existing rowMarker.onToggleRow (anchor + selectRange/toggleRow). Phase 1\n\t\t\t// keeps that handler the source of truth; the command threads it so the id exists in the map.\n\t\t\tctx.toggleRow(rowIndex, shift);\n\t\t},\n\t},\n\t{\n\t\tid: 'rowmarker.toggleAll',\n\t\trun: (ctx) => {\n\t\t\tctx.toggleAll();\n\t\t},\n\t},\n];\n\n/**\n * Plain-arrow MOVE command factory (verbatim: arrow branch, non-shift path). Computes the\n * clamped target off the LATEST selection, RESETS the anchor, moves, then scrolls.\n */\nfunction makeMoveCommand(id: string, dCol: number, dRow: number): GridCommand {\n\treturn {\n\t\tid,\n\t\tcanRun: gridNonEmpty,\n\t\trun: (ctx) => {\n\t\t\tconst base = ctx.selection?.current?.cell ?? [0, 0];\n\t\t\tconst nextCol = Math.max(0, Math.min(base[0] + dCol, ctx.colCount - 1));\n\t\t\tconst nextRow = Math.max(0, Math.min(base[1] + dRow, ctx.rowCount - 1));\n\t\t\tctx.setAnchor([nextCol, nextRow]);\n\t\t\tctx.moveActiveCell(dCol, dRow, ctx.colCount, ctx.rowCount);\n\t\t\tctx.scrollToCell(nextCol, nextRow);\n\t\t},\n\t};\n}\n\n/**\n * Shift-arrow EXTEND command factory (verbatim: arrow branch, shift path). Extends the\n * range from the FIXED anchor to the clamped target, then scrolls the target into view.\n */\nfunction makeExtendCommand(id: string, dCol: number, dRow: number): GridCommand {\n\treturn {\n\t\tid,\n\t\tcanRun: gridNonEmpty,\n\t\trun: (ctx) => {\n\t\t\tconst base = ctx.selection?.current?.cell ?? [0, 0];\n\t\t\tconst nextCol = Math.max(0, Math.min(base[0] + dCol, ctx.colCount - 1));\n\t\t\tconst nextRow = Math.max(0, Math.min(base[1] + dRow, ctx.rowCount - 1));\n\t\t\tctx.extendToCell(nextCol, nextRow);\n\t\t\tctx.scrollToCell(nextCol, nextRow);\n\t\t},\n\t};\n}\n\n/**\n * Build a command registry: DEFAULT_COMMANDS, with optional consumer overrides folded in\n * LAST so a matching id REPLACES the default and a new id ADDS a command (Phase 2 seam).\n */\nexport function createGridCommandRegistry(overrides?: GridCommand[]): GridCommandRegistry {\n\tconst registry: GridCommandRegistry = new Map();\n\tfor (const cmd of DEFAULT_COMMANDS) registry.set(cmd.id, cmd);\n\tif (overrides) {\n\t\tfor (const cmd of overrides) registry.set(cmd.id, cmd);\n\t}\n\treturn registry;\n}\n","/**\n * The ONE interceptable dispatch pipeline (P4 Phase 1).\n *\n * `dispatch(command, native?, payload?)`:\n * 1. resolve `command` in the registry — a missing / null id is a silent NO-OP\n * (so an unbound key falls through to the browser: NO `preventDefault`).\n * 2. run the interceptor chain (reduceRight → first-listed is OUTERMOST). Each\n * interceptor may VETO (not call `next` → command never runs, nothing prevented),\n * TRANSFORM (mutate `ev.payload` before `next`), or OBSERVE (read `next()`'s result).\n * 3. AFTER the chain, check `command.canRun(ctx, payload)` — false NO-OPs (and does\n * NOT preventDefault).\n * 4. `native?.preventDefault()` happens ONLY here in the core (so a vetoed / unresolved /\n * can't-run command leaves the native event untouched and the key reaches the browser).\n * 5. `command.run(ctx, payload)` — synchronous return (it MAY kick a Promise; we never\n * await — NO async-dispatch / re-entrancy machinery).\n *\n * Phase 1 ships ZERO interceptors (the consumer seam is Phase 2); the chain is wired so\n * adding one later is purely additive and behavior stays byte-for-byte identical.\n */\n\nimport type { GridCommandContext } from './context';\nimport type { GridCommandRegistry } from './types';\n\n/** The mutable event threaded through the interceptor chain. */\nexport interface DispatchEvent {\n\t/** The resolved command id. */\n\tcommand: string;\n\t/** The originating native event, if any (the funnel's `preventDefault` target). */\n\tnative?: Event;\n\t/** The command payload — interceptors MAY mutate this in place to TRANSFORM. */\n\tpayload?: unknown;\n}\n\n/** Result of a dispatch attempt — observable by interceptors via `next()`. */\nexport interface CommandResult {\n\t/** The dispatched command id (or null when nothing resolved). */\n\tcommand: string | null;\n\t/** Whether `command.run` was invoked (false = unresolved / vetoed / canRun=false). */\n\tran: boolean;\n\t/** Whether `native.preventDefault()` was called. */\n\tprevented: boolean;\n}\n\n/**\n * An interceptor wraps the rest of the chain (`next`). Call `next()` to continue\n * (returning its CommandResult); SKIP it to VETO; mutate `ev.payload` before `next()`\n * to TRANSFORM. The OUTERMOST (first-listed) interceptor sees the final result.\n */\nexport type Interceptor = (ev: DispatchEvent, next: () => CommandResult) => CommandResult;\n\n/** The dispatch fn signature wired into the grid root. */\nexport type Dispatch = (command: string | null, native?: Event, payload?: unknown) => CommandResult;\n\nconst UNRESOLVED: CommandResult = { command: null, ran: false, prevented: false };\n\n/**\n * Wrap an `onCommand(ev, result)` callback as an INNERMOST tail OBSERVER interceptor:\n * it always calls `next()` (never vetoes / transforms), then reports the final\n * {@link CommandResult} to the consumer. Listed LAST in the interceptor array so it\n * runs after all consumer interceptors (closest to the core) and observes the actual\n * outcome — purely observational, never altering behavior.\n */\nexport function tailObserver(onCommand: (ev: DispatchEvent, result: CommandResult) => void): Interceptor {\n\treturn (ev, next) => {\n\t\tconst result = next();\n\t\tonCommand(ev, result);\n\t\treturn result;\n\t};\n}\n\n/**\n * Build the dispatch fn over a registry + live context + (optional) interceptor list.\n * `getContext` is read fresh per dispatch so the latched context is always current.\n */\nexport function makeDispatch(\n\tregistry: GridCommandRegistry,\n\tgetContext: () => GridCommandContext,\n\tinterceptors: Interceptor[] = [],\n): Dispatch {\n\treturn function dispatch(command, native, payload): CommandResult {\n\t\tif (command == null) return UNRESOLVED;\n\t\tconst cmd = registry.get(command);\n\t\tif (!cmd) return { command, ran: false, prevented: false };\n\n\t\tconst ev: DispatchEvent = { command, native, payload };\n\n\t\t// The CORE runs last (innermost): canRun gate → preventDefault → run.\n\t\tconst core = (): CommandResult => {\n\t\t\tconst ctx = getContext();\n\t\t\tif (cmd.canRun && !cmd.canRun(ctx, ev.payload)) {\n\t\t\t\treturn { command, ran: false, prevented: false };\n\t\t\t}\n\t\t\tlet prevented = false;\n\t\t\tif (ev.native) {\n\t\t\t\tev.native.preventDefault();\n\t\t\t\tprevented = true;\n\t\t\t}\n\t\t\tvoid cmd.run(ctx, ev.payload);\n\t\t\treturn { command, ran: true, prevented };\n\t\t};\n\n\t\t// reduceRight so the FIRST-LISTED interceptor is the OUTERMOST wrapper.\n\t\tconst chain = interceptors.reduceRight<() => CommandResult>(\n\t\t\t(next, interceptor) => () => interceptor(ev, next),\n\t\t\tcore,\n\t\t);\n\t\treturn chain();\n\t};\n}\n","/**\n * Keybinding primitives — COPIED from packages/command-palette/src/keybinding.ts\n * (kbd / matchKeyBinding / isMac / isEditableTarget) so @constructive-io/sheets stays\n * distributable WITHOUT a dependency on command-palette. Keep the two in sync by hand;\n * the logic is intentionally identical (strict modifier matching, Mac mod=meta).\n */\n\n/** Modifier key abstraction. 'mod' = Cmd on Mac, Ctrl on Windows/Linux. */\nexport type KeyModifier = 'mod' | 'shift' | 'alt';\n\n/** Structured key binding — matchable against KeyboardEvents. */\nexport interface KeyBinding {\n\tmodifiers?: KeyModifier[];\n\t/** Lowercase key name: 'h', 'k', 'enter', 'backspace', ',', '/', etc. */\n\tkey: string;\n}\n\n/** Ergonomic KeyBinding factory. */\nexport function kbd(key: string, ...modifiers: KeyModifier[]): KeyBinding {\n\treturn modifiers.length > 0 ? { key, modifiers } : { key };\n}\n\n/** Platform detection with SSR fallback (assumes non-Mac). */\nexport function isMac(): boolean {\n\tif (typeof navigator === 'undefined') return false;\n\treturn /mac|ipod|iphone|ipad/i.test(navigator.platform ?? '');\n}\n\n/** Check if event target is an editable element (input, textarea, select, contenteditable). */\nexport function isEditableTarget(target: EventTarget | null): boolean {\n\tif (!target || !(target instanceof HTMLElement)) return false;\n\tconst tag = target.tagName;\n\tif (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;\n\treturn target.contentEditable === 'true';\n}\n\n/** Match a KeyboardEvent against a KeyBinding with strict modifier check. */\nexport function matchKeyBinding(event: KeyboardEvent, binding: KeyBinding): boolean {\n\t// Compare key (case-insensitive)\n\tif (event.key.toLowerCase() !== binding.key.toLowerCase()) return false;\n\n\tconst mods = binding.modifiers ?? [];\n\tconst wantMod = mods.includes('mod');\n\tconst wantShift = mods.includes('shift');\n\tconst wantAlt = mods.includes('alt');\n\n\t// On Mac, 'mod' maps to metaKey; elsewhere, ctrlKey\n\tconst modPressed = isMac() ? event.metaKey : event.ctrlKey;\n\n\t// Strict: every required modifier must be pressed, no extras\n\tif (wantMod !== modPressed) return false;\n\tif (wantShift !== event.shiftKey) return false;\n\tif (wantAlt !== event.altKey) return false;\n\n\t// Prevent false positives: if mod maps to meta on Mac, ctrl shouldn't be pressed (and vice versa)\n\tif (isMac()) {\n\t\tif (!wantMod && event.ctrlKey) return false;\n\t} else {\n\t\tif (!wantMod && event.metaKey) return false;\n\t}\n\n\treturn true;\n}\n","/**\n * DEFAULT_KEYMAP + resolveKeyCommand (P4 Phase 1).\n *\n * A keymap is an ordered Binding[]; `resolveKeyCommand` returns the FIRST matching\n * binding's command id (first-match-wins) or `null` when nothing matches — including\n * for an unbound PRINTABLE key, so the dispatch funnel can fall to the `editor.typeToEdit`\n * sentinel (the printable-key path is NOT in the keymap; the funnel routes it explicitly).\n *\n * Triggers come in three kinds — `key` (matched here via the copied matchKeyBinding),\n * `pointer` (gesture, wired in Stage B / Phase 2), and `native` (a raw DOM event name).\n * Pointer + native triggers are declared in the table for invariant completeness even\n * though only key triggers resolve through `resolveKeyCommand`.\n *\n * `Mod` is ctrl on win/linux, cmd on mac — encoded as the copied `'mod'` KeyModifier, so\n * matchKeyBinding's platform branch (isMac) picks the right physical key.\n */\n\nimport { kbd, matchKeyBinding, type KeyBinding } from './keybinding';\n\n/** A pointer gesture name (resolved by the pointer handlers, not the key funnel). */\nexport type PointerGesture = 'click' | 'shiftClick' | 'dblclick' | 'headerClick' | 'rowToggle' | 'rowToggleAll';\n\n/** What fires a command. */\nexport type Trigger =\n\t| { kind: 'key'; binding: KeyBinding }\n\t| { kind: 'pointer'; gesture: PointerGesture }\n\t| { kind: 'native'; event: string };\n\n/** A trigger -> command id mapping. */\nexport interface Binding {\n\ttrigger: Trigger;\n\tcommand: string;\n}\n\n/** key-trigger shorthand. */\nfunction key(binding: KeyBinding, command: string): Binding {\n\treturn { trigger: { kind: 'key', binding }, command };\n}\n\n/** pointer-trigger shorthand. */\nfunction pointer(gesture: PointerGesture, command: string): Binding {\n\treturn { trigger: { kind: 'pointer', gesture }, command };\n}\n\n/**\n * The default key + pointer + native bindings. Order matters for the key kind\n * (first-match-wins). matchKeyBinding is STRICT on modifiers, so the undo (Mod+Z) and\n * redo (Mod+Shift+Z) chords never alias even though they share the 'z' key.\n */\nexport const DEFAULT_KEYMAP: Binding[] = [\n\t// undo / redo\n\tkey(kbd('z', 'mod'), 'edit.undo'),\n\tkey(kbd('z', 'mod', 'shift'), 'edit.redo'),\n\tkey(kbd('y', 'mod'), 'edit.redo'),\n\n\t// select all\n\tkey(kbd('a', 'mod'), 'selection.all'),\n\n\t// clear cells (Delete / Backspace → null over the active range). The funnel bails\n\t// while an overlay editor is open, so these still edit text inside an editor.\n\tkey(kbd('Delete'), 'cell.clear'),\n\tkey(kbd('Backspace'), 'cell.clear'),\n\n\t// fill (Mod = Cmd/mac, Ctrl/win)\n\tkey(kbd('d', 'mod'), 'fill.down'),\n\tkey(kbd('r', 'mod'), 'fill.right'),\n\n\t// arrow move (plain)\n\tkey(kbd('ArrowUp'), 'cell.moveUp'),\n\tkey(kbd('ArrowDown'), 'cell.moveDown'),\n\tkey(kbd('ArrowLeft'), 'cell.moveLeft'),\n\tkey(kbd('ArrowRight'), 'cell.moveRight'),\n\n\t// arrow extend (shift)\n\tkey(kbd('ArrowUp', 'shift'), 'cell.extendUp'),\n\tkey(kbd('ArrowDown', 'shift'), 'cell.extendDown'),\n\tkey(kbd('ArrowLeft', 'shift'), 'cell.extendLeft'),\n\tkey(kbd('ArrowRight', 'shift'), 'cell.extendRight'),\n\n\t// absolute nav — base + ctrl/meta + shift variants all resolve to one command (the\n\t// command body branches on the payload via computeKeyNavTarget, matching the original).\n\tkey(kbd('Tab'), 'cell.navAbsolute'),\n\tkey(kbd('Tab', 'shift'), 'cell.navAbsolute'),\n\tkey(kbd('Home'), 'cell.navAbsolute'),\n\tkey(kbd('Home', 'mod'), 'cell.navAbsolute'),\n\tkey(kbd('End'), 'cell.navAbsolute'),\n\tkey(kbd('End', 'mod'), 'cell.navAbsolute'),\n\tkey(kbd('PageUp'), 'cell.navAbsolute'),\n\tkey(kbd('PageDown'), 'cell.navAbsolute'),\n\n\t// open editor at active cell\n\tkey(kbd('Enter'), 'editor.openActive'),\n\tkey(kbd('F2'), 'editor.openActive'),\n\n\t// pointer gestures (wired Stage B / Phase 2)\n\tpointer('click', 'cell.activate'),\n\tpointer('shiftClick', 'cell.extendToClicked'),\n\tpointer('dblclick', 'editor.open'),\n\tpointer('headerClick', 'header.sortToggle'),\n\tpointer('rowToggle', 'rowmarker.toggleRow'),\n\tpointer('rowToggleAll', 'rowmarker.toggleAll'),\n];\n\n/**\n * Resolve a KeyboardEvent to a command id via the keymap (first key-trigger match wins).\n * Returns `null` when no key binding matches — including unbound printable keys — so the\n * caller can fall to the `editor.typeToEdit` sentinel. Pointer / native triggers are\n * ignored here (they are not key events).\n */\nexport function resolveKeyCommand(event: KeyboardEvent, keymap: Binding[] = DEFAULT_KEYMAP): string | null {\n\tfor (const binding of keymap) {\n\t\tif (binding.trigger.kind !== 'key') continue;\n\t\tif (matchKeyBinding(event, binding.trigger.binding)) return binding.command;\n\t}\n\treturn null;\n}\n","/**\n * Sheets theme tokens.\n *\n * A small, semantic token set a host can override per light/dark mode, plus a\n * reader that lifts tokens off CSS custom properties. The native DOM grid styles\n * from CSS variables directly, so these tokens are the glide-free surface that\n * survived the canvas cutover (the old glide `Theme` mapping was removed).\n */\n\n/**\n * Semantic, composable theme tokens. A small surface a host can override per mode.\n */\nexport interface SheetsThemeTokens {\n\t/** Primary accent (selection, links, focus). */\n\taccent: string;\n\t/** Foreground rendered on top of `accent` (e.g. selected header text). */\n\taccentForeground: string;\n\t/** Base canvas / cell background. */\n\tbackground: string;\n\t/** Header / muted cell surface. */\n\tsurface: string;\n\t/** Hover / focused surface (one step from `surface`). */\n\tsurfaceMuted: string;\n\t/** Grid + header border color. */\n\tborder: string;\n\t/** Primary text color. */\n\ttext: string;\n\t/** Secondary (muted) text color. */\n\ttextMuted: string;\n\t/** Optional font stack; falls back to the default Inter-based stack. */\n\tfontFamily?: string;\n}\n\n/**\n * Host theme input: a partial token override keyed by mode (deep-merged over the\n * grid's defaults).\n */\nexport type SheetsThemeInput = Partial<Record<'light' | 'dark', Partial<SheetsThemeTokens>>>;\n\n/**\n * Read theme tokens off CSS custom properties on `el` (defaults to\n * `document.documentElement`). Only properties that resolve to a non-empty value\n * are returned, so the result is safe to deep-merge over a defaults object.\n */\nexport function tokensFromCssVars(\n\tel: Element | null = typeof document !== 'undefined' ? document.documentElement : null,\n): Partial<SheetsThemeTokens> {\n\tif (!el || typeof window === 'undefined') return {};\n\tconst cs = window.getComputedStyle(el);\n\tconst read = (name: string): string | undefined => {\n\t\tconst v = cs.getPropertyValue(name).trim();\n\t\treturn v.length > 0 ? v : undefined;\n\t};\n\n\tconst out: Partial<SheetsThemeTokens> = {};\n\tconst accent = read('--sheets-accent') ?? read('--primary');\n\tconst background = read('--background');\n\tconst border = read('--border');\n\tconst text = read('--foreground');\n\n\tif (accent !== undefined) out.accent = accent;\n\tif (background !== undefined) out.background = background;\n\tif (border !== undefined) out.border = border;\n\tif (text !== undefined) out.text = text;\n\treturn out;\n}\n","import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { RiAddLine, RiDatabaseLine, RiSearchLine } from '@remixicon/react';\nimport { ChevronRight } from 'lucide-react';\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { cn } from '../utils/cn';\nimport { Button } from '@constructive-io/ui/button';\nimport { Collapsible, CollapsibleTrigger } from '@constructive-io/ui/collapsible';\nimport { Input } from '@constructive-io/ui/input';\nimport { ProgressiveBlur } from '@constructive-io/ui/progressive-blur';\nimport { ScrollArea } from '@constructive-io/ui/scroll-area';\nimport { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@constructive-io/ui/tooltip';\n\nconst BLUR_HEIGHT_PERCENT = 0.28;\nconst BLUR_HEIGHT_MIN_PX = 64;\nconst BLUR_HEIGHT_MAX_PX = 140;\n\nexport type TableWithCategory = {\n\tname: string;\n\tcategory?: string;\n};\n\ninterface TableItemProps {\n\ttable: { value: string; label: string };\n\tactiveTable: string;\n\tonTableSelect: (tableName: string) => void;\n\t/** Ref to attach to this item (used for scroll-into-view on active item) */\n\titemRef?: React.RefObject<HTMLButtonElement | null>;\n}\n\nconst TableItem = memo(function TableItem({ table, activeTable, onTableSelect, itemRef }: TableItemProps) {\n\tconst isActive = activeTable === table.value;\n\n\treturn (\n\t\t<Button\n\t\t\tref={isActive ? itemRef : undefined}\n\t\t\taria-pressed={isActive}\n\t\t\tdata-testid='table-item'\n\t\t\tstatic\n\t\t\tsize='sm'\n\t\t\ttype='button'\n\t\t\tvariant='ghost'\n\t\t\tclassName={cn(\n\t\t\t\t'group relative my-1 flex h-8 w-full shrink items-center justify-between rounded-lg px-2 text-left text-xs font-normal transition-colors duration-150',\n\t\t\t\tisActive\n\t\t\t\t\t? 'bg-primary/10 text-foreground ring-primary/30 dark:bg-primary/15 dark:ring-primary/40 ring-1'\n\t\t\t\t\t: 'text-muted-foreground hover:text-foreground',\n\t\t\t)}\n\t\t\tonClick={() => onTableSelect(table.value)}\n\t\t>\n\t\t\t<span className='flex min-w-0 flex-1 items-center'>\n\t\t\t\t<Tooltip>\n\t\t\t\t\t<TooltipTrigger asChild>\n\t\t\t\t\t\t<span className='truncate text-xs'>{table.label}</span>\n\t\t\t\t\t</TooltipTrigger>\n\t\t\t\t\t<TooltipContent side='right' align='start'>\n\t\t\t\t\t\t<span className='text-xs font-medium'>{table.label}</span>\n\t\t\t\t\t</TooltipContent>\n\t\t\t\t</Tooltip>\n\t\t\t</span>\n\t\t</Button>\n\t);\n});\n\nexport interface TableSelectorProps {\n\ttables: string[] | TableWithCategory[];\n\tactiveTable: string;\n\tonTableChange: (table: string) => void;\n\tisLoading?: boolean;\n\t/** When true, scroll the active table into view and expand its section */\n\tshouldScrollToActive?: boolean;\n\t/** Optional callback when user clicks the \"New table\" button */\n\tonNewTable?: () => void;\n}\n\nexport const SheetsTableSelector = memo(function SheetsTableSelector({\n\ttables,\n\tactiveTable,\n\tonTableChange,\n\tisLoading = false,\n\tshouldScrollToActive = false,\n\tonNewTable,\n}: TableSelectorProps) {\n\tconst [searchQuery, setSearchQuery] = useState('');\n\tconst containerRef = useRef<HTMLDivElement>(null);\n\tconst [_containerHeight, setContainerHeight] = useState(0);\n\n\t// Local expand/collapse state (not persisted -- standalone component)\n\tconst [isExpanded, setIsExpanded] = useState(true);\n\n\t// Transform tables to internal format\n\tconst tableData = useMemo(() => {\n\t\treturn tables.map((table) => {\n\t\t\tconst isObject = typeof table === 'object';\n\t\t\tconst name = isObject ? table.name : table;\n\t\t\treturn {\n\t\t\t\tvalue: name,\n\t\t\t\tlabel: name,\n\t\t\t};\n\t\t});\n\t}, [tables]);\n\n\t// Apply search filter\n\tconst filteredTables = useMemo(() => {\n\t\tif (!searchQuery) return tableData;\n\t\treturn tableData.filter((table) => table.label.toLowerCase().includes(searchQuery.toLowerCase()));\n\t}, [tableData, searchQuery]);\n\n\t// Measure container height on mount and resize\n\tuseEffect(() => {\n\t\tconst container = containerRef.current;\n\t\tif (!container) return;\n\n\t\tconst updateHeight = () => {\n\t\t\tsetContainerHeight(container.clientHeight);\n\t\t};\n\n\t\tupdateHeight();\n\n\t\tconst resizeObserver = new ResizeObserver(updateHeight);\n\t\tresizeObserver.observe(container);\n\n\t\treturn () => resizeObserver.disconnect();\n\t}, []);\n\n\tconst handleTableSelect = useCallback(\n\t\t(tableName: string) => {\n\t\t\tonTableChange(tableName);\n\t\t},\n\t\t[onTableChange],\n\t);\n\n\tconst handleNewTable = useCallback(() => {\n\t\tif (onNewTable) {\n\t\t\tonNewTable();\n\t\t}\n\t}, [onNewTable]);\n\n\tif (isLoading) {\n\t\treturn (\n\t\t\t<div data-part-id='sheets-table-selector-loading' className='bg-background flex h-full flex-col'>\n\t\t\t\t{/* Header skeleton */}\n\t\t\t\t<div className='border-border/60 flex-shrink-0 border-b p-6'>\n\t\t\t\t\t<div className='bg-muted mb-6 h-8 w-32 animate-pulse rounded'></div>\n\n\t\t\t\t\t{/* Schema selector skeleton */}\n\t\t\t\t\t<div className='bg-muted mb-4 h-10 w-full animate-pulse rounded-md'></div>\n\n\t\t\t\t\t{/* New table button skeleton */}\n\t\t\t\t\t<div className='bg-muted mb-4 h-10 w-full animate-pulse rounded-md'></div>\n\n\t\t\t\t\t{/* Search input skeleton */}\n\t\t\t\t\t<div className='bg-muted h-10 w-full animate-pulse rounded-md'></div>\n\t\t\t\t</div>\n\n\t\t\t\t{/* Table list skeleton */}\n\t\t\t\t<div className='flex-1 space-y-2 p-6'>\n\t\t\t\t\t{[1, 2, 3, 4, 5].map((i) => (\n\t\t\t\t\t\t<div key={i} className='flex items-center justify-between rounded-lg border p-3'>\n\t\t\t\t\t\t\t<div className='flex items-center gap-3'>\n\t\t\t\t\t\t\t\t<div className='bg-muted h-4 w-4 animate-pulse rounded'></div>\n\t\t\t\t\t\t\t\t<div className='bg-muted h-4 w-24 animate-pulse rounded'></div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div className='bg-muted h-6 w-20 animate-pulse rounded-full'></div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t))}\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t);\n\t}\n\n\treturn (\n\t\t<TooltipProvider delayDuration={150}>\n\t\t\t<div\n\t\t\t\tdata-part-id='sheets-table-selector'\n\t\t\t\tclassName='bg-background flex h-full max-h-[calc(100vh-4rem)] flex-col'\n\t\t\t>\n\t\t\t\t{/* Header */}\n\t\t\t\t<div className='flex-shrink-0 py-4'>\n\t\t\t\t\t<div className='flex flex-col gap-2 pr-2 pb-2'>\n\t\t\t\t\t\t{/* New table button */}\n\t\t\t\t\t\t<Button onClick={handleNewTable} className='h-8 w-full justify-start gap-2' variant='outline'>\n\t\t\t\t\t\t\t<RiAddLine size={16} />\n\t\t\t\t\t\t\tNew table\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t{/* Search input */}\n\t\t\t\t\t<div className='relative pr-2'>\n\t\t\t\t\t\t<RiSearchLine\n\t\t\t\t\t\t\tsize={16}\n\t\t\t\t\t\t\tclassName='text-muted-foreground absolute top-1/2 left-3 -translate-y-1/2 transform'\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t<Input\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\tplaceholder='Search tables...'\n\t\t\t\t\t\t\tvalue={searchQuery}\n\t\t\t\t\t\t\tonChange={(e) => setSearchQuery(e.target.value)}\n\t\t\t\t\t\t\tclassName='pl-10'\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\n\t\t\t\t{/* Table list */}\n\t\t\t\t<div\n\t\t\t\t\tref={containerRef}\n\t\t\t\t\tdata-part-id='table-selector-table-list'\n\t\t\t\t\tclassName='mt-4 flex min-h-0 flex-1 flex-col gap-2 overflow-hidden pr-2'\n\t\t\t\t>\n\t\t\t\t\t{filteredTables.length === 0 ? (\n\t\t\t\t\t\t<div className='flex flex-col items-center justify-center py-12 text-center'>\n\t\t\t\t\t\t\t<div className='bg-muted mb-4 flex h-12 w-12 items-center justify-center rounded-full'>\n\t\t\t\t\t\t\t\t<RiSearchLine size={20} className='text-muted-foreground' />\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<p className='text-muted-foreground mb-1 text-sm font-medium'>No tables found</p>\n\t\t\t\t\t\t\t<p className='text-muted-foreground/80 text-xs'>\n\t\t\t\t\t\t\t\t{searchQuery ? 'Try adjusting your search terms' : 'No tables available in this schema'}\n\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t) : (\n\t\t\t\t\t\t<SheetsTableListByCategory\n\t\t\t\t\t\t\ttitle='Tables'\n\t\t\t\t\t\t\ttables={filteredTables}\n\t\t\t\t\t\t\tactiveTable={activeTable}\n\t\t\t\t\t\t\tisExpanded={isExpanded}\n\t\t\t\t\t\t\tonToggleExpand={() => setIsExpanded((prev) => !prev)}\n\t\t\t\t\t\t\tonTableSelect={handleTableSelect}\n\t\t\t\t\t\t\temptyMessage='No tables yet'\n\t\t\t\t\t\t\thasSearchTerm={searchQuery.length > 0}\n\t\t\t\t\t\t\tshouldScrollToActive={shouldScrollToActive}\n\t\t\t\t\t\t/>\n\t\t\t\t\t)}\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</TooltipProvider>\n\t);\n});\n\ninterface TableListByCategoryProps {\n\ttitle: string;\n\ttables: { value: string; label: string }[];\n\tactiveTable: string;\n\tisExpanded: boolean;\n\tonToggleExpand: () => void;\n\tonTableSelect: (tableName: string) => void;\n\temptyMessage?: string;\n\thasSearchTerm?: boolean;\n\tmaxContentHeight?: number;\n\t/** When true, scroll the active table into view */\n\tshouldScrollToActive?: boolean;\n}\n\nfunction SheetsTableListByCategory({\n\ttitle,\n\ttables,\n\tactiveTable,\n\tisExpanded,\n\tonToggleExpand,\n\tonTableSelect,\n\temptyMessage = 'No tables',\n\thasSearchTerm = false,\n\tmaxContentHeight,\n\tshouldScrollToActive = false,\n}: TableListByCategoryProps) {\n\tconst scrollRef = useRef<HTMLDivElement>(null);\n\tconst activeItemRef = useRef<HTMLButtonElement>(null);\n\tconst [showBottomBlur, setShowBottomBlur] = useState(false);\n\tconst [scrollAreaHeight, setScrollAreaHeight] = useState(0);\n\n\tconst hasSelectedItem = activeTable ? tables.some((t) => t.value === activeTable) : false;\n\n\t// Scroll active item into view when requested\n\tuseEffect(() => {\n\t\tif (!shouldScrollToActive || !isExpanded || !activeItemRef.current) return;\n\n\t\t// Wait for animation to complete before scrolling\n\t\tconst timer = setTimeout(() => {\n\t\t\tactiveItemRef.current?.scrollIntoView({\n\t\t\t\tbehavior: 'smooth',\n\t\t\t\tblock: 'center',\n\t\t\t});\n\t\t}, 350); // Match the collapsible animation duration\n\n\t\treturn () => clearTimeout(timer);\n\t}, [shouldScrollToActive, isExpanded, activeTable]);\n\n\tconst handleScroll = useCallback((event: React.UIEvent<HTMLDivElement>) => {\n\t\tconst el = event.currentTarget;\n\t\tconst atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 1;\n\t\tsetShowBottomBlur(!(atBottom || el.scrollHeight <= el.clientHeight));\n\t}, []);\n\n\tuseEffect(() => {\n\t\tconst el = scrollRef.current;\n\t\tif (!el) return;\n\t\tconst atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 1;\n\t\tsetShowBottomBlur(!(atBottom || el.scrollHeight <= el.clientHeight));\n\t}, [tables.length, isExpanded, maxContentHeight]);\n\n\tuseEffect(() => {\n\t\tconst el = scrollRef.current;\n\t\tif (!el) return;\n\n\t\tconst update = () => setScrollAreaHeight(el.clientHeight);\n\t\tupdate();\n\n\t\tconst ro = new ResizeObserver(update);\n\t\tro.observe(el);\n\t\treturn () => ro.disconnect();\n\t}, [isExpanded, maxContentHeight]);\n\n\tconst blurHeight = useMemo(() => {\n\t\tif (!scrollAreaHeight) return '28%';\n\t\tconst percentPx = scrollAreaHeight * BLUR_HEIGHT_PERCENT;\n\t\tconst clamped = Math.min(scrollAreaHeight, Math.min(BLUR_HEIGHT_MAX_PX, Math.max(BLUR_HEIGHT_MIN_PX, percentPx)));\n\t\treturn `${Math.round(clamped)}px`;\n\t}, [scrollAreaHeight]);\n\n\t// Calculate max-height style\n\tconst scrollAreaStyle = maxContentHeight !== undefined ? { maxHeight: `${maxContentHeight}px` } : undefined;\n\n\treturn (\n\t\t<Collapsible open={isExpanded} onOpenChange={onToggleExpand} className='flex min-h-0 shrink-0 flex-col'>\n\t\t\t<CollapsibleTrigger\n\t\t\t\tclassName={cn(\n\t\t\t\t\t'group flex w-full items-center gap-2 rounded-lg py-1.5 pr-2 pl-1 transition-colors duration-150',\n\t\t\t\t\t'bg-muted hover:bg-muted/50',\n\t\t\t\t\tisExpanded && 'bg-muted/50',\n\t\t\t\t)}\n\t\t\t>\n\t\t\t\t<motion.div\n\t\t\t\t\tanimate={{ rotate: isExpanded ? 90 : 0 }}\n\t\t\t\t\ttransition={{ type: 'spring', stiffness: 400, damping: 25 }}\n\t\t\t\t\tclassName='flex shrink-0 items-center justify-center'\n\t\t\t\t>\n\t\t\t\t\t<ChevronRight className='text-muted-foreground/60 h-3.5 w-3.5' />\n\t\t\t\t</motion.div>\n\t\t\t\t<span className='text-muted-foreground text-xs font-medium'>{title}</span>\n\t\t\t\t<span className='ml-auto flex items-center gap-1.5'>\n\t\t\t\t\t{!isExpanded && hasSelectedItem && (\n\t\t\t\t\t\t<span className='bg-primary/50 h-1.5 w-1.5 rounded-full' aria-label='Contains selected item' />\n\t\t\t\t\t)}\n\t\t\t\t\t<span className='text-muted-foreground/70 text-[10px] tabular-nums'>{tables.length}</span>\n\t\t\t\t</span>\n\t\t\t</CollapsibleTrigger>\n\n\t\t\t<AnimatePresence initial={false}>\n\t\t\t\t{isExpanded && (\n\t\t\t\t\t<motion.div\n\t\t\t\t\t\tdata-testid={`collapsible-content-${title}`}\n\t\t\t\t\t\tinitial={{ height: 0, opacity: 0 }}\n\t\t\t\t\t\tanimate={{\n\t\t\t\t\t\t\theight: 'auto',\n\t\t\t\t\t\t\topacity: 1,\n\t\t\t\t\t\t\ttransition: {\n\t\t\t\t\t\t\t\theight: { type: 'spring', stiffness: 500, damping: 40, mass: 0.8 },\n\t\t\t\t\t\t\t\topacity: { duration: 0.2, ease: 'easeOut' },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}}\n\t\t\t\t\t\texit={{\n\t\t\t\t\t\t\theight: 0,\n\t\t\t\t\t\t\topacity: 0,\n\t\t\t\t\t\t\ttransition: {\n\t\t\t\t\t\t\t\theight: { type: 'spring', stiffness: 500, damping: 40, mass: 0.8 },\n\t\t\t\t\t\t\t\topacity: { duration: 0.15, ease: 'easeIn' },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tclassName='min-h-0 overflow-hidden'\n\t\t\t\t\t>\n\t\t\t\t\t\t{tables.length > 0 ? (\n\t\t\t\t\t\t\t<div className='relative mt-2 min-h-0'>\n\t\t\t\t\t\t\t\t<ScrollArea\n\t\t\t\t\t\t\t\t\tref={scrollRef}\n\t\t\t\t\t\t\t\t\tonScroll={handleScroll}\n\t\t\t\t\t\t\t\t\tstyle={scrollAreaStyle}\n\t\t\t\t\t\t\t\t\tclassName='scrollbar-neutral-thin min-h-0'\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<div className='space-y-0.5 pr-1 pb-2 pl-1'>\n\t\t\t\t\t\t\t\t\t\t{tables.map((table) => (\n\t\t\t\t\t\t\t\t\t\t\t<TableItem\n\t\t\t\t\t\t\t\t\t\t\t\tkey={table.value}\n\t\t\t\t\t\t\t\t\t\t\t\ttable={table}\n\t\t\t\t\t\t\t\t\t\t\t\tactiveTable={activeTable}\n\t\t\t\t\t\t\t\t\t\t\t\tonTableSelect={onTableSelect}\n\t\t\t\t\t\t\t\t\t\t\t\titemRef={table.value === activeTable ? activeItemRef : undefined}\n\t\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</ScrollArea>\n\t\t\t\t\t\t\t\t{showBottomBlur && tables.length > 3 && (\n\t\t\t\t\t\t\t\t\t<ProgressiveBlur position='bottom' height={blurHeight} surface='background' intensity={0.22} />\n\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t<div className='flex flex-col items-center justify-center py-6 text-center'>\n\t\t\t\t\t\t\t\t<div className='bg-muted mb-2 flex h-10 w-10 items-center justify-center rounded-full'>\n\t\t\t\t\t\t\t\t\t{hasSearchTerm ? (\n\t\t\t\t\t\t\t\t\t\t<RiSearchLine className='text-muted-foreground h-5 w-5' />\n\t\t\t\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t\t\t\t<RiDatabaseLine className='text-muted-foreground h-5 w-5' />\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<p className='text-muted-foreground text-xs'>{emptyMessage}</p>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t)}\n\t\t\t\t\t</motion.div>\n\t\t\t\t)}\n\t\t\t</AnimatePresence>\n\t\t</Collapsible>\n\t);\n}\n","// Public contract for defining and overriding cell types.\n//\n// A CellTypeDefinition unifies DETECTION (`match`) and native DISPLAY\n// (`toSheetsCell` / `cell`) and native EDITING (`editorComponent`) in one object.\n// Consumers register them per-instance via `<SheetsProvider config={{ plugins }}>`\n// or `<Sheets cellTypes>`; a def whose `typeKey` matches a built-in overrides that\n// built-in for this grid, and a def with a `match()` adds detection. Any concern\n// left undefined falls back to the built-in behavior, so a def may override just\n// the editor, just the display, or add a brand-new type end-to-end.\n\nimport type { CellCategory } from './types';\n// Type-only imports (erased at runtime) — avoids a cell-types -> grid cycle.\nimport type { CellCreationMetadata } from '../grid/grid-cell-types';\nimport type { SheetsCell } from '../cell-model/sheets-cell';\nimport type { CellProps } from '../cell-model/cell-props';\nimport type { EditorProps } from '../grid-dom/editors/editor-props';\n\n/** Schema-only inputs used to DETECT a cell type. Never the runtime value. */\nexport interface CellTypeMatchInput {\n\tgqlType: string;\n\tisArray: boolean;\n\tpgAlias?: string | null;\n\tpgType?: string | null;\n\tsubtype?: string | null;\n\tfieldName?: string;\n}\n\n/** Context handed to `toSheetsCell` so a definition can build the neutral cell.\n * Geometry uses the built-in fallback, so no `createGeometry` callback is needed. */\nexport interface SheetsCellRenderContext {\n\tmetadata: CellCreationMetadata;\n}\n\nexport interface CellTypeDefinition<TValue = unknown> {\n\t/** Stable key. A def whose typeKey equals a built-in (e.g. 'relation') overrides it. */\n\ttypeKey: string;\n\tcategory?: CellCategory;\n\t/** Toolbar / type-picker icon. */\n\ticon?: React.ComponentType<{ size?: number }>;\n\tdefaultWidth?: number;\n\tsupportsInlineEdit?: boolean;\n\t/** DETECTION (schema-only). Highest-priority match wins; omit for typeKey-only. */\n\tmatch?: (meta: CellTypeMatchInput) => boolean;\n\t/** Native DISPLAY. Build the neutral SheetsCell. Omit to keep the built-in renderer. */\n\ttoSheetsCell?: (value: TValue, ctx: SheetsCellRenderContext) => SheetsCell;\n\t/** Native cell COMPONENT override (the slot target). Omit to keep the built-in view. */\n\tcell?: React.ComponentType<CellProps>;\n\t/** Native EDITOR override (DOM portal overlay). Omit to keep the built-in native editor. */\n\teditorComponent?: React.ComponentType<EditorProps>;\n\t/** Value -> display/copy/export string. */\n\tformat?: (value: TValue) => string;\n\tdefaultValue?: () => TValue;\n}\n\n/** Identity helper that pins the generic — `defineCellType<number>({ ... })`. */\nexport function defineCellType<T = unknown>(def: CellTypeDefinition<T>): CellTypeDefinition<T> {\n\treturn def;\n}\n\n/** A named bundle of cell types, registered via `SheetsConfig.plugins`. */\nexport interface CellTypePlugin {\n\tname: string;\n\tcellTypes: CellTypeDefinition<any>[];\n}\n\nexport type { CellCreationMetadata };\n","export function createMetadataHash(value: unknown): string {\n\tconst serialized = JSON.stringify(value, stableReplacer);\n\tlet hash = 0;\n\tfor (let index = 0; index < serialized.length; index += 1) {\n\t\thash = (hash * 33) ^ serialized.charCodeAt(index);\n\t}\n\n\treturn `h${(hash >>> 0).toString(16)}`;\n}\n\nfunction stableReplacer(_key: string, value: unknown): unknown {\n\tif (value && typeof value === 'object' && !Array.isArray(value)) {\n\t\treturn Object.keys(value)\n\t\t\t.sort()\n\t\t\t.reduce<Record<string, unknown>>((acc, key) => {\n\t\t\t\tacc[key] = (value as Record<string, unknown>)[key];\n\t\t\t\treturn acc;\n\t\t\t}, {});\n\t}\n\treturn value;\n}\n","import { mapToFrontendCellType } from '../cell-types/type-mapping';\n\nimport { createMetadataHash } from './metadata-hash';\nimport type {\n\tBuildFormSpecOptions,\n\tDynamicFormSpec,\n\tMetaField,\n\tMetaTable,\n\tScalarFieldKind,\n\tScalarFieldSpec,\n} from './types';\n\nconst SCALAR_CELL_TYPE_TO_KIND: Partial<Record<string, ScalarFieldKind>> = {\n\ttext: 'text',\n\ttextarea: 'multiline',\n\tcitext: 'text',\n\tbpchar: 'text',\n\temail: 'email',\n\turl: 'url',\n\tphone: 'phone',\n\tuuid: 'uuid',\n\tinet: 'inet',\n\tnumber: 'number',\n\tinteger: 'integer',\n\tsmallint: 'smallint',\n\tdecimal: 'decimal',\n\tcurrency: 'currency',\n\tpercentage: 'percentage',\n\tboolean: 'boolean',\n\tbit: 'bit',\n\tdate: 'date',\n\tdatetime: 'datetime',\n\ttime: 'time',\n\ttimestamptz: 'timestamptz',\n\tjson: 'json',\n\tjsonb: 'json',\n\ttsvector: 'tsvector',\n};\n\nconst HUMAN_CASE_REGEX = /([a-z0-9])([A-Z])/g;\n\nexport function buildScalarFormSpec(metaTable: MetaTable, options: BuildFormSpecOptions = {}): DynamicFormSpec | null {\n\tconst fields: ScalarFieldSpec[] = [];\n\tconst uniqueFieldSet = collectSingleFieldUniqueNames(metaTable);\n\tconst primaryFieldSet = collectSingleFieldPrimaryNames(metaTable);\n\n\tfor (const field of metaTable.fields ?? []) {\n\t\tif (!field) continue;\n\n\t\tconst spec = createScalarFieldSpec(field, options, uniqueFieldSet, primaryFieldSet);\n\t\tif (!spec) continue;\n\n\t\tfields.push(spec);\n\t}\n\n\tif (fields.length === 0) {\n\t\treturn null;\n\t}\n\n\tconst versionHash = createMetadataHash({\n\t\ttable: metaTable.name,\n\t\tfields: fields.map((f) => ({\n\t\t\tname: f.name,\n\t\t\tkind: f.kind,\n\t\t\tnullable: f.nullable,\n\t\t\tmetadata: f.metadata,\n\t\t\tmaxLength: f.maxLength,\n\t\t\tminLength: f.minLength,\n\t\t\tminimum: f.minimum,\n\t\t\tmaximum: f.maximum,\n\t\t\tenumValues: f.enumValues,\n\t\t})),\n\t});\n\n\treturn {\n\t\ttableName: metaTable.name,\n\t\tversionHash,\n\t\tfields,\n\t};\n}\n\nexport function findTableFormSpec(\n\tmeta: MetaTable[] | null | undefined,\n\ttableName: string,\n\toptions: BuildFormSpecOptions = {},\n): DynamicFormSpec | null {\n\tif (!meta) return null;\n\tconst table = meta.find((item) => item?.name === tableName);\n\tif (!table) return null;\n\treturn buildScalarFormSpec(table, options);\n}\n\nfunction createScalarFieldSpec(\n\tmetaField: MetaField,\n\toptions: BuildFormSpecOptions,\n\tuniqueFields: Set<string>,\n\tprimaryFields: Set<string>,\n): ScalarFieldSpec | null {\n\tconst { multilineFields } = options;\n\tconst cellType = mapToFrontendCellType({\n\t\tgqlType: metaField.type.gqlType,\n\t\tisArray: metaField.type.isArray,\n\t\tpgAlias: metaField.type.pgAlias,\n\t\tpgType: metaField.type.pgType,\n\t\tsubtype: metaField.type.subtype ?? undefined,\n\t\tencoding: metaField.type.encoding,\n\t});\n\n\tif (metaField.type.isArray) {\n\t\treturn null;\n\t}\n\n\tlet kind = SCALAR_CELL_TYPE_TO_KIND[cellType];\n\n\tif (!kind && cellType === 'text' && multilineFields?.has(metaField.name)) {\n\t\tkind = 'multiline';\n\t}\n\n\tif (!kind) {\n\t\treturn null;\n\t}\n\n\tconst nullable = isFieldNullable(metaField);\n\tconst { maxLength, numericPrecision, numericScale } = extractTypmodConstraints(metaField);\n\n\tconst label = humanize(metaField.name);\n\tconst description = buildDescription(metaField);\n\n\tconst spec: ScalarFieldSpec = {\n\t\tname: metaField.name,\n\t\tlabel,\n\t\tdescription,\n\t\tkind,\n\t\tnullable,\n\t\tmetadata: {\n\t\t\tcellType,\n\t\t\tgqlType: metaField.type.gqlType,\n\t\t\tpgAlias: metaField.type.pgAlias ?? undefined,\n\t\t\tpgType: metaField.type.pgType ?? undefined,\n\t\t\tsubtype: metaField.type.subtype ?? undefined,\n\t\t\ttypmod: metaField.type.typmod ?? undefined,\n\t\t\tencoding: metaField.type.encoding ?? undefined,\n\t\t},\n\t\tconstraints: {\n\t\t\tisUnique: uniqueFields.has(metaField.name) || undefined,\n\t\t\tisPrimaryKey: primaryFields.has(metaField.name) || undefined,\n\t\t},\n\t};\n\n\tif (metaField.enumValues?.values?.length) {\n\t\tspec.enumValues = [...metaField.enumValues.values];\n\t}\n\n\tif (maxLength != null) {\n\t\tspec.maxLength = maxLength;\n\t}\n\n\tif (numericPrecision != null) {\n\t\tspec.numericPrecision = numericPrecision;\n\t}\n\n\tif (numericScale != null) {\n\t\tspec.numericScale = numericScale;\n\t}\n\n\tif (\n\t\tkind === 'decimal' ||\n\t\tkind === 'number' ||\n\t\tkind === 'integer' ||\n\t\tkind === 'smallint' ||\n\t\tkind === 'currency' ||\n\t\tkind === 'percentage'\n\t) {\n\t\tconst { minimum, maximum } = extractNumericCheckBounds(metaField);\n\t\tif (minimum != null) spec.minimum = minimum;\n\t\tif (maximum != null) spec.maximum = maximum;\n\t}\n\n\tif (kind === 'json') {\n\t\tspec.description = description ?? 'JSON value';\n\t}\n\n\tif (kind === 'boolean') {\n\t\tspec.defaultValue = false;\n\t}\n\n\treturn spec;\n}\n\nfunction buildDescription(metaField: MetaField): string | undefined {\n\tif (metaField.description) return metaField.description;\n\tconst details: string[] = [];\n\tconst { pgAlias, pgType, subtype } = metaField.type;\n\n\tif (pgAlias && pgAlias !== pgType) {\n\t\tdetails.push(pgAlias);\n\t}\n\tif (pgType) {\n\t\tdetails.push(pgType);\n\t}\n\tif (subtype) {\n\t\tdetails.push(subtype);\n\t}\n\n\treturn details.length > 0 ? details.join(' • ') : undefined;\n}\n\nfunction humanize(name: string): string {\n\treturn name.replace(HUMAN_CASE_REGEX, '$1 $2').replace(/^./, (str) => str.toUpperCase());\n}\n\nfunction isFieldNullable(metaField: MetaField): boolean {\n\tif (metaField.isNotNull === true || metaField.type.isNotNull === true) return false;\n\tconst gqlType = metaField.type.gqlType;\n\tif (gqlType.endsWith('!')) return false;\n\t// Note: modifier is a numeric code from PostgreSQL, not a string enum\n\t// The gqlType check above is the primary indicator of non-nullability\n\treturn true;\n}\n\nfunction extractTypmodConstraints(metaField: MetaField): {\n\tmaxLength?: number;\n\tnumericPrecision?: number;\n\tnumericScale?: number;\n} {\n\tconst typmod = metaField.type.typmod ?? null;\n\tconst pgType = metaField.type.pgType?.toLowerCase();\n\n\tif (typmod == null || typmod < 0) {\n\t\treturn {};\n\t}\n\n\tif (pgType === 'varchar' || pgType === 'character varying' || pgType === 'bpchar' || pgType === 'character') {\n\t\treturn { maxLength: Math.max(0, typmod - 4) };\n\t}\n\n\tif (pgType === 'numeric' || pgType === 'decimal') {\n\t\tconst precision = ((typmod - 4) >> 16) & 65535;\n\t\tconst scale = (typmod - 4) & 65535;\n\t\treturn {\n\t\t\tnumericPrecision: precision || undefined,\n\t\t\tnumericScale: scale || undefined,\n\t\t};\n\t}\n\n\treturn {};\n}\n\nfunction extractNumericCheckBounds(_metaField: MetaField): { minimum?: number; maximum?: number } {\n\t// Placeholder for future enhancements: currently return empty bounds.\n\t// Backend check constraints can be parsed here when the metadata exposes readable expressions.\n\treturn {};\n}\n\nfunction collectSingleFieldUniqueNames(metaTable: MetaTable): Set<string> {\n\tconst result = new Set<string>();\n\n\tfor (const constraint of metaTable.uniqueConstraints ?? []) {\n\t\tif (!constraint || !constraint.fields) continue;\n\t\tconst fields = constraint.fields.filter((field): field is MetaField => Boolean(field));\n\t\tif (fields.length === 1) {\n\t\t\tresult.add(fields[0].name);\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction collectSingleFieldPrimaryNames(metaTable: MetaTable): Set<string> {\n\tconst result = new Set<string>();\n\tfor (const constraint of metaTable.primaryKeyConstraints ?? []) {\n\t\tif (!constraint) continue;\n\t\tconst fields = constraint.fields?.filter((field): field is MetaField => Boolean(field));\n\t\tif (fields && fields.length === 1) {\n\t\t\tresult.add(fields[0].name);\n\t\t}\n\t}\n\treturn result;\n}\n","import { z } from 'zod';\n\nimport type { DynamicFormSpec, ScalarFieldSpec } from './types';\n\nconst schemaCache = new Map<string, z.ZodObject<Record<string, z.ZodTypeAny>>>();\n\nexport function buildZodSchema(spec: DynamicFormSpec): z.ZodObject<Record<string, z.ZodTypeAny>> {\n\tconst cached = schemaCache.get(spec.versionHash);\n\tif (cached) {\n\t\treturn cached;\n\t}\n\n\tconst shape: Record<string, z.ZodTypeAny> = {};\n\n\tfor (const field of spec.fields) {\n\t\tshape[field.name] = buildFieldSchema(field);\n\t}\n\n\tconst schema = z.object(shape);\n\tschemaCache.set(spec.versionHash, schema);\n\treturn schema;\n}\n\nfunction buildFieldSchema(field: ScalarFieldSpec): z.ZodTypeAny {\n\tlet baseSchema: z.ZodTypeAny;\n\tlet isStringSchema = false;\n\n\tswitch (field.kind) {\n\t\tcase 'email':\n\t\t\tbaseSchema = z.string({ error: 'Email is required' }).email('Invalid email address');\n\t\t\tisStringSchema = true;\n\t\t\tbreak;\n\t\tcase 'url':\n\t\t\tbaseSchema = z.string({ error: 'URL is required' }).url('Invalid URL');\n\t\t\tisStringSchema = true;\n\t\t\tbreak;\n\t\tcase 'phone':\n\t\t\tbaseSchema = z\n\t\t\t\t.string({ error: 'Phone number is required' })\n\t\t\t\t.refine((value) => /^\\+?[0-9\\-()\\s]+$/.test(value), { message: 'Invalid phone number' });\n\t\t\tbreak;\n\t\tcase 'uuid':\n\t\t\tbaseSchema = z.string({ error: 'UUID is required' }).uuid('Invalid UUID');\n\t\t\tisStringSchema = true;\n\t\t\tbreak;\n\t\tcase 'inet':\n\t\t\tbaseSchema = z\n\t\t\t\t.string({ error: 'IP address is required' })\n\t\t\t\t.refine((value) => isValidInet(value), { message: 'Invalid IP address' });\n\t\t\tbreak;\n\t\tcase 'boolean':\n\t\t\tbaseSchema = z.preprocess(\n\t\t\t\t(value) => {\n\t\t\t\t\tif (typeof value === 'string') {\n\t\t\t\t\t\tif (value === 'true') return true;\n\t\t\t\t\t\tif (value === 'false') return false;\n\t\t\t\t\t}\n\t\t\t\t\treturn value;\n\t\t\t\t},\n\t\t\t\tz.boolean({ error: 'Required' }),\n\t\t\t);\n\t\t\tbreak;\n\t\tcase 'bit':\n\t\t\tbaseSchema = z.union([z.literal('0'), z.literal('1')]);\n\t\t\tbreak;\n\t\tcase 'integer':\n\t\tcase 'smallint':\n\t\tcase 'number':\n\t\tcase 'decimal':\n\t\tcase 'currency':\n\t\tcase 'percentage':\n\t\t\tbaseSchema = buildNumericSchema(field);\n\t\t\tbreak;\n\t\tcase 'date':\n\t\tcase 'datetime':\n\t\tcase 'timestamptz':\n\t\tcase 'time':\n\t\t\tbaseSchema = z\n\t\t\t\t.string({ error: 'Required' })\n\t\t\t\t.refine((value) => value.length > 0, { message: 'Required' });\n\t\t\tbreak;\n\t\tcase 'json':\n\t\t\tbaseSchema = z\n\t\t\t\t.string({ error: 'JSON is required' })\n\t\t\t\t.superRefine((value, ctx) => {\n\t\t\t\t\tif (value === '' && field.nullable) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tJSON.parse(value);\n\t\t\t\t} catch (_error) {\n\t\t\t\t\t\tctx.addIssue({\n\t\t\t\t\t\t\tcode: z.ZodIssueCode.custom,\n\t\t\t\t\t\t\tmessage: 'Invalid JSON',\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.transform((value) => {\n\t\t\t\t\tif (value === '') {\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\treturn JSON.parse(value);\n\t\t\t\t});\n\t\t\tbreak;\n\t\tcase 'tsvector':\n\t\tcase 'multiline':\n\t\tcase 'text':\n\t\tdefault:\n\t\t\tbaseSchema = z.string({ error: 'Required' });\n\t\t\tisStringSchema = true;\n\t\t\tbreak;\n\t}\n\n\t// Apply string constraints (tracked via isStringSchema flag for zod v4 compat)\n\tif (isStringSchema) {\n\t\tif ('maxLength' in field && typeof field.maxLength === 'number') {\n\t\t\tbaseSchema = (baseSchema as z.ZodString).max(field.maxLength, `Must be at most ${field.maxLength} characters`);\n\t\t}\n\n\t\tif ('minLength' in field && typeof field.minLength === 'number') {\n\t\t\tbaseSchema = (baseSchema as z.ZodString).min(field.minLength, `Must be at least ${field.minLength} characters`);\n\t\t}\n\t}\n\n\tif (field.enumValues && field.enumValues.length > 0) {\n\t\tbaseSchema = z.enum(field.enumValues as [string, ...string[]]);\n\t}\n\n\tif (!field.nullable) {\n\t\treturn baseSchema;\n\t}\n\n\tif (field.kind === 'json') {\n\t\treturn baseSchema.optional().nullable();\n\t}\n\n\treturn baseSchema.nullable().optional();\n}\n\nfunction buildNumericSchema(field: ScalarFieldSpec): z.ZodTypeAny {\n\t// Build inner number schema with all constraints\n\tconst preprocessFn = (value: unknown) => {\n\t\tif (value === '' || value === null || value === undefined) {\n\t\t\treturn value;\n\t\t}\n\t\tif (typeof value === 'number') return value;\n\t\tif (typeof value === 'string') {\n\t\t\tconst parsed = Number(value);\n\t\t\treturn Number.isNaN(parsed) ? value : parsed;\n\t\t}\n\t\treturn value;\n\t};\n\n\tlet innerSchema = z.number({\n\t\terror: 'Must be a valid number',\n\t});\n\n\t// Apply integer constraint\n\tif (field.kind === 'integer' || field.kind === 'smallint') {\n\t\tinnerSchema = innerSchema.int('Must be an integer');\n\t}\n\n\t// Apply range constraints\n\tif (field.kind === 'smallint') {\n\t\tinnerSchema = innerSchema.min(-32768, 'Must be >= -32768').max(32767, 'Must be <= 32767');\n\t} else {\n\t\tif (typeof field.minimum === 'number') {\n\t\t\tinnerSchema = innerSchema.min(field.minimum, `Must be >= ${field.minimum}`);\n\t\t}\n\n\t\tif (typeof field.maximum === 'number') {\n\t\t\tinnerSchema = innerSchema.max(field.maximum, `Must be <= ${field.maximum}`);\n\t\t}\n\t}\n\n\treturn z.preprocess(preprocessFn, innerSchema);\n}\n\nfunction isValidInet(value: string): boolean {\n\tconst ipv4 = /^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$/;\n\tconst ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::1)$/;\n\treturn ipv4.test(value) || ipv6.test(value);\n}\n","import * as React from 'react';\n\nimport { useSheetsTable } from '../hooks/use-sheets-table';\nimport type { SheetsRowIdentifier } from '../row-identity';\n\nexport interface DynamicMutationResult<TData = unknown> {\n\tsubmit: (values: Record<string, unknown>) => Promise<TData | null>;\n\tisSubmitting: boolean;\n\terror: Error | null;\n}\n\nexport function useDynamicCreate(tableName: string): DynamicMutationResult {\n\tconst table = useSheetsTable(tableName, { enabled: false });\n\n\tconst submit = React.useCallback(\n\t\tasync (values: Record<string, unknown>) => {\n\t\t\tconst result = await table.create(values);\n\t\t\treturn result.createdRow ?? null;\n\t\t},\n\t\t[table],\n\t);\n\n\treturn {\n\t\tsubmit,\n\t\tisSubmitting: table.isCreating,\n\t\terror: table.createError,\n\t};\n}\n\nexport function useDynamicUpdate(tableName: string, rowId: SheetsRowIdentifier): DynamicMutationResult {\n\tconst table = useSheetsTable(tableName, { enabled: false });\n\n\tconst submit = React.useCallback(\n\t\tasync (values: Record<string, unknown>) => {\n\t\t\tconst result = await table.update(rowId, values);\n\t\t\treturn result.updatedRow ?? null;\n\t\t},\n\t\t[table, rowId],\n\t);\n\n\treturn {\n\t\tsubmit,\n\t\tisSubmitting: table.isUpdating,\n\t\terror: table.updateError,\n\t};\n}\n","import { useCallback, useMemo, useState } from 'react';\nimport type { ReactNode } from 'react';\n\nimport { isValuelessOperator } from '../filter-operators';\nimport {\n\tcreateEmptyGroup,\n\ttype FilterGroup,\n\ttype FilterNode,\n} from '../sheets.controls';\nimport { buildWhereFromFilters } from '../sheets.utils';\n\n// Data filtering context type\nexport interface DataFilteringContextValue {\n\tfilterTree: FilterGroup;\n\tfiltersOpen: boolean;\n\teffectiveWhere: any;\n\thasActiveFilters: boolean;\n\tsetFilterTree: (tree: FilterGroup) => void;\n\tsetFiltersOpen: (open: boolean) => void;\n\tclearAllFilters: () => void;\n\tapplyFilters: () => void;\n}\n\n// Data filtering hook configuration\nexport interface UseDataFilteringConfig {\n\tcolumnKeys: string[];\n\ttableMeta?: {\n\t\tfields?: Array<{\n\t\t\tname?: string | null;\n\t\t\ttype?: {\n\t\t\t\tgqlType?: string | null;\n\t\t\t} | null;\n\t\t} | null> | null;\n\t} | null;\n\tinitialFilterTree?: FilterGroup;\n}\n\nfunction hasActiveNode(node: FilterNode): boolean {\n\tif (node.type === 'condition') {\n\t\treturn isValuelessOperator(node.operator) ||\n\t\t\t(node.value !== '' && node.value !== null && node.value !== undefined);\n\t}\n\treturn node.children.some(hasActiveNode);\n}\n\n// Main data filtering hook — uses local state instead of global Zustand store\nexport function useDataFiltering({\n\tcolumnKeys,\n\ttableMeta,\n\tinitialFilterTree,\n}: UseDataFilteringConfig) {\n\tconst [filterTree, setFilterTree] = useState<FilterGroup>(initialFilterTree ?? createEmptyGroup());\n\tconst [filtersOpen, setFiltersOpen] = useState(false);\n\n\tconst clearAllFilters = useCallback(() => {\n\t\tsetFilterTree(createEmptyGroup());\n\t}, []);\n\n\t// applyFilters is a no-op since state is already reactive\n\tconst applyFilters = useCallback(() => {}, []);\n\n\t// Compute effective where clause from current filters\n\tconst effectiveWhere = useMemo(\n\t\t() => buildWhereFromFilters(filterTree, tableMeta),\n\t\t[filterTree, tableMeta],\n\t);\n\n\t// Check if there are active filters\n\tconst hasActiveFilters = useMemo(\n\t\t() => hasActiveNode(filterTree),\n\t\t[filterTree],\n\t);\n\n\tconst contextValue: DataFilteringContextValue = useMemo(\n\t\t() => ({\n\t\t\tfilterTree,\n\t\t\tfiltersOpen,\n\t\t\teffectiveWhere,\n\t\t\thasActiveFilters,\n\t\t\tsetFilterTree,\n\t\t\tsetFiltersOpen,\n\t\t\tclearAllFilters,\n\t\t\tapplyFilters,\n\t\t}),\n\t\t[filterTree, filtersOpen, effectiveWhere, hasActiveFilters, clearAllFilters, applyFilters],\n\t);\n\n\treturn {\n\t\tcontextValue,\n\t\tProvider: ({ children }: { children: ReactNode }) => children,\n\t};\n}\n","import { useCallback, useEffect, useMemo, useState } from 'react';\n\n// Data pagination context type\nexport interface DataPaginationContextValue {\n\t// Pagination state\n\tpageIndex: number;\n\tpageSize: number;\n\ttotalCount: number;\n\ttotalPages: number;\n\n\t// Computed values\n\thasNextPage: boolean;\n\thasPreviousPage: boolean;\n\tstartIndex: number;\n\tendIndex: number;\n\n\t// Actions\n\tsetPageIndex: (index: number) => void;\n\tsetPageSize: (size: number) => void;\n\tgoToNextPage: () => void;\n\tgoToPreviousPage: () => void;\n\tgoToFirstPage: () => void;\n\tgoToLastPage: () => void;\n}\n\n// Data pagination hook configuration\nexport interface UseDataPaginationConfig {\n\tinitialPageSize?: number;\n\tinitialPageIndex?: number;\n\ttotalCount?: number;\n\tonPageChange?: (pageIndex: number, pageSize: number) => void;\n}\n\n// Main data pagination hook — uses local state instead of global Zustand store\nexport function useDataPagination({\n\tinitialPageSize = 100,\n\tinitialPageIndex = 0,\n\ttotalCount = 0,\n\tonPageChange,\n}: UseDataPaginationConfig) {\n\tconst [pageIndex, setPageIndexState] = useState(initialPageIndex);\n\tconst [pageSize, setPageSizeState] = useState(initialPageSize);\n\n\t// Compute pagination values\n\tconst totalPages = useMemo(() => Math.max(1, Math.ceil(totalCount / pageSize)), [totalCount, pageSize]);\n\tconst hasNextPage = useMemo(() => pageIndex < totalPages - 1, [pageIndex, totalPages]);\n\tconst hasPreviousPage = useMemo(() => pageIndex > 0, [pageIndex]);\n\tconst startIndex = useMemo(() => pageIndex * pageSize + 1, [pageIndex, pageSize]);\n\tconst endIndex = useMemo(() => Math.min((pageIndex + 1) * pageSize, totalCount), [pageIndex, pageSize, totalCount]);\n\n\tuseEffect(() => {\n\t\tif (pageSize !== initialPageSize) {\n\t\t\tsetPageSizeState(initialPageSize);\n\t\t}\n\t}, [initialPageSize]); // eslint-disable-line react-hooks/exhaustive-deps\n\n\tuseEffect(() => {\n\t\tif (pageIndex !== initialPageIndex) {\n\t\t\tsetPageIndexState(initialPageIndex);\n\t\t}\n\t}, [initialPageIndex]); // eslint-disable-line react-hooks/exhaustive-deps\n\n\t// Auto-adjust page index when total pages changes\n\tuseEffect(() => {\n\t\tif (pageIndex >= totalPages && totalPages > 0) {\n\t\t\tsetPageIndexState(Math.max(0, totalPages - 1));\n\t\t}\n\t}, [pageIndex, totalPages]);\n\n\t// Page index setter with callback\n\tconst setPageIndex = useCallback(\n\t\t(index: number) => {\n\t\t\tconst clampedIndex = Math.max(0, Math.min(index, totalPages - 1));\n\t\t\tsetPageIndexState(clampedIndex);\n\t\t\tonPageChange?.(clampedIndex, pageSize);\n\t\t},\n\t\t[totalPages, pageSize, onPageChange],\n\t);\n\n\t// Page size setter with callback and reset to first page\n\tconst setPageSize = useCallback(\n\t\t(size: number) => {\n\t\t\tsetPageSizeState(size);\n\t\t\tsetPageIndexState(0);\n\t\t\tonPageChange?.(0, size);\n\t\t},\n\t\t[onPageChange],\n\t);\n\n\t// Navigation actions\n\tconst goToNextPage = useCallback(() => {\n\t\tif (hasNextPage) {\n\t\t\tsetPageIndex(pageIndex + 1);\n\t\t}\n\t}, [hasNextPage, pageIndex, setPageIndex]);\n\n\tconst goToPreviousPage = useCallback(() => {\n\t\tif (hasPreviousPage) {\n\t\t\tsetPageIndex(pageIndex - 1);\n\t\t}\n\t}, [hasPreviousPage, pageIndex, setPageIndex]);\n\n\tconst goToFirstPage = useCallback(() => {\n\t\tsetPageIndex(0);\n\t}, [setPageIndex]);\n\n\tconst goToLastPage = useCallback(() => {\n\t\tsetPageIndex(totalPages - 1);\n\t}, [totalPages, setPageIndex]);\n\n\tconst contextValue: DataPaginationContextValue = useMemo(\n\t\t() => ({\n\t\t\tpageIndex,\n\t\t\tpageSize,\n\t\t\ttotalCount,\n\t\t\ttotalPages,\n\t\t\thasNextPage,\n\t\t\thasPreviousPage,\n\t\t\tstartIndex,\n\t\t\tendIndex,\n\t\t\tsetPageIndex,\n\t\t\tsetPageSize,\n\t\t\tgoToNextPage,\n\t\t\tgoToPreviousPage,\n\t\t\tgoToFirstPage,\n\t\t\tgoToLastPage,\n\t\t}),\n\t\t[\n\t\t\tpageIndex,\n\t\t\tpageSize,\n\t\t\ttotalCount,\n\t\t\ttotalPages,\n\t\t\thasNextPage,\n\t\t\thasPreviousPage,\n\t\t\tstartIndex,\n\t\t\tendIndex,\n\t\t\tsetPageIndex,\n\t\t\tsetPageSize,\n\t\t\tgoToNextPage,\n\t\t\tgoToPreviousPage,\n\t\t\tgoToFirstPage,\n\t\t\tgoToLastPage,\n\t\t],\n\t);\n\n\treturn {\n\t\tcontextValue,\n\t\tProvider: ({ children }: { children: any }) => children,\n\t};\n}\n\n// Convenience hooks for accessing specific parts of the context\nexport function usePaginationState() {\n\t// Placeholder — real values come from the contextValue returned by useDataPagination\n\treturn { pageIndex: 0, pageSize: 100 };\n}\n\nexport function usePaginationActions() {\n\t// Placeholder — real actions come from the contextValue\n\treturn {\n\t\tsetPageIndex: (_index: number) => {},\n\t\tsetPageSize: (_size: number) => {},\n\t\tgoToNextPage: () => {},\n\t\tgoToPreviousPage: () => {},\n\t\tgoToFirstPage: () => {},\n\t\tgoToLastPage: () => {},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,eAAAA,eAAa,aAAAC,YAAW,uBAAAC,sBAAqB,WAAAC,WAAS,UAAAC,UAAQ,YAAAC,iBAAgB;AAEnG;AAAA,EACC;AAAA,OAKM;AACP,SAAS,iBAAiB,uBAAuB;AAIjD,SAAS,UAAAC,eAAc;;;ACbvB,SAAS,MAAM,aAAa,WAAW,SAAS,gBAAgB;AAChE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP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AAU,YAAY;AAAA,EACpC;AAGA,QAAM,cAAcA;AAAA,IACnB,CAAC,SAAiB;AACjB,uBAAiB,IAAI;AACrB,wBAAkB,CAAC;AACnB,qBAAe,GAAG,IAAI;AAAA,IACvB;AAAA,IACA,CAAC,YAAY;AAAA,EACd;AAGA,QAAM,eAAeA,cAAY,MAAM;AACtC,QAAI,aAAa;AAChB,mBAAa,YAAY,CAAC;AAAA,IAC3B;AAAA,EACD,GAAG,CAAC,aAAa,WAAW,YAAY,CAAC;AAEzC,QAAM,mBAAmBA,cAAY,MAAM;AAC1C,QAAI,iBAAiB;AACpB,mBAAa,YAAY,CAAC;AAAA,IAC3B;AAAA,EACD,GAAG,CAAC,iBAAiB,WAAW,YAAY,CAAC;AAE7C,QAAM,gBAAgBA,cAAY,MAAM;AACvC,iBAAa,CAAC;AAAA,EACf,GAAG,CAAC,YAAY,CAAC;AAEjB,QAAM,eAAeA,cAAY,MAAM;AACtC,iBAAa,aAAa,CAAC;AAAA,EAC5B,GAAG,CAAC,YAAY,YAAY,CAAC;AAE7B,QAAM,eAA2CE;AAAA,IAChD,OAAO;AAAA,MACN;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACD;AAAA,IACA;AAAA,MACC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACD;AAAA,EACD;AAEA,SAAO;AAAA,IACN;AAAA,IACA,UAAU,CAAC,EAAE,SAAS,MAAyB;AAAA,EAChD;AACD;","names":["useCallback","useEffect","useImperativeHandle","useMemo","useRef","useState","Button","FilterConditionRow","FilterGroupUI","useState","RiAddLine","RiDeleteBin6Line","AlertDialog","AlertDialogAction","AlertDialogCancel","AlertDialogContent","AlertDialogDescription","AlertDialogFooter","AlertDialogHeader","AlertDialogTitle","Fragment","jsx","jsxs","key","useCallback","useEffect","useMemo","jsx","useEffect","useCallback","useMemo","useCallback","Button","jsx","jsxs","useCallback","Button","useCallback","RiCheckLine","RiCloseLine","RiErrorWarningLine","RiLoader4Line","AnimatePresence","motion","jsx","jsxs","useCallback","AnimatePresence","motion","StatusIcon","RiCloseLine","RiLoader4Line","RiCheckLine","RiErrorWarningLine","RiAddLine","RiErrorWarningLine","Button","jsx","jsxs","RiErrorWarningLine","Button","RiAddLine","jsx","Button","jsx","jsxs","useCallback","useEffect","useMemo","useRef","useCallback","useMemo","baseType","key","relationData","fkField","foreignKeyUpdates","useCallback","useMemo","useMemo","useCallback","useMemo","key","useCallback","columnKeys","useCallback","useCallback","useCallback","useRef","legacyRowIdentifier","useRef","useCallback","useCallback","useRef","useState","clear","useMemo","useMemo","useCallback","useMemo","useState","useState","useCallback","useMemo","useCallback","useMemo","key","isDraftRow","useMemo","cache","useCallback","hit","resolution","useCallback","useCallback","useMemo","useMemo","useCallback","useMemo","useReducer","key","useReducer","useCallback","useMemo","useCallback","useMemo","useCallback","useEffect","useMemo","useRef","useState","useQueryClient","cleanTable","useQueryClient","useMemo","useState","useRef","cleanTable","useEffect","useCallback","useMemo","useCallback","useMemo","buildFieldMetaMap","useMemo","useRef","useCallback","useMemo","useEffect","key","useMemo","useMemo","useMemo","useRef","jsx","jsxs","useRef","useMemo","memo","useCallback","useRef","jsx","Checkbox","jsx","Button","jsx","jsxs","Button","jsx","jsxs","img","jsx","jsxs","jsx","jsx","jsx","jsxs","jsx","jsx","useRef","useState","jsx","useState","useRef","jsx","memo","SheetsCellHostInner","useRef","useCallback","Component","useCallback","useState","useEffect","useLayoutEffect","useMemo","useRef","useState","Component","jsx","jsxs","Component","jsx","useRef","useState","useMemo","useLayoutEffect","useEffect","key","Fragment","jsx","jsxs","ESTIMATED_ROW_HEIGHT","useRef","useMemo","useCallback","key","useImperativeHandle","useEffect","overlay","useState","active","Button","memo","useCallback","useEffect","useMemo","useRef","useState","RiAddLine","AnimatePresence","motion","Button","Input","jsx","jsxs","memo","TableItem","SheetsTableSelector","useState","useRef","useMemo","useEffect","useCallback","RiAddLine","motion","AnimatePresence","key","React","useCallback","useMemo","useState","useState","useCallback","useMemo","useCallback","useEffect","useMemo","useState"]}
1
+ {"version":3,"sources":["../src/grid/sheets.tsx","../src/grid/sheets.controls.tsx","../src/grid/filter-operators.ts","../src/grid/sheets.context-menu.tsx","../src/grid/feedback/feedback-context.tsx","../src/grid/feedback/feedback-reducer.ts","../src/grid/feedback/dock-status-bar.tsx","../src/utils/motion-config.ts","../src/grid/feedback/floating-status.tsx","../src/grid/feedback/sheets-error-boundary.tsx","../src/grid/feedback/sheets-error-state.tsx","../src/grid/sheets.pagination.tsx","../src/grid/use-sheets.ts","../src/hooks/use-relation-columns.ts","../src/cell-types/cell-registry.ts","../src/cell-types/type-mapping.ts","../src/cell-types/cell-type-resolver.ts","../src/grid/sheets.utils.ts","../src/hooks/use-relation-metadata-cache.ts","../src/grid/row-model.ts","../src/cell-types/cell-type-registry.ts","../src/cell-model/cell-slots.ts","../src/grid/sheets.constants.ts","../src/grid/hooks/use-cell-editing.ts","../src/grid/hooks/use-batch-commit.ts","../src/grid/hooks/use-undo-redo.ts","../src/grid/hooks/use-draft-rows.ts","../src/grid/hooks/use-draft-submission.ts","../src/config/sheets-concurrency.ts","../src/grid-dom/use-sheets-content.ts","../src/grid/cell-routing.ts","../src/grid/hooks/use-grid-operations.ts","../src/grid/hooks/use-grid-selection.ts","../src/grid/hooks/use-grid-state.ts","../src/selection/range-set.ts","../src/selection/selection-model.ts","../src/grid/hooks/use-infinite-grid-data.ts","../src/hooks/use-sheets-infinite-table.ts","../src/grid/hooks/use-load-grid.ts","../src/table/use-sheets-table-instance.ts","../src/table/features.ts","../src/table/grid-viewport.tsx","../src/grid-dom/sheets-cell-host.tsx","../src/cell-model/badge-tones.ts","../src/cell-model/views/badges-view.tsx","../src/cell-model/views/boolean-view.tsx","../src/cell-model/views/draft-action-view.tsx","../src/cell-model/views/geometry-view.tsx","../src/cell-model/views/image-view.tsx","../src/cell-model/image-cache.ts","../src/cell-model/views/loading-view.tsx","../src/cell-model/views/number-view.tsx","../src/cell-model/views/relation-view.tsx","../src/cell-model/views/text-view.tsx","../src/cell-model/views/uri-view.tsx","../src/grid-dom/inline-cell-editor.tsx","../src/grid-dom/overlay/use-overlay-controller.ts","../src/grid-dom/overlay/overlay-manager.tsx","../src/grid/feedback/editor-error-boundary.tsx","../src/grid-dom/editors/edit-intent.ts","../src/selection/cell-extract.ts","../src/selection/fill.ts","../src/selection/tsv.ts","../src/commands/registry.ts","../src/commands/dispatch.ts","../src/commands/keybinding.ts","../src/commands/keymap.ts","../src/grid/sheets.theme.ts","../src/grid/sheets.table-selector.tsx","../src/cell-types/define-cell-type.ts","../src/forms/metadata-hash.ts","../src/forms/form-spec-builder.ts","../src/forms/zod-schema.ts","../src/forms/mutations.ts","../src/grid/hooks/use-filter-grid.ts","../src/grid/hooks/use-paginate-grid.ts"],"sourcesContent":["import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\nimport type React from 'react';\nimport {\n\tfunctionalUpdate,\n\ttype ColumnPinningState,\n\ttype ColumnSizingState,\n\ttype OnChangeFn,\n\ttype RowSelectionState\n} from '@tanstack/react-table';\nimport { RiFilterOffLine, RiSearchEyeLine } from '@remixicon/react';\n\nimport { useSheetsContext } from '../context/sheets-context';\nimport { cn } from '../utils/cn';\nimport { Button } from '@constructive-io/ui/button';\nimport type { DataGridProps, SheetsHandle } from './sheets.types';\nimport type { SheetsRow } from './row-model';\n\nimport { SheetsControls, countConditions } from './sheets.controls';\nimport { SheetsContextMenu, type ContextMenuState } from './sheets.context-menu';\nimport { FeedbackProvider, FloatingStatus } from './feedback';\nimport { SheetsErrorBoundary } from './feedback/sheets-error-boundary';\nimport { SheetsEmptyState, SheetsErrorState, SheetsLoadingState } from './feedback/sheets-error-state';\nimport { SheetsPagination } from './sheets.pagination';\nimport { useSheets } from './use-sheets';\nimport { useSheetsTableInstance, type SheetsColumnDescriptor } from '../table/use-sheets-table-instance';\nimport { GridViewport, type GridViewportHandle, type RenderCell, type RowMarker, type VisibleRange } from '../table/grid-viewport';\nimport { SheetsCellHost, type OpenEditor } from '../grid-dom/sheets-cell-host';\nimport { useOverlayController } from '../grid-dom/overlay/use-overlay-controller';\nimport { OverlayManager } from '../grid-dom/overlay/overlay-manager';\nimport { resolveEditIntent } from '../grid-dom/editors/edit-intent';\nimport { computeOverlayGeometry } from './editors/overlay-viewport-guard';\nimport { RangeSet } from '../selection/range-set';\nimport { clear, emptySheetsSelection, extendRangeToCell, selectRange, toggleRow } from '../selection/selection-model';\nimport type { SelectionRect } from '../selection/selection-model';\nimport { getCellsInRange as extractCellsInRange, toTSV as serializeTSV } from '../selection/cell-extract';\nimport { bulkEditWrites } from '../selection/fill';\nimport { createGridCommandRegistry, type NavAbsolutePayload } from '../commands/registry';\nimport type { GridCommandRegistry } from '../commands/types';\nimport type { GridCommandContext, CellMatrix } from '../commands/context';\nimport { makeDispatch, tailObserver, type Dispatch, type Interceptor } from '../commands/dispatch';\nimport { resolveKeyCommand, DEFAULT_KEYMAP, type Binding } from '../commands/keymap';\n\n// Rows moved per PageUp/PageDown when the scroll element's clientHeight can't be read\n// (jsdom / detached). A sensible spreadsheet page span.\nconst FALLBACK_PAGE_ROWS = 10;\n/** Estimated body row height — MUST match grid-viewport's ESTIMATED_ROW_HEIGHT (page-span math). */\nconst ESTIMATED_ROW_HEIGHT = 34;\n\n/** Escape a single CSV field: wrap in quotes when it contains comma/quote/newline. */\nfunction escapeCsvField(value: unknown): string {\n\tconst str = value == null ? '' : String(value);\n\tif (/[\",\\n\\r]/.test(str)) {\n\t\treturn `\"${str.replace(/\"/g, '\"\"')}\"`;\n\t}\n\treturn str;\n}\n\n/**\n * Build a CSV string from rows + columns and trigger a browser download.\n * Dependency-free: values are stringified via String() (objects become\n * \"[object Object]\" — callers wanting rich serialization should pre-flatten).\n */\nfunction downloadCsv(rows: Record<string, unknown>[], columns: string[], filename?: string): void {\n\tif (typeof document === 'undefined') return;\n\tconst header = columns.map(escapeCsvField).join(',');\n\tconst body = rows.map((row) => columns.map((col) => escapeCsvField(row?.[col])).join(',')).join('\\n');\n\tconst csv = body ? `${header}\\n${body}` : header;\n\n\tconst blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });\n\tconst url = URL.createObjectURL(blob);\n\tconst link = document.createElement('a');\n\tlink.href = url;\n\tlink.download = filename ?? 'export.csv';\n\tdocument.body.appendChild(link);\n\tlink.click();\n\tdocument.body.removeChild(link);\n\tURL.revokeObjectURL(url);\n}\n\n/**\n * Coerce a cell's raw row value to a boolean for the inline-toggle commit — MUST\n * match the boolean SheetsCell factory (cell-model/factories/boolean.ts) so the\n * toggle flips against the SAME boolean the cell renders: null/undefined -> false,\n * a boolean passes through, anything else via Boolean(). The host commits the\n * negation, so an unset boolean toggles on first.\n */\nfunction coerceCellBoolean(value: unknown): boolean {\n\tif (value === null || value === undefined) return false;\n\treturn typeof value === 'boolean' ? value : Boolean(value);\n}\n\n/** The absolute-nav keys whose command (`cell.navAbsolute`) needs the payload below. */\nconst ABSOLUTE_NAV_KEYS = new Set(['Tab', 'Home', 'End', 'PageUp', 'PageDown']);\n\n/**\n * Build the dispatch payload for a key event. Only `cell.navAbsolute` (Tab/Home/End/Page*)\n * needs one — the funnel's old inline branch derived the page span from the scroll element's\n * clientHeight (e.currentTarget IS the scroll root), falling back to a constant under jsdom.\n * Arrows / extends / undo / redo / select-all / open read everything from the command context,\n * so they get `undefined`.\n */\nfunction buildKeyPayload(e: React.KeyboardEvent): NavAbsolutePayload | undefined {\n\tif (!ABSOLUTE_NAV_KEYS.has(e.key)) return undefined;\n\tconst clientHeight = (e.currentTarget as HTMLElement).clientHeight;\n\tconst pageRows = clientHeight > 0 ? Math.max(1, Math.floor(clientHeight / ESTIMATED_ROW_HEIGHT)) : FALLBACK_PAGE_ROWS;\n\treturn { key: e.key, ctrlOrMeta: e.ctrlKey || e.metaKey, shift: e.shiftKey, pageRows };\n}\n\nfunction SheetsInnerComponent<TRow extends SheetsRow = SheetsRow>(\n\tprops: DataGridProps<TRow>,\n\tref: React.ForwardedRef<SheetsHandle>,\n) {\n\t// The native TanStack DOM grid is the only render path (the canvas <DataEditor>\n\t// branch was removed at the glide cutover).\n\treturn (\n\t\t<FeedbackProvider>\n\t\t\t<SheetsDomInner {...props} forwardedRef={ref} />\n\t\t</FeedbackProvider>\n\t);\n}\n\n// forwardRef erases the component's own generic parameter; the cast restores a\n// generic call signature so `Sheets<MyRow>` keeps inferring TRow. This is the\n// single allowed `as` cast for Unit A (well-known generic-forwardRef pattern).\nexport const Sheets = forwardRef(SheetsInnerComponent) as <TRow extends SheetsRow = SheetsRow>(\n\tprops: DataGridProps<TRow> & { ref?: React.Ref<SheetsHandle> },\n) => React.ReactElement;\n\n// ============================================================================\n// The (only) render path. Reuses the useSheets hook for data/state, feeds its\n// bindings into the v9 table instance + GridViewport, and renders native DOM\n// cells via SheetsCellHost. Surfaces the same load states (error / loading /\n// empty + consumer slots) the removed canvas branch owned.\n// ============================================================================\n\n// Row selection (Phase 6), column sizing + pinning (Stage 2) are all wired to the shell now.\n// Pinning is shell-DERIVED (frozenCount), never edited from the grid, so its onChange is a no-op.\n// Stable empty row-selection map returned when nothing is selected.\nconst EMPTY_ROW_SELECTION: RowSelectionState = {};\nconst noop = () => {};\n\n// Overlay flip-geometry knobs — MUST match the OverlayManager's private constants so\n// the geometry we hand the editor via EditorProps.overlay matches where it's placed.\nconst OVERLAY_MARGIN_PX = 12;\nconst OVERLAY_MIN_BELOW_PX = 320;\n\nfunction SheetsDomInner<TRow extends SheetsRow = SheetsRow>({\n\tforwardedRef,\n\t...props\n}: DataGridProps<TRow> & { forwardedRef?: React.ForwardedRef<SheetsHandle> }) {\n\tconst {\n\t\ttableName,\n\t\tclassName,\n\t\tpageSize = 100,\n\t\tshowSelection = true,\n\t\tshowPagination = true,\n\t\tinfiniteScroll = false,\n\t\tslots,\n\t} = props;\n\tconst s = useSheets<TRow>(props);\n\tconst shell = s._shell;\n\n\tconst { config } = useSheetsContext();\n\n\tconst viewportRef = useRef<GridViewportHandle>(null);\n\n\t// ============== EVENT->COMMAND DISPATCH (P4 Phase 1) ==============\n\t// ONE interceptable pipeline: every grid event resolves to a named command and runs\n\t// through `dispatch`. The registry + keymap are latched (so a Phase 2 consumer override\n\t// is a ref swap, not a new dispatch identity); `ctxRef.current` is the assembled\n\t// GridCommandContext, repointed each render below (mirrors the openEditor ref-latch).\n\t// `dispatch` is useCallback([]) reading the refs, so it stays referentially STABLE — the\n\t// per-cell memo gates on the pointer callbacks that close over it, so it must never churn.\n\t// PUBLIC CUSTOMIZATION SEAM (P4 Phase 2): registry / keymap / interceptors derive from the\n\t// consumer props but rebuild ONLY when the prop IDENTITY changes (useMemo), so omitting them\n\t// is identical to the defaults. Each is latched into a ref so the keydown handler + dispatch\n\t// read the latest without re-creating. The PUBLIC `dispatch` callback stays referentially\n\t// STABLE (reads dispatchRef.current), so the per-cell memo never churns; dispatchRef itself is\n\t// rebuilt when the registry or interceptor list identity changes (additive, no identity leak).\n\tconst { commands, keymap, interceptors, onCommand } = props;\n\tconst registry = useMemo<GridCommandRegistry>(() => createGridCommandRegistry(commands), [commands]);\n\t// Consumer bindings scan FIRST (resolveKeyCommand is first-match-wins) so a rebind of a\n\t// built-in chord wins over the default; the defaults follow as the fallback set.\n\tconst fullKeymap = useMemo<Binding[]>(() => [...(keymap ?? []), ...DEFAULT_KEYMAP], [keymap]);\n\tconst keymapRef = useRef<Binding[]>(fullKeymap);\n\tkeymapRef.current = fullKeymap;\n\t// Consumer interceptors are OUTERMOST (first-listed); the onCommand tail observer is appended\n\t// LAST so it sits innermost (after every consumer interceptor) and observes the real result.\n\tconst chain = useMemo<Interceptor[]>(\n\t\t() => [...(interceptors ?? []), ...(onCommand ? [tailObserver(onCommand)] : [])],\n\t\t[interceptors, onCommand],\n\t);\n\tconst ctxRef = useRef<GridCommandContext>(undefined as unknown as GridCommandContext);\n\tconst dispatchRef = useRef<Dispatch>(undefined as unknown as Dispatch);\n\tdispatchRef.current = useMemo<Dispatch>(() => makeDispatch(registry, () => ctxRef.current, chain), [registry, chain]);\n\tconst dispatch = useCallback<Dispatch>((command, native, payload) => dispatchRef.current(command, native, payload), []);\n\n\tconst columns = useMemo<SheetsColumnDescriptor[]>(\n\t\t() => s.columns.map((col) => ({ key: col.id, name: col.title, size: col.width })),\n\t\t[s.columns],\n\t);\n\n\t// ============== COLUMN SIZING + PINNING STATE MIRROR (Stage 2) ==============\n\t// Sizing: project the shell's columnWidths Map → v9 ColumnSizingState; a width committed\n\t// by the header drag-resize handle goes STRAIGHT to resizeColumn (the same setter the canvas\n\t// onColumnResize uses), so the Map stays the single source of truth and the table just mirrors.\n\t// Pinning: pin col0 ('id') exactly when the canvas freezes it (frozenCount), else nothing —\n\t// GridViewport's findStickyColumnIndex falls back to col0 anyway, so the sticky column is identical.\n\tconst columnWidths = shell.columnWidths;\n\tconst resizeColumn = shell.resizeColumn;\n\tconst frozenCount = shell.frozenCount;\n\tconst firstColumnKey = shell.columnKeys[0];\n\n\tconst columnSizing = useMemo<Record<string, number>>(() => {\n\t\tconst sizing: Record<string, number> = {};\n\t\tcolumnWidths.forEach((width, key) => {\n\t\t\tsizing[key] = width;\n\t\t});\n\t\treturn sizing;\n\t}, [columnWidths]);\n\n\tconst columnPinning = useMemo<ColumnPinningState>(\n\t\t() => ({ start: frozenCount > 0 && firstColumnKey ? [firstColumnKey] : [], end: [] }),\n\t\t[frozenCount, firstColumnKey],\n\t);\n\n\tconst onColumnSizingChange = useCallback<OnChangeFn<ColumnSizingState>>(\n\t\t(updater) => {\n\t\t\tconst next = functionalUpdate(updater, columnSizing);\n\t\t\tfor (const key of Object.keys(next)) {\n\t\t\t\tif (next[key] !== columnSizing[key]) resizeColumn(key, next[key]);\n\t\t\t}\n\t\t},\n\t\t[columnSizing, resizeColumn],\n\t);\n\n\t// ============== ROW-SELECTION STATE MIRROR (Phase 6, both directions) ==============\n\t// The native SheetsSelection (RangeSet of ROW indices) stays canonical; the v9\n\t// table only needs a derived `Record<rowId, true>` view. Both directions use the\n\t// same metadata-defined row key, so renamed/composite PK selections round-trip.\n\tconst combinedRows = shell.combinedRows;\n\tconst getRowId = shell.getRowId;\n\tconst selection = s.selection.gridSelection;\n\tconst setSelection = s.selection.setGridSelection;\n\t// Active (keyboard cursor) cell `[col, row]`, threaded to the viewport for the focus ring +\n\t// aria-activedescendant. Derived in render (a plain read, no setState) per the no-setState-in-render rule.\n\tconst activeCell = selection?.current?.cell;\n\n\tconst rowSelection = useMemo<RowSelectionState>(() => {\n\t\tif (!selection) return EMPTY_ROW_SELECTION;\n\t\tconst map: RowSelectionState = {};\n\t\tfor (const index of selection.rows.toArray()) {\n\t\t\tmap[getRowId(combinedRows[index], index)] = true;\n\t\t}\n\t\treturn map;\n\t}, [selection, combinedRows, getRowId]);\n\n\tconst onRowSelectionChange = useCallback<OnChangeFn<RowSelectionState>>(\n\t\t(updater) => {\n\t\t\tconst next = functionalUpdate(updater, rowSelection);\n\t\t\t// Map the selected row IDS back to row INDICES via combinedRows, then fold\n\t\t\t// into a fresh RangeSet. Active cell follows the lowest selected index (or\n\t\t\t// clears to the empty selection when nothing is selected).\n\t\t\tconst indexById = new Map<string, number>();\n\t\t\tfor (let i = 0; i < combinedRows.length; i++) indexById.set(getRowId(combinedRows[i], i), i);\n\n\t\t\tlet rows = RangeSet.empty();\n\t\t\tlet lowest: number | undefined;\n\t\t\tfor (const id of Object.keys(next)) {\n\t\t\t\tif (!next[id]) continue;\n\t\t\t\tconst index = indexById.get(id);\n\t\t\t\tif (index === undefined) continue;\n\t\t\t\trows = rows.add(index);\n\t\t\t\tif (lowest === undefined || index < lowest) lowest = index;\n\t\t\t}\n\n\t\t\tif (lowest === undefined) {\n\t\t\t\tsetSelection(emptySheetsSelection);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsetSelection({ current: { cell: [0, lowest] }, rows, columns: RangeSet.empty() });\n\t\t},\n\t\t[rowSelection, combinedRows, getRowId, setSelection],\n\t);\n\n\tconst table = useSheetsTableInstance({\n\t\tcolumns,\n\t\tdata: combinedRows,\n\t\tcolumnSizing,\n\t\tcolumnPinning,\n\t\trowSelection,\n\t\tonColumnSizingChange,\n\t\t// Pinning is shell-derived (frozenCount), never edited from the grid → no writer needed.\n\t\tonColumnPinningChange: noop,\n\t\tonRowSelectionChange,\n\t\tgetRowId,\n\t});\n\n\t// ============== LEADING CHECKBOX / SELECT-ALL COLUMN (drives the canonical RangeSet) ==============\n\t// The DOM grid has no canvas rowMarkers, so the GridViewport paints a sticky checkbox column whose\n\t// toggles write the canonical SheetsSelection directly (the rowSelection mirror above derives FROM\n\t// it). selectRange/toggleRow/clear are the same pure helpers the canvas projection round-trips, so\n\t// shift-range and ctrl-toggle behave identically. `shiftAnchorRef` records the last-toggled index so\n\t// a subsequent shift-click selects the contiguous block — caller-owned, matching selectRange's contract.\n\tconst rowCount = combinedRows.length;\n\tconst shiftAnchorRef = useRef<number | null>(null);\n\t// Latch selection + rowCount so the STABLE toggle impls (ctx methods) read the latest values\n\t// without re-creating, while rowMarker's handlers dispatch the named commands through `dispatch`.\n\tconst rowMarkerSelectionRef = useRef(selection);\n\trowMarkerSelectionRef.current = selection;\n\tconst rowCountRef = useRef(rowCount);\n\trowCountRef.current = rowCount;\n\t// Verbatim toggle bodies, lifted from the previous inline rowMarker handlers — the rowMarker\n\t// dispatches `rowmarker.toggleRow` / `rowmarker.toggleAll`, whose commands call these.\n\tconst toggleRowImpl = useCallback((index: number, shiftKey: boolean) => {\n\t\tconst sel = rowMarkerSelectionRef.current ?? emptySheetsSelection;\n\t\tconst anchor = shiftAnchorRef.current;\n\t\tconst next = shiftKey && anchor !== null ? selectRange(sel, anchor, index) : toggleRow(sel, index);\n\t\tshiftAnchorRef.current = index;\n\t\tsetSelection(next);\n\t}, [setSelection]);\n\tconst toggleAllImpl = useCallback(() => {\n\t\tconst sel = rowMarkerSelectionRef.current ?? emptySheetsSelection;\n\t\tconst rc = rowCountRef.current;\n\t\tconst allSelected = rc > 0 && sel.rows.length === rc;\n\t\tshiftAnchorRef.current = null;\n\t\tsetSelection(\n\t\t\tallSelected || rc === 0\n\t\t\t\t? clear(sel)\n\t\t\t\t: { current: { cell: [0, 0] }, rows: RangeSet.fromSingleSelection([0, rc]), columns: RangeSet.empty() },\n\t\t);\n\t}, [setSelection]);\n\tconst rowMarker = useMemo<RowMarker>(() => {\n\t\tconst sel = selection ?? emptySheetsSelection;\n\t\tconst selectedCount = sel.rows.length;\n\t\tconst allSelected = rowCount > 0 && selectedCount === rowCount;\n\t\treturn {\n\t\t\tisSelected: (index) => sel.rows.hasIndex(index),\n\t\t\t// Toggle handlers route through the ONE dispatch pipeline (rowmarker.toggleRow /\n\t\t\t// rowmarker.toggleAll); the command bodies call toggleRowImpl / toggleAllImpl (the\n\t\t\t// verbatim selectRange/toggleRow/clear logic lifted above).\n\t\t\tonToggleRow: (index, shiftKey) => dispatch('rowmarker.toggleRow', undefined, { rowIndex: index, shift: shiftKey }),\n\t\t\tallSelected,\n\t\t\tsomeSelected: selectedCount > 0 && !allSelected,\n\t\t\tonToggleAll: () => dispatch('rowmarker.toggleAll'),\n\t\t};\n\t}, [selection, rowCount, dispatch]);\n\n\t// Imperative getSelectedRows reads the SAME canonical RangeSet the canvas handle uses.\n\tconst getSelectedRows = useCallback(\n\t\t(): Record<string, unknown>[] =>\n\t\t\t(selection?.rows.toArray() ?? []).map((i) => combinedRows[i]).filter(Boolean) as Record<string, unknown>[],\n\t\t[selection, combinedRows],\n\t);\n\n\t// Shared CSV export body — selected rows if any, else the loaded/filtered set. Reused by\n\t// the imperative SheetsHandle.exportCsv() and the toolbar Export button (handleExport).\n\tconst runCsvExport = useCallback(\n\t\t(opts?: { columns?: string[]; filename?: string }) => {\n\t\t\tconst selected = getSelectedRows();\n\t\t\tconst rows = selected.length ? selected : (shell.combinedRows as Record<string, unknown>[]);\n\t\t\tdownloadCsv(rows, opts?.columns ?? shell.columnKeys, opts?.filename);\n\t\t},\n\t\t[getSelectedRows, shell.combinedRows, shell.columnKeys],\n\t);\n\n\tuseImperativeHandle(\n\t\tforwardedRef,\n\t\t(): SheetsHandle => ({\n\t\t\tscrollToRow: (index) => viewportRef.current?.scrollToIndex(index),\n\t\t\tsubmitDrafts: () => s.draft.submitDrafts(),\n\t\t\trefetch: () => s.refetch(),\n\t\t\tgetSelectedRows,\n\t\t\texportCsv: (opts) => runCsvExport(opts),\n\t\t}),\n\t\t[s.draft.submitDrafts, s.refetch, getSelectedRows, runCsvExport],\n\t);\n\n\t// ============== ADD ROW (toolbar) ==============\n\t// Append a draft via the shell API, then scroll it into view. appendRow resolves to the\n\t// new draft's index (or undefined when metadata isn't ready yet — then there's nothing to\n\t// scroll to). Threaded into <SheetsControls onAddRow=…> so the toolbar renders an Add-row button.\n\tconst appendRow = s.draft.appendRow;\n\tconst handleAddRow = useCallback(() => {\n\t\tvoid appendRow().then((index) => {\n\t\t\tif (index !== undefined) viewportRef.current?.scrollToIndex(index);\n\t\t});\n\t}, [appendRow]);\n\n\t// Toolbar Export button — same path as the imperative SheetsHandle.exportCsv().\n\tconst handleExport = useCallback(() => runCsvExport({ filename: `${tableName}.csv` }), [runCsvExport, tableName]);\n\n\t// ============== SCROLL + SELECTION RESET ON SORT/FILTER CHANGE ==============\n\t// When sort or filter changes the infinite query re-keys and the row set is a different,\n\t// index-based window — so any held selection/active-cell now points at the wrong rows.\n\t// Per the locked decision we CLEAR selection + active cell and scroll back to the top.\n\t// Keyed precisely on the same sort+filter inputs the query derives its where/orderBy from,\n\t// so it fires only on a real sort/filter transition (not on data refetch or draft edits).\n\tconst optionsKey = useMemo(\n\t\t() => JSON.stringify({ id: shell.sorting.id, desc: shell.sorting.desc, filter: shell.filterTree }),\n\t\t[shell.sorting.id, shell.sorting.desc, shell.filterTree],\n\t);\n\tconst didMountResetRef = useRef(false);\n\tuseEffect(() => {\n\t\tif (!didMountResetRef.current) {\n\t\t\tdidMountResetRef.current = true;\n\t\t\treturn;\n\t\t}\n\t\tsetSelection(emptySheetsSelection);\n\t\tviewportRef.current?.scrollToIndex(0);\n\t}, [optionsKey, setSelection]);\n\n\t// ============== NATIVE OVERLAY EDITING (Phase 4, additive) ==============\n\t// Open/close state for the native React-portal overlay editor. The host measures\n\t// the activated cell's rect (only it knows the cell DOM node) and calls openEditor.\n\tconst overlay = useOverlayController();\n\tconst overlayOpen = overlay.open;\n\tconst overlayClose = overlay.close;\n\tconst overlayReanchor = overlay.reanchor;\n\n\t// Inject the shell's native content resolver into the cell host (Phase 3): the\n\t// host renders the consumer component when registered, else the kind→view map.\n\t// openEditor is threaded so the cell wrapper can activate the overlay editor;\n\t// submitDraftRow is threaded so the draft-action cell's Button can submit (Stage 4).\n\tconst getSheetsCellContent = shell.getSheetsCellContent;\n\tconst submitDraftRow = shell.submitDraftRow;\n\tconst commitCellValue = shell.commitCellValue;\n\tconst getEditorComponent = shell.cellRegistry.getEditorComponent;\n\t// Undo/redo handlers (stable from useUndoRedo) — wired into the edit.undo / edit.redo commands.\n\tconst undo = shell.undo;\n\tconst redo = shell.redo;\n\t// Batched commit + observational emit — threaded into the command context (commitCells/emit).\n\tconst commitCells = shell.commitCells;\n\tconst emit = shell.emit;\n\n\t// REF-LATCH (perf): `openEditor` is a dep of `renderCell`, which the cell host\n\t// memo-gates on (prev.openEditor === next.openEditor). Closing over `combinedRows` /\n\t// `commitCellValue` / the resolver directly would give `openEditor` a NEW identity on\n\t// every data/draft change, busting the per-cell memo for the ENTIRE visible window.\n\t// Instead we latch each churning value into a ref kept current every render and read\n\t// `*Ref.current` inside the callback, so `openEditor` stays referentially STABLE while\n\t// still seeing the latest values. (`overlayOpen` is already stable — useCallback([]) —\n\t// so it stays a direct, guaranteed-stable dep.)\n\tconst getSheetsCellContentRef = useRef(getSheetsCellContent);\n\tgetSheetsCellContentRef.current = getSheetsCellContent;\n\tconst getEditorComponentRef = useRef(getEditorComponent);\n\tgetEditorComponentRef.current = getEditorComponent;\n\tconst combinedRowsRef = useRef(combinedRows);\n\tcombinedRowsRef.current = combinedRows;\n\tconst commitCellValueRef = useRef(commitCellValue);\n\tcommitCellValueRef.current = commitCellValue;\n\tconst commitCellsRef = useRef(commitCells);\n\tcommitCellsRef.current = commitCells;\n\t// Read the LATEST selection inside the keydown handler so a queued move can't resurrect a\n\t// stale active cell right after a sort/filter clear (the optionsKey effect resets selection).\n\tconst selectionRef = useRef(selection);\n\tselectionRef.current = selection;\n\n\t// EDIT-INTENT BRANCH (Stage 2): activation routes through the SINGLE edit-intent\n\t// resolver off the resolved `typeKey` — NOT the broken `cell.meta?.cellType ?? 'text'`\n\t// lookup that mis-routed every non-text cell to TextEditor. The cell-host fires this\n\t// on double-click / Enter / F2 (it already no-ops readonly cells); here we branch\n\t// BEFORE opening any overlay:\n\t// • inline-toggle (booleans): commit `!currentBool` in place, no overlay.\n\t// • overlay: open the portal (the editorNode block resolves intent.editor).\n\t// • none (readonly / non-editable): do nothing.\n\tconst openEditorImpl = useCallback<OpenEditor>(\n\t\t(rowIndex, colKey, anchorRect, initialText) => {\n\t\t\tconst resolution = getSheetsCellContentRef.current(rowIndex, colKey);\n\t\t\tconst intent = resolveEditIntent(\n\t\t\t\tresolution.typeKey,\n\t\t\t\t{ readonly: resolution.cell.readonly },\n\t\t\t\tgetEditorComponentRef.current,\n\t\t\t);\n\t\t\tif (intent.mode === 'none') return;\n\t\t\tif (intent.mode === 'inline-toggle') {\n\t\t\t\tconst current = (combinedRowsRef.current[rowIndex] as Record<string, unknown> | undefined)?.[colKey];\n\t\t\t\tcommitCellValueRef.current(rowIndex, colKey, !coerceCellBoolean(current));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// inline-edit (simple text/number): edit IN PLACE — same active-cell controller (so nav/\n\t\t\t// clipboard suppression + scroll commit-on-unmount are shared) but the cell host renders\n\t\t\t// the input and the portal is skipped (editorNode is null for a non-overlay intent).\n\t\t\tif (intent.mode === 'inline-edit') {\n\t\t\t\toverlayOpen({ rowIndex, colKey, anchorRect, initialText, mode: 'inline' });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\toverlayOpen({ rowIndex, colKey, anchorRect, initialText, mode: 'overlay' });\n\t\t},\n\t\t[overlayOpen],\n\t);\n\t// The dblclick entrypoint threaded into the cell host: route through the ONE pipeline as\n\t// `editor.open`; the command body calls ctx.openEditorAt → openEditorImpl. STABLE (closes\n\t// over the stable `dispatch`), so it never busts the per-cell memo.\n\tconst openEditor = useCallback<OpenEditor>(\n\t\t(rowIndex, colKey, anchorRect, initialText) =>\n\t\t\tdispatch('editor.open', undefined, { rowIndex, colKey, anchorRect, initialText }),\n\t\t[dispatch],\n\t);\n\t// ============== RANGE-AWARE BULK EDIT (Stage B) ==============\n\t// The editor's onCommit routes through here. When a MULTI-CELL range is selected AND the\n\t// active (edited) cell sits inside it, the committed value FANS OUT across the whole range\n\t// as ONE undo-aware batch (single optimistic patch + coalesced per-row mutations + one undo\n\t// entry — commitCells skips readonly/UUID internally and resolveServerPatch coerces the\n\t// string value PER target column). A single-cell selection (or none, or an active cell\n\t// outside the range) keeps the existing single-cell commit byte-for-byte. The LATEST range\n\t// is read off `selectionRef` so a queued sort/filter clear wins (same latch the keymap uses).\n\tconst columnKeysRef = useRef(shell.columnKeys);\n\tcolumnKeysRef.current = shell.columnKeys;\n\tconst commitBulkOrSingle = useCallback(\n\t\t(rowIndex: number, colKey: string, value: unknown) => {\n\t\t\tconst range = selectionRef.current?.current?.range;\n\t\t\tconst keys = columnKeysRef.current;\n\t\t\tconst activeCol = keys.indexOf(colKey);\n\t\t\tconst multiCell = !!range && range.width * range.height > 1;\n\t\t\tconst inside =\n\t\t\t\t!!range &&\n\t\t\t\tactiveCol >= 0 &&\n\t\t\t\tactiveCol >= range.x &&\n\t\t\t\tactiveCol < range.x + range.width &&\n\t\t\t\trowIndex >= range.y &&\n\t\t\t\trowIndex < range.y + range.height;\n\t\t\tif (multiCell && inside && range) {\n\t\t\t\tconst writes = bulkEditWrites(range, value, keys);\n\t\t\t\tif (writes.length) void commitCellsRef.current(writes);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcommitCellValueRef.current(rowIndex, colKey, value);\n\t\t},\n\t\t[],\n\t);\n\t// ============== CELL-RANGE SELECTION (Stage B) ==============\n\t// `anchorRef` holds the FIXED corner a contiguous range extends FROM. A plain activate\n\t// (click / non-shift Arrow) resets it to the new active cell; a shift extend keeps it put.\n\t// It is the caller-owned anchor `extendRangeToCell` expects (the model stays a pure value).\n\tconst anchorRef = useRef<[number, number] | null>(null);\n\tconst setSelectionRange = s.selection.setGridSelection;\n\t// Extend the contiguous range from the latched anchor to `[col, row]`. Reads the LATEST\n\t// selection (post-sort-clear safe) and falls back to the target as anchor when none latched.\n\tconst extendToCell = useCallback(\n\t\t(col: number, row: number) => {\n\t\t\tconst sel = selectionRef.current ?? emptySheetsSelection;\n\t\t\tconst anchor = anchorRef.current ?? sel.current?.cell ?? [col, row];\n\t\t\tanchorRef.current = anchor;\n\t\t\tsetSelectionRange(extendRangeToCell(sel, col, row, anchor[0], anchor[1]));\n\t\t},\n\t\t[setSelectionRange],\n\t);\n\t// Click-to-activate: park the active cell on the clicked cell. Stable (the shell's\n\t// setActiveCell is a stable useCallback), so it never busts the per-cell memo. Shift-click\n\t// EXTENDS the range from the latched anchor; a plain click activates AND resets the anchor.\n\tconst setActiveCell = s.selection.setActiveCell;\n\tconst handleActivateCell = useCallback(\n\t\t(col: number, row: number, shiftKey?: boolean) =>\n\t\t\tdispatch(shiftKey ? 'cell.extendToClicked' : 'cell.activate', undefined, { col, row }),\n\t\t[dispatch],\n\t);\n\n\t// ============== RIGHT-CLICK CONTEXT MENU (Stage B) ==============\n\t// A menu is just another EVENT SOURCE → dispatch. State is the pointer anchor (null = closed),\n\t// rendered ONCE at the grid level. `handleContextMenu` is STABLE (reads selectionRef + the stable\n\t// dispatch), so it never busts the per-cell memo. When the right-clicked cell sits OUTSIDE the\n\t// current active cell / selection range, we activate it first so the menu acts on the clicked cell.\n\tconst [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);\n\tconst handleContextMenu = useCallback(\n\t\t(col: number, row: number, clientX: number, clientY: number) => {\n\t\t\tconst sel = selectionRef.current;\n\t\t\tconst active = sel?.current?.cell;\n\t\t\tconst range = sel?.current?.range;\n\t\t\tconst inRange =\n\t\t\t\t!!range && col >= range.x && col < range.x + range.width && row >= range.y && row < range.y + range.height;\n\t\t\tconst isActive = !!active && active[0] === col && active[1] === row;\n\t\t\tif (!isActive && !inRange) dispatch('cell.activate', undefined, { col, row });\n\t\t\tsetContextMenu({ clientX, clientY });\n\t\t},\n\t\t[dispatch],\n\t);\n\tconst closeContextMenu = useCallback(() => setContextMenu(null), []);\n\t// Enabled-state probe for the menu items: run the resolved command's `canRun` against the latched\n\t// context (same gate the dispatch core applies). A missing canRun means \"always runnable\".\n\tconst isCommandEnabled = useCallback(\n\t\t(commandId: string) => {\n\t\t\tconst cmd = registry.get(commandId);\n\t\t\treturn cmd ? (cmd.canRun ? cmd.canRun(ctxRef.current, undefined) : true) : false;\n\t\t},\n\t\t[registry],\n\t);\n\n\t// ============== INLINE (IN-CELL) EDIT WIRING ==============\n\t// Simple text/number types edit in place via the cell host's <input> instead of the portal.\n\t// They ride the SAME active-editor controller (`overlay`) tagged `mode: 'inline'`, so the only\n\t// extra wiring here is (a) telling the editing cell to render the input and (b) commit/cancel\n\t// routed through the existing value-commit pipeline. The inline KEY is the editing cell identity,\n\t// NULL during overlay editing — so `renderCell` stays referentially stable across overlay\n\t// scroll-reanchors (which mutate `overlay.active.anchorRect` but never this key).\n\tconst inlineActive = overlay.active?.mode === 'inline' ? overlay.active : null;\n\tconst inlineKey = inlineActive ? `${inlineActive.rowIndex}:${inlineActive.colKey}` : null;\n\tconst inlineInitialText = inlineActive?.initialText;\n\tconst onInlineCommit = useCallback(\n\t\t(rowIndex: number, colKey: string, value: unknown) => {\n\t\t\tcommitBulkOrSingle(rowIndex, colKey, value);\n\t\t\toverlayClose();\n\t\t},\n\t\t[commitBulkOrSingle, overlayClose],\n\t);\n\n\tconst renderCell = useCallback<RenderCell>(\n\t\t(c, ctx) => {\n\t\t\tconst editingThisCell = inlineKey != null && inlineKey === `${c.row.index}:${c.column.id}`;\n\t\t\treturn (\n\t\t\t\t<SheetsCellHost\n\t\t\t\t\tcell={c}\n\t\t\t\t\tctx={ctx}\n\t\t\t\t\tgetSheetsCellContent={getSheetsCellContent}\n\t\t\t\t\topenEditor={openEditor}\n\t\t\t\t\tisEditing={editingThisCell}\n\t\t\t\t\tinlineInitialText={editingThisCell ? inlineInitialText : undefined}\n\t\t\t\t\tonInlineCommit={onInlineCommit}\n\t\t\t\t\tonInlineCancel={overlayClose}\n\t\t\t\t\tonActivateCell={handleActivateCell}\n\t\t\t\t\tonContextMenu={handleContextMenu}\n\t\t\t\t\tonSubmitDraftRow={submitDraftRow}\n\t\t\t\t/>\n\t\t\t);\n\t\t},\n\t\t[inlineKey, inlineInitialText, onInlineCommit, overlayClose, getSheetsCellContent, openEditor, handleActivateCell, handleContextMenu, submitDraftRow],\n\t);\n\n\t// ============== SPREADSHEET KEYBOARD NAV (grid root owns keys) ==============\n\t// The grid root (role=grid, tabIndex=0, aria-activedescendant) owns spreadsheet keys.\n\t// Arrows move the active cell (clamped); Enter/F2 open the overlay at the active cell.\n\t// IGNORE keydowns while an overlay editor is open so nav doesn't fight editing. The\n\t// active cell + col/row counts are read LATEST (refs) so a post-sort/filter clear wins.\n\tconst moveActiveCell = s.selection.moveActive;\n\tconst isOverlayOpen = overlay.isOpen;\n\n\t// Shared open-at-active-cell path (Enter / F2 / type-to-edit): resolve the active cell's\n\t// DOM node by its stable id, null-guarding the row (infinite-mode proxy rows can be null at\n\t// unloaded indices) + the colKey, then open the overlay. `initialText` seeds type-to-edit\n\t// (OVERWRITE). Returns true when an overlay was opened.\n\tconst openEditorAtActiveCell = useCallback(\n\t\t(initialText?: string): boolean => {\n\t\t\tconst cell = selectionRef.current?.current?.cell;\n\t\t\tif (!cell) return false;\n\t\t\tconst [col, row] = cell;\n\t\t\tconst rowData = combinedRowsRef.current[row];\n\t\t\tif (!rowData) return false;\n\t\t\tconst colKey = columns[col]?.key;\n\t\t\tif (!colKey) return false;\n\t\t\tconst node = document.getElementById(`sheets-cell-${row}-${col}`);\n\t\t\tif (!node) return false;\n\t\t\t// Open directly via the impl (NOT the dispatching `openEditor`) — this fn is itself the\n\t\t\t// body of the editor.openActive / editor.typeToEdit commands' canRun, so going through\n\t\t\t// dispatch again would double-route. Matches the original (which called openEditor directly).\n\t\t\topenEditorImpl(row, colKey, node.getBoundingClientRect(), initialText);\n\t\t\treturn true;\n\t\t},\n\t\t[columns, openEditorImpl],\n\t);\n\n\t// Every grid key now resolves to a NAMED command through the ONE dispatch pipeline. The\n\t// keymap (first-match-wins) covers undo/redo/select-all/arrows/extend/abs-nav/open; an\n\t// UNRESOLVED key that is a single printable char (no ctrl/meta/alt) falls to the\n\t// `editor.typeToEdit` sentinel (also through dispatch, so it is interceptable). Any other\n\t// unresolved key is left untouched — NO dispatch, NO preventDefault — so it reaches the\n\t// browser. preventDefault lives in the dispatch CORE, gated on a resolved+runnable command.\n\tconst handleGridKeyDown = useCallback(\n\t\t(e: React.KeyboardEvent) => {\n\t\t\t// Don't intercept while editing — the overlay editor owns its own keys.\n\t\t\tif (isOverlayOpen) return;\n\t\t\tconst cmd = resolveKeyCommand(e.nativeEvent, keymapRef.current);\n\t\t\tif (cmd) {\n\t\t\t\tdispatch(cmd, e.nativeEvent, buildKeyPayload(e));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Unresolved: only the printable-key sentinel routes through dispatch; everything\n\t\t\t// else falls through to the browser with no preventDefault.\n\t\t\tif (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {\n\t\t\t\tdispatch('editor.typeToEdit', e.nativeEvent, { char: e.key });\n\t\t\t}\n\t\t},\n\t\t[isOverlayOpen, dispatch],\n\t);\n\n\t// ============== NATIVE CLIPBOARD (Stage B) ==============\n\t// The grid root (role=grid, tabIndex=0) receives the browser's native copy/cut/paste events\n\t// when focused. We do NOT bind Ctrl/Cmd+C/X/V in the keymap — pressing them fires these native\n\t// events directly, so binding the keys too would double-handle. Each handler is SKIPPED while an\n\t// overlay editor is open (the editor owns its own clipboard) and routes through the ONE dispatch\n\t// pipeline as `clipboard.copy`/`cut`/`paste`, threading the native ClipboardData as the payload.\n\t// preventDefault happens in the dispatch core (so the browser does not also copy/paste).\n\tconst handleCopy = useCallback(\n\t\t(e: React.ClipboardEvent) => {\n\t\t\tif (isOverlayOpen) return;\n\t\t\tdispatch('clipboard.copy', e.nativeEvent, { clipboard: (e.nativeEvent as ClipboardEvent).clipboardData });\n\t\t},\n\t\t[isOverlayOpen, dispatch],\n\t);\n\tconst handleCut = useCallback(\n\t\t(e: React.ClipboardEvent) => {\n\t\t\tif (isOverlayOpen) return;\n\t\t\tdispatch('clipboard.cut', e.nativeEvent, { clipboard: (e.nativeEvent as ClipboardEvent).clipboardData });\n\t\t},\n\t\t[isOverlayOpen, dispatch],\n\t);\n\tconst handlePaste = useCallback(\n\t\t(e: React.ClipboardEvent) => {\n\t\t\tif (isOverlayOpen) return;\n\t\t\tdispatch('clipboard.paste', e.nativeEvent, { clipboard: (e.nativeEvent as ClipboardEvent).clipboardData });\n\t\t},\n\t\t[isOverlayOpen, dispatch],\n\t);\n\n\t// FOLLOW-CELL-ON-SCROLL (Stage B): on viewport scroll, re-measure the active cell's DOM\n\t// node and re-anchor the overlay to it (cheap, passive — DOM read + a position state set)\n\t// instead of closing. If the node is GONE (the cell scrolled out of the virtual window and\n\t// unmounted), we COMMIT-AND-CLOSE rather than silently discard: blur the focused editor\n\t// element so a commit-on-blur editor (text/number) commits its in-progress value, then\n\t// close. (Backgrounded-tab rAF throttling is irrelevant — this runs straight off scroll.)\n\tconst activeRef = useRef(overlay.active);\n\tactiveRef.current = overlay.active;\n\tconst columnsRef = useRef(columns);\n\tcolumnsRef.current = columns;\n\tconst handleOverlayScroll = useCallback(() => {\n\t\tconst a = activeRef.current;\n\t\tif (!a) return;\n\t\t// The cell DOM id is `sheets-cell-${rowIndex}-${columnIndex}` — map the stored colKey\n\t\t// back to its rendered column index (same ordering the cell host + activedescendant use).\n\t\tconst colIndex = columnsRef.current.findIndex((c) => c.key === a.colKey);\n\t\tconst node = colIndex >= 0 ? document.getElementById(`sheets-cell-${a.rowIndex}-${colIndex}`) : null;\n\t\tif (node) {\n\t\t\t// Inline edits live INSIDE the cell, so they ride the virtualized row natively — no\n\t\t\t// reposition needed (and reanchoring would churn state every scroll frame). Only the\n\t\t\t// portal overlay re-anchors to the cell on scroll.\n\t\t\tif (a.mode !== 'inline') overlayReanchor(node.getBoundingClientRect());\n\t\t\treturn;\n\t\t}\n\t\t// Cell unmounted (scrolled out of the virtual window) — commit any in-progress value\n\t\t// (commit-on-blur editors, incl. the inline input) then close.\n\t\tconst focused = document.activeElement;\n\t\tif (focused instanceof HTMLElement) focused.blur();\n\t\toverlayClose();\n\t}, [overlayReanchor, overlayClose]);\n\n\t// Resolve the active editor + its EditorProps. Computed in render (cheap, only when\n\t// an overlay is open) — the cell resolution, value, native editor and flip geometry\n\t// all derive from overlay.active, so no effect/state mirror is needed.\n\tconst active = overlay.active;\n\tconst editorNode = (() => {\n\t\tif (!active) return null;\n\t\tconst resolution = getSheetsCellContent(active.rowIndex, active.colKey);\n\t\t// Resolve the editor through the SAME edit-intent resolver the activation branch\n\t\t// used (typeKey-driven, consumer-override aware). Only `overlay` intents ever open\n\t\t// here (openEditor short-circuits inline-toggle/none), but resolving again keeps a\n\t\t// single source of truth — and guards against a non-overlay intent slipping through.\n\t\tconst intent = resolveEditIntent(resolution.typeKey, { readonly: resolution.cell.readonly }, getEditorComponent);\n\t\tif (intent.mode !== 'overlay') return null;\n\t\tconst Editor = intent.editor;\n\t\tconst rowValue = (combinedRows[active.rowIndex] as Record<string, unknown> | undefined)?.[active.colKey];\n\t\tconst geom = computeOverlayGeometry(\n\t\t\ttypeof window !== 'undefined' ? window.innerHeight : 800,\n\t\t\tactive.anchorRect.top,\n\t\t\tactive.anchorRect.height,\n\t\t\tOVERLAY_MARGIN_PX,\n\t\t\tOVERLAY_MIN_BELOW_PX,\n\t\t);\n\t\treturn {\n\t\t\tpresetClass: Editor.overlayPresetClass,\n\t\t\t// Commit-on-click-away (Stage B): editors that own an onBlur→onCommit advertise it\n\t\t\t// so the OverlayManager dismisses by blurring (commit) instead of cancelling.\n\t\t\tdismissMode: Editor.commitsOnBlur ? ('commit' as const) : ('cancel' as const),\n\t\t\telement: (\n\t\t\t\t<Editor\n\t\t\t\t\tvalue={rowValue}\n\t\t\t\t\tcell={resolution.cell}\n\t\t\t\t\tcolKey={active.colKey}\n\t\t\t\t\trowId={getRowId(combinedRows[active.rowIndex], active.rowIndex)}\n\t\t\t\t\trowIndex={active.rowIndex}\n\t\t\t\t\ttableName={props.tableName}\n\t\t\t\t\tfieldMeta={resolution.fieldMeta}\n\t\t\t\t\trelationInfo={resolution.relationInfo}\n\t\t\t\t\tinitialText={active.initialText}\n\t\t\t\t\tonCommit={(next) => {\n\t\t\t\t\t\tcommitBulkOrSingle(active.rowIndex, active.colKey, next);\n\t\t\t\t\t\toverlayClose();\n\t\t\t\t\t}}\n\t\t\t\t\tonCommitPatch={(patch) => {\n\t\t\t\t\t\tshell.commitCellPatch(active.rowIndex, patch);\n\t\t\t\t\t\toverlayClose();\n\t\t\t\t\t}}\n\t\t\t\t\tonSubmitDraftRow={shell.submitDraftRow}\n\t\t\t\t\tonInvalidateData={shell.invalidateData}\n\t\t\t\t\tonCancel={overlayClose}\n\t\t\t\t\toverlay={{ maxHeight: geom.maxHeight, flipped: geom.shouldFlip }}\n\t\t\t\t/>\n\t\t\t),\n\t\t};\n\t})();\n\n\t// INFINITE SCROLL: the virtualizer COUNT is left to its default (`rows.length`) — in\n\t// infinite mode `combinedRows` IS the full-length proxy (`serverRowCount + drafts`, null-backing\n\t// unloaded indices), so `rows.length` already spans every lazy row AND includes drafts; forcing\n\t// `count = totalCount` would drop the appended draft rows. We only wire the prefetch handler:\n\t// the viewport's overscan-inclusive {startIndex,endIndex} window IS the native range the shell\n\t// prefetches against (handleVisibleRegionChanged no-ops when paginated + clamps to the server\n\t// row count, but we still attach only in infinite mode, matching the prior paginated omission).\n\tconst onVisibleRegionChanged = shell.onVisibleRegionChanged;\n\tconst onVisibleRangeChange = useCallback(\n\t\t(range: VisibleRange) => {\n\t\t\tonVisibleRegionChanged(range);\n\t\t},\n\t\t[onVisibleRegionChanged],\n\t);\n\n\t// Sort caret state mirror (the shell owns it via useGridState). The shell's onHeaderClicked is\n\t// the sort toggle keyed by colIndex (the draft-action column is excluded as non-sortable); the\n\t// DOM header speaks colKey, so map back to the colIndex it expects via columnKeys.\n\tconst sorting = shell.sorting;\n\tconst onHeaderClicked = shell.onHeaderClicked;\n\tconst columnKeys = shell.columnKeys;\n\t// Header click routes through the ONE pipeline as `header.sortToggle`; the command body calls\n\t// ctx.sortToggle(colKey), which maps the colKey back to the colIndex onHeaderClicked expects.\n\tconst onHeaderClick = useCallback((colKey: string) => dispatch('header.sortToggle', undefined, { colKey }), [dispatch]);\n\n\t// Fill-handle drag release routes through the ONE pipeline as `fill.drag`; the command extends\n\t// the source band toward `target`, replicates the source values, and widens the selection.\n\tconst handleFillDrag = useCallback(\n\t\t(sourceRange: SelectionRect, target: [number, number]) => dispatch('fill.drag', undefined, { from: sourceRange, to: target }),\n\t\t[dispatch],\n\t);\n\n\t// ============== ASSEMBLE + LATCH THE GRID COMMAND CONTEXT ==============\n\t// ONE object the commands run against: live GETTERS read the existing refs/derived render\n\t// values; methods are the EXISTING stable callbacks wrapped VERBATIM (no dispatcher is\n\t// reinvented). Rebuilt each render (cheap) and REPOINTED into `ctxRef` so `dispatch`\n\t// (stable, reads ctxRef.current) always sees the latest values — mirrors the openEditor\n\t// ref-latch. The pointer callbacks threaded into renderCell close over `dispatch`, not this,\n\t// so the per-cell memo is unaffected.\n\tctxRef.current = {\n\t\tget rowCount() {\n\t\t\treturn combinedRowsRef.current.length;\n\t\t},\n\t\tget colCount() {\n\t\t\treturn columnsRef.current.length;\n\t\t},\n\t\tget activeCell() {\n\t\t\treturn selectionRef.current?.current?.cell;\n\t\t},\n\t\tget selection() {\n\t\t\treturn selectionRef.current;\n\t\t},\n\t\tget combinedRows() {\n\t\t\treturn combinedRowsRef.current;\n\t\t},\n\t\tget columnKeys() {\n\t\t\treturn columnsRef.current.map((c) => c.key);\n\t\t},\n\t\tgetAnchor: () => anchorRef.current,\n\t\tsetAnchor: (anchor) => {\n\t\t\tanchorRef.current = anchor;\n\t\t},\n\t\tsetActiveCell,\n\t\tmoveActiveCell,\n\t\textendToCell,\n\t\tsetSelection: setSelectionRange,\n\t\tcommitCells,\n\t\topenEditorAtActive: openEditorAtActiveCell,\n\t\topenEditorAt: openEditorImpl,\n\t\tundo,\n\t\tredo,\n\t\tscrollToCell: (col, row) => viewportRef.current?.scrollToCell(col, row),\n\t\tsortToggle: (colKey) => onHeaderClicked(columnKeys.indexOf(colKey)),\n\t\ttoggleRow: toggleRowImpl,\n\t\ttoggleAll: toggleAllImpl,\n\t\tgetCellsInRange: (rect: SelectionRect): CellMatrix => {\n\t\t\tconst r = extractCellsInRange(rect, combinedRowsRef.current, columnsRef.current.map((c) => c.key));\n\t\t\treturn { cols: r.cols, rows: r.rows, values: r.values };\n\t\t},\n\t\ttoTSV: (values) => serializeTSV(values),\n\t\temit,\n\t} satisfies GridCommandContext;\n\n\t// ============== LOAD STATES ==============\n\t// Surface real error/empty/loading states instead of a blank grid (moved here from\n\t// the removed canvas branch). The full-screen error is for INITIAL-load failure only\n\t// (no server rows AND no drafts); background-refetch errors keep the populated grid\n\t// mounted and surface via the `load:error` onEvent emission instead.\n\tif (s.dataError && shell.combinedRows.length === 0) {\n\t\tconst retry = () => s.refetch();\n\t\tif (slots?.error) {\n\t\t\treturn <>{slots.error({ error: s.dataError, retry })}</>;\n\t\t}\n\t\treturn <SheetsErrorState error={s.dataError} onRetry={retry} />;\n\t}\n\n\t// Initial load only; same-scope refetches retain their current query data.\n\tif (s.isInitialLoading) {\n\t\tif (slots?.loading) return <>{slots.loading}</>;\n\t\treturn <SheetsLoadingState />;\n\t}\n\n\t// Loaded successfully but no server rows and nothing drafted yet (and no active filter).\n\tif (s.isEmpty) {\n\t\tif (slots?.empty) {\n\t\t\treturn <>{typeof slots.empty === 'function' ? slots.empty({ tableName }) : slots.empty}</>;\n\t\t}\n\t\treturn (\n\t\t\t<SheetsEmptyState\n\t\t\t\ttableName={tableName}\n\t\t\t\treadOnlyReason={shell.readOnlyReason}\n\t\t\t\tonAddRow={shell.canCreate ? () => {\n\t\t\t\t\tvoid s.draft.appendRow();\n\t\t\t\t} : undefined}\n\t\t\t/>\n\t\t);\n\t}\n\n\t// Filtered-empty: the server returned 0 rows while a filter is active (so `isEmpty` above is\n\t// false — it requires no filter). Without this the body renders blank under the header and looks\n\t// broken; instead we keep the toolbar/filter bar mounted and overlay a \"No matching rows\" panel\n\t// with a one-click clear back to the unfiltered set.\n\tconst activeFilterCount = shell.filterTree ? countConditions(shell.filterTree) : 0;\n\tconst isFilteredEmpty = shell.serverRowCount === 0 && shell.draftRowCount === 0 && activeFilterCount > 0;\n\n\treturn (\n\t\t<SheetsErrorBoundary onError={config.onError}>\n\t\t\t{/* Controls — consumer toolbar slot replaces the default <SheetsControls> block. */}\n\t\t\t<div data-part-id='sheets-controls-container'>\n\t\t\t\t{slots?.toolbar ? (\n\t\t\t\t\t<>{typeof slots.toolbar === 'function' ? slots.toolbar({ tableName }) : slots.toolbar}</>\n\t\t\t\t) : (\n\t\t\t\t\t<SheetsControls\n\t\t\t\t\t\tfilterTree={shell.filterTree}\n\t\t\t\t\t\tsetFilterTree={shell.setFilterTree}\n\t\t\t\t\t\tfiltersOpen={shell.filtersOpen}\n\t\t\t\t\t\tsetFiltersOpen={shell.setFiltersOpen}\n\t\t\t\t\t\tclearAllFilters={shell.clearAllFilters}\n\t\t\t\t\t\tapplyFilters={shell.applyFilters}\n\t\t\t\t\t\tcolumnKeys={shell.columnKeys}\n\t\t\t\t\t\tfieldTypeMap={shell.fieldTypeMap}\n\t\t\t\t\t\tshowSelection={showSelection}\n\t\t\t\t\t\tgridSelection={s.selection.gridSelection ?? null}\n\t\t\t\t\t\tsetGridSelection={shell.setGridSelectionForControls}\n\t\t\t\t\t\tdeleteSelected={s.draft.deleteSelected}\n\t\t\t\t\t\tonAddRow={shell.canCreate ? handleAddRow : undefined}\n\t\t\t\t\t\tcanDelete={shell.canDelete}\n\t\t\t\t\t\treadOnlyReason={shell.readOnlyReason}\n\t\t\t\t\t\tonExport={handleExport}\n\t\t\t\t\t/>\n\t\t\t\t)}\n\t\t\t</div>\n\n\t\t\t<div\n\t\t\t\tdata-part-id='sheets-container'\n\t\t\t\trole='region'\n\t\t\t\taria-label={`${tableName} table`}\n\t\t\t\tclassName={cn('bg-background relative isolate h-full min-h-0 flex-1 overflow-hidden rounded-lg border', className)}\n\t\t\t>\n\t\t\t\t<GridViewport\n\t\t\t\t\ttable={table}\n\t\t\t\t\trenderCell={renderCell}\n\t\t\t\t\thandleRef={viewportRef}\n\t\t\t\t\tonScroll={handleOverlayScroll}\n\t\t\t\t\tsorting={sorting}\n\t\t\t\t\tonHeaderClick={onHeaderClick}\n\t\t\t\t\tonResize={resizeColumn}\n\t\t\t\t\tonVisibleRangeChange={infiniteScroll ? onVisibleRangeChange : undefined}\n\t\t\t\t\trowMarker={showSelection ? rowMarker : undefined}\n\t\t\t\t\tactiveCell={activeCell}\n\t\t\t\t\tactiveRange={s.selection.gridSelection?.current?.range}\n\t\t\t\t\tonGridKeyDown={handleGridKeyDown}\n\t\t\t\t\tonCopy={handleCopy}\n\t\t\t\t\tonCut={handleCut}\n\t\t\t\t\tonPaste={handlePaste}\n\t\t\t\t\tonFillDrag={handleFillDrag}\n\t\t\t\t\tactiveDescendantId={activeCell ? `sheets-cell-${activeCell[1]}-${activeCell[0]}` : undefined}\n\t\t\t\t/>\n\n\t\t\t\t{/* Filtered-empty panel — overlays the empty body while the filter bar stays visible above. */}\n\t\t\t\t{isFilteredEmpty && (\n\t\t\t\t\t<div className='bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-center'>\n\t\t\t\t\t\t<RiSearchEyeLine className='text-muted-foreground h-8 w-8' />\n\t\t\t\t\t\t<div className='space-y-1'>\n\t\t\t\t\t\t\t<p className='text-foreground text-sm font-medium'>No matching rows</p>\n\t\t\t\t\t\t\t<p className='text-muted-foreground max-w-md text-sm'>\n\t\t\t\t\t\t\t\tNo rows match the active {activeFilterCount === 1 ? 'filter' : 'filters'}.\n\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<Button variant='outline' size='sm' onClick={shell.clearAllFilters}>\n\t\t\t\t\t\t\t<RiFilterOffLine className='h-4 w-4' />\n\t\t\t\t\t\t\t<span className='ms-1'>Clear filters</span>\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</div>\n\t\t\t\t)}\n\n\t\t\t\t{/* Floating status indicator — surfaces save/delete/submit feedback from the FeedbackProvider. */}\n\t\t\t\t<div className='pointer-events-none absolute bottom-4 left-1/2 z-10 -translate-x-1/2'>\n\t\t\t\t\t<FloatingStatus />\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t{/* Pagination — hidden in infinite scroll mode (canvas parity). */}\n\t\t\t{showPagination && !infiniteScroll && s.pagination.pageCount > 1 && (\n\t\t\t\t<SheetsPagination\n\t\t\t\t\tpageIndex={s.pagination.pageIndex}\n\t\t\t\t\tpageSize={pageSize}\n\t\t\t\t\ttotalCount={shell.totalCount}\n\t\t\t\t\ttotalPages={s.pagination.pageCount}\n\t\t\t\t\tsetPageIndex={s.pagination.setPageIndex}\n\t\t\t\t/>\n\t\t\t)}\n\n\t\t\t<OverlayManager\n\t\t\t\topen={overlay.isOpen && editorNode != null}\n\t\t\t\tanchorRect={active?.anchorRect ?? null}\n\t\t\t\tpresetClass={editorNode?.presetClass}\n\t\t\t\tdismissMode={editorNode?.dismissMode}\n\t\t\t\tonCancel={overlayClose}\n\t\t\t>\n\t\t\t\t{editorNode?.element}\n\t\t\t</OverlayManager>\n\n\t\t\t{/* Right-click context menu — items dispatch through the SAME pipeline as keys/clicks\n\t\t\t (clipboard.* with no native event take the navigator.clipboard fallback). Rendered once. */}\n\t\t\t<SheetsContextMenu\n\t\t\t\tstate={contextMenu}\n\t\t\t\tonClose={closeContextMenu}\n\t\t\t\tonAction={(commandId) => dispatch(commandId)}\n\t\t\t\tisEnabled={isCommandEnabled}\n\t\t\t\tonAddRow={handleAddRow}\n\t\t\t\tonDeleteRows={s.draft.deleteSelected}\n\t\t\t\tselectedRowCount={selection?.rows.length ?? 0}\n\t\t\t\tcanAddRows={shell.canCreate}\n\t\t\t\tcanDeleteRows={shell.canDelete}\n\t\t\t/>\n\t\t</SheetsErrorBoundary>\n\t);\n}\n\n// Public props alias — generic over the consumer's row type (default SheetsRow keeps\n// existing untyped callers compiling). Carries DataGridProps' TRow through.\nexport type SheetsProps<TRow extends SheetsRow = SheetsRow> = DataGridProps<TRow>;\n","import { memo, useCallback, useEffect, useMemo, useState } from \"react\";\nimport {\n RiAddLine,\n RiCloseCircleLine,\n RiDeleteBin6Line,\n RiDownloadLine,\n RiFilter3Line,\n RiSearch2Line,\n} from \"@remixicon/react\";\n\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n AlertDialogTrigger,\n} from \"@constructive-io/ui/alert-dialog\";\nimport { Button } from \"@constructive-io/ui/button\";\nimport { Input } from \"@constructive-io/ui/input\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"@constructive-io/ui/popover\";\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from \"@constructive-io/ui/select\";\n\nimport {\n getDefaultOperator,\n getOperatorsForGqlType,\n isFilterableType,\n type FilterOperator,\n type OperatorValueType,\n} from \"./filter-operators\";\nimport type { SheetsSelection } from \"../selection/selection-model\";\n\n// Filter value can be string, number, boolean, null, or undefined\n// This matches the usage in buildWhereFromFilters and GraphQL filter operations\nexport type FilterValue = string | number | boolean | null | undefined;\n\n// ── Filter tree types ──\n\nexport type FilterNode = FilterCondition | FilterGroup;\n\nexport interface FilterCondition {\n type: \"condition\";\n id: string;\n field: string;\n operator: string;\n value: FilterValue;\n}\n\nexport interface FilterGroup {\n type: \"group\";\n id: string;\n conjunction: \"and\" | \"or\";\n children: FilterNode[];\n}\n\nexport const MAX_FILTER_DEPTH = 3;\n\nexport type FieldTypeMap = Record<string, { gqlType: string; isArray: boolean }>;\n\n// ── Tree helpers ──\n\nfunction uid(): string {\n return Math.random().toString(36).slice(2, 9);\n}\n\nexport function createEmptyGroup(conjunction: \"and\" | \"or\" = \"and\"): FilterGroup {\n return { type: \"group\", id: uid(), conjunction, children: [] };\n}\n\nfunction createCondition(field: string, operator: string): FilterCondition {\n return { type: \"condition\", id: uid(), field, operator, value: \"\" };\n}\n\nexport function countConditions(node: FilterNode): number {\n if (node.type === \"condition\") return 1;\n return node.children.reduce((sum, child) => sum + countConditions(child), 0);\n}\n\nexport interface SheetsControlsProps {\n openSearch?: () => void;\n filterTree: FilterGroup;\n setFilterTree: (tree: FilterGroup) => void;\n filtersOpen: boolean;\n setFiltersOpen: (open: boolean) => void;\n clearAllFilters: () => void;\n applyFilters: () => void;\n columnKeys: string[];\n fieldTypeMap: FieldTypeMap;\n showSelection: boolean;\n gridSelection: SheetsSelection | null;\n setGridSelection: (selection: SheetsSelection | null) => void;\n deleteSelected: () => void;\n onAddRow?: () => void;\n onExport?: () => void;\n canDelete?: boolean;\n readOnlyReason?: string | null;\n}\n\nfunction getInputType(valueType: OperatorValueType): string {\n switch (valueType) {\n case \"number\":\n return \"number\";\n case \"date\":\n return \"date\";\n case \"datetime\":\n return \"datetime-local\";\n default:\n return \"text\";\n }\n}\n\nfunction getPlaceholder(valueType: OperatorValueType): string {\n if (valueType === \"key\") return \"key name\";\n return \"Value...\";\n}\n\n/** Parse a JSON-encoded IntervalInput string into individual fields. */\nfunction parseIntervalValue(raw: FilterValue): {\n days: string;\n hours: string;\n minutes: string;\n seconds: string;\n} {\n const empty = { days: \"\", hours: \"\", minutes: \"\", seconds: \"\" };\n if (!raw || typeof raw !== \"string\") return empty;\n try {\n const obj = JSON.parse(raw);\n return {\n days: obj.days ? String(obj.days) : \"\",\n hours: obj.hours ? String(obj.hours) : \"\",\n minutes: obj.minutes ? String(obj.minutes) : \"\",\n seconds: obj.seconds ? String(obj.seconds) : \"\",\n };\n } catch {\n return empty;\n }\n}\n\n/** Compose individual interval fields into a JSON-encoded IntervalInput string. */\nfunction composeIntervalValue(fields: {\n days: string;\n hours: string;\n minutes: string;\n seconds: string;\n}): string {\n const obj: Record<string, number> = {};\n const d = parseInt(fields.days, 10);\n const h = parseInt(fields.hours, 10);\n const m = parseInt(fields.minutes, 10);\n const s = parseInt(fields.seconds, 10);\n if (!isNaN(d) && d !== 0) obj.days = d;\n if (!isNaN(h) && h !== 0) obj.hours = h;\n if (!isNaN(m) && m !== 0) obj.minutes = m;\n if (!isNaN(s) && s !== 0) obj.seconds = s;\n return Object.keys(obj).length > 0 ? JSON.stringify(obj) : \"\";\n}\n\n/** Structured interval input — renders d/h/m/s number fields that map to IntervalInput. */\nfunction IntervalFilterInput({\n value,\n onChange,\n}: {\n value: FilterValue;\n onChange: (v: string) => void;\n}) {\n const fields = useMemo(() => parseIntervalValue(value), [value]);\n\n const handleChange = useCallback(\n (unit: \"days\" | \"hours\" | \"minutes\" | \"seconds\", v: string) => {\n onChange(composeIntervalValue({ ...fields, [unit]: v }));\n },\n [fields, onChange],\n );\n\n return (\n <div className=\"flex items-center gap-1\">\n <Input\n className=\"w-[52px] px-1.5 text-center\"\n type=\"number\"\n placeholder=\"d\"\n min={0}\n value={fields.days}\n onChange={(e) => handleChange(\"days\", e.target.value)}\n />\n <Input\n className=\"w-[52px] px-1.5 text-center\"\n type=\"number\"\n placeholder=\"h\"\n min={0}\n max={23}\n value={fields.hours}\n onChange={(e) => handleChange(\"hours\", e.target.value)}\n />\n <Input\n className=\"w-[52px] px-1.5 text-center\"\n type=\"number\"\n placeholder=\"m\"\n min={0}\n max={59}\n value={fields.minutes}\n onChange={(e) => handleChange(\"minutes\", e.target.value)}\n />\n <Input\n className=\"w-[52px] px-1.5 text-center\"\n type=\"number\"\n placeholder=\"s\"\n min={0}\n max={59}\n value={fields.seconds}\n onChange={(e) => handleChange(\"seconds\", e.target.value)}\n />\n </div>\n );\n}\n\nconst FilterConditionRow = memo(function FilterConditionRow({\n condition,\n columns,\n fieldTypeMap,\n onChange,\n onRemove,\n}: {\n condition: FilterCondition;\n columns: readonly string[];\n fieldTypeMap: FieldTypeMap;\n onChange: (updates: Partial<FilterCondition>) => void;\n onRemove: () => void;\n}) {\n const typeInfo = fieldTypeMap[condition.field];\n const operators = useMemo<FilterOperator[]>(\n () => getOperatorsForGqlType(typeInfo?.gqlType, typeInfo?.isArray ?? false),\n [typeInfo?.gqlType, typeInfo?.isArray],\n );\n const currentOp = operators.find((o) => o.operator === condition.operator) ?? operators[0];\n\n const handleColumnChange = useCallback(\n (newField: string) => {\n const info = fieldTypeMap[newField];\n const defaultOp = getDefaultOperator(info?.gqlType, info?.isArray ?? false) ?? \"equalTo\";\n onChange({ field: newField, operator: defaultOp, value: \"\" });\n },\n [fieldTypeMap, onChange],\n );\n\n const handleOperatorChange = useCallback(\n (newOp: string) => {\n const opEntry = operators.find((o) => o.operator === newOp);\n if (opEntry?.valueType === \"none\") {\n onChange({ operator: newOp, value: \"\" });\n } else {\n onChange({ operator: newOp });\n }\n },\n [operators, onChange],\n );\n\n return (\n <div className=\"flex items-center gap-2\">\n <Select value={condition.field} onValueChange={handleColumnChange}>\n <SelectTrigger className=\"w-[140px]\">\n <SelectValue placeholder=\"Column\" />\n </SelectTrigger>\n <SelectContent>\n {columns.map((k) => (\n <SelectItem key={k} value={k}>\n {k}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n\n {operators.length > 0 && (\n <Select value={currentOp?.operator ?? \"\"} onValueChange={handleOperatorChange}>\n <SelectTrigger className=\"w-[130px]\">\n <SelectValue placeholder=\"Operator\" />\n </SelectTrigger>\n <SelectContent>\n {operators.map((op) => (\n <SelectItem key={op.operator} value={op.operator}>\n {op.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )}\n\n {currentOp && currentOp.valueType === \"interval\" && (\n <IntervalFilterInput value={condition.value} onChange={(v) => onChange({ value: v })} />\n )}\n\n {currentOp && currentOp.valueType !== \"none\" && currentOp.valueType !== \"interval\" && (\n <Input\n className=\"w-[150px]\"\n type={getInputType(currentOp.valueType)}\n placeholder={getPlaceholder(currentOp.valueType)}\n value={\n typeof condition.value === \"string\" || typeof condition.value === \"number\"\n ? String(condition.value)\n : \"\"\n }\n onChange={(e) => onChange({ value: e.target.value })}\n />\n )}\n\n <Button variant=\"ghost\" size=\"icon\" onClick={onRemove} aria-label=\"Remove filter\">\n <RiCloseCircleLine className=\"h-4 w-4\" />\n </Button>\n </div>\n );\n});\n\n/** Recursive filter group UI — renders AND/OR toggle + conditions + nested groups. */\nconst FilterGroupUI = memo(function FilterGroupUI({\n group,\n depth,\n fieldTypeMap,\n filterableColumns,\n onChange,\n onRemove,\n}: {\n group: FilterGroup;\n depth: number;\n fieldTypeMap: FieldTypeMap;\n filterableColumns: readonly string[];\n onChange: (updated: FilterGroup) => void;\n onRemove?: () => void;\n}) {\n const toggleConjunction = useCallback(() => {\n onChange({ ...group, conjunction: group.conjunction === \"and\" ? \"or\" : \"and\" });\n }, [group, onChange]);\n\n const addCondition = useCallback(() => {\n const firstCol = filterableColumns[0];\n if (!firstCol) return;\n const info = fieldTypeMap[firstCol];\n const defaultOp = getDefaultOperator(info?.gqlType, info?.isArray ?? false) ?? \"equalTo\";\n onChange({ ...group, children: [...group.children, createCondition(firstCol, defaultOp)] });\n }, [group, filterableColumns, fieldTypeMap, onChange]);\n\n const addGroup = useCallback(() => {\n const childConj = group.conjunction === \"and\" ? \"or\" : \"and\";\n onChange({ ...group, children: [...group.children, createEmptyGroup(childConj)] });\n }, [group, onChange]);\n\n const updateChild = useCallback(\n (childId: string, updated: FilterNode) => {\n onChange({ ...group, children: group.children.map((c) => (c.id === childId ? updated : c)) });\n },\n [group, onChange],\n );\n\n const removeChild = useCallback(\n (childId: string) => {\n onChange({ ...group, children: group.children.filter((c) => c.id !== childId) });\n },\n [group, onChange],\n );\n\n return (\n <div className={depth > 0 ? \"border-muted-foreground/20 ml-1 border-l-2 pl-3\" : undefined}>\n <div className=\"mb-2 flex items-center gap-1.5\">\n <span className=\"text-muted-foreground text-xs\">Match</span>\n <Button\n variant=\"outline\"\n size=\"sm\"\n className=\"h-6 px-2 text-xs font-medium\"\n onClick={toggleConjunction}\n >\n {group.conjunction === \"and\" ? \"all\" : \"any\"}\n </Button>\n <span className=\"text-muted-foreground text-xs\">of:</span>\n {onRemove && (\n <Button\n variant=\"ghost\"\n size=\"icon\"\n className=\"ml-auto h-6 w-6\"\n onClick={onRemove}\n aria-label=\"Remove group\"\n >\n <RiCloseCircleLine className=\"h-3.5 w-3.5\" />\n </Button>\n )}\n </div>\n\n <div className=\"grid gap-2\">\n {group.children.map((child) => {\n if (child.type === \"condition\") {\n return (\n <FilterConditionRow\n key={child.id}\n condition={child}\n columns={filterableColumns}\n fieldTypeMap={fieldTypeMap}\n onChange={(updates) => updateChild(child.id, { ...child, ...updates })}\n onRemove={() => removeChild(child.id)}\n />\n );\n }\n return (\n <FilterGroupUI\n key={child.id}\n group={child}\n depth={depth + 1}\n fieldTypeMap={fieldTypeMap}\n filterableColumns={filterableColumns}\n onChange={(updated) => updateChild(child.id, updated)}\n onRemove={() => removeChild(child.id)}\n />\n );\n })}\n </div>\n\n <div className=\"mt-2 flex items-center gap-2\">\n <Button variant=\"ghost\" size=\"sm\" className=\"h-7 text-xs\" onClick={addCondition}>\n <RiAddLine className=\"mr-1 h-3.5 w-3.5\" /> Condition\n </Button>\n {depth < MAX_FILTER_DEPTH - 1 && (\n <Button variant=\"ghost\" size=\"sm\" className=\"h-7 text-xs\" onClick={addGroup}>\n <RiAddLine className=\"mr-1 h-3.5 w-3.5\" /> Group\n </Button>\n )}\n </div>\n </div>\n );\n});\n\nexport function SheetsControls(props: SheetsControlsProps) {\n const {\n openSearch,\n filterTree,\n setFilterTree,\n filtersOpen,\n setFiltersOpen,\n clearAllFilters,\n applyFilters,\n columnKeys,\n fieldTypeMap,\n showSelection,\n gridSelection,\n deleteSelected,\n onAddRow,\n onExport,\n canDelete = true,\n readOnlyReason,\n } = props;\n\n const filterableColumns = useMemo(() => {\n if (Object.keys(fieldTypeMap).length === 0) return columnKeys;\n return columnKeys.filter((k) => {\n const info = fieldTypeMap[k];\n if (!info) return false;\n return isFilterableType(info.gqlType, info.isArray);\n });\n }, [columnKeys, fieldTypeMap]);\n\n // ── Local filter tree (only committed on Apply) ──\n const [localTree, setLocalTree] = useState<FilterGroup>(filterTree);\n\n // Sync local state when popover opens\n useEffect(() => {\n if (filtersOpen) {\n setLocalTree(filterTree);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- only trigger on popover open/close\n }, [filtersOpen]);\n\n const handleApplyFilters = useCallback(() => {\n setFilterTree(localTree);\n applyFilters();\n }, [localTree, setFilterTree, applyFilters]);\n\n const handleClearAllFilters = useCallback(() => {\n setLocalTree(createEmptyGroup());\n clearAllFilters();\n }, [clearAllFilters]);\n\n const conditionCount = useMemo(() => countConditions(localTree), [localTree]);\n\n const selectedRowCount = useMemo(() => {\n if (!gridSelection) return 0;\n return gridSelection.rows.length;\n }, [gridSelection]);\n\n return (\n <>\n <div\n data-part-id=\"sheets-controls\"\n className=\"flex shrink-0 flex-wrap items-center justify-between gap-4 py-4\"\n >\n <div className=\"flex min-w-0 flex-wrap items-center gap-2\">\n\t\t {readOnlyReason && (\n\t\t\t<span\n\t\t\t\tclassName=\"border-border bg-muted text-muted-foreground inline-flex h-8 items-center rounded-md border px-2.5 text-xs\"\n\t\t\t\trole=\"status\"\n\t\t\t\ttitle={readOnlyReason}\n\t\t\t>\n\t\t\t\tRead-only\n\t\t\t</span>\n\t\t )}\n <Button variant=\"outline\" size=\"sm\" onClick={() => openSearch?.()}>\n <RiSearch2Line className=\"text-muted-foreground/60 -ms-1.5 size-5\" aria-hidden=\"true\" />\n Search\n </Button>\n {onAddRow && (\n <Button variant=\"outline\" size=\"sm\" aria-label=\"Add row\" onClick={() => onAddRow()}>\n <RiAddLine className=\"text-muted-foreground/60 -ms-1.5 size-5\" aria-hidden=\"true\" />\n Add row\n </Button>\n )}\n {onExport && (\n <Button variant=\"outline\" size=\"sm\" aria-label=\"Export CSV\" onClick={() => onExport()}>\n <RiDownloadLine\n className=\"text-muted-foreground/60 -ms-1.5 size-5\"\n aria-hidden=\"true\"\n />\n Export\n </Button>\n )}\n </div>\n\n <div className=\"flex items-center gap-2\">\n {showSelection && (\n <AlertDialog>\n <AlertDialogTrigger asChild>\n <Button\n\t\t\t\t variant=\"destructive-outline\"\n\t\t\t\t size=\"sm\"\n\t\t\t\t disabled={!canDelete || selectedRowCount === 0}\n\t\t\t\t title={!canDelete ? readOnlyReason ?? 'Delete is unavailable for this table.' : undefined}\n\t\t\t\t>\n <RiDeleteBin6Line className=\"-ms-1.5 size-5\" aria-hidden=\"true\" />\n Delete\n {selectedRowCount > 0 ? ` (${selectedRowCount})` : \"\"}\n </Button>\n </AlertDialogTrigger>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>Delete rows?</AlertDialogTitle>\n <AlertDialogDescription>\n This will permanently delete {selectedRowCount}{\" \"}\n {selectedRowCount === 1 ? \"row\" : \"rows\"}. This action cannot be undone.\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel>Cancel</AlertDialogCancel>\n <AlertDialogAction\n className=\"bg-destructive text-white hover:bg-destructive/90\"\n onClick={() => deleteSelected()}\n >\n Delete\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n )}\n <Popover open={filtersOpen} onOpenChange={setFiltersOpen}>\n <PopoverTrigger asChild>\n <Button variant=\"outline\" size=\"sm\" className=\"relative\">\n <RiFilter3Line\n className=\"text-muted-foreground/60 -ms-1.5 size-5\"\n aria-hidden=\"true\"\n />\n Filters\n {countConditions(filterTree) > 0 && (\n <span\n className=\"border-border/60 bg-background text-muted-foreground/70 ms-2 -me-1 inline-flex h-5\n\t\t\t\t\t\t\t\t\t\t\tmax-h-full items-center rounded border px-1 font-[inherit] text-[0.625rem] font-medium\"\n >\n {countConditions(filterTree)}\n </span>\n )}\n </Button>\n </PopoverTrigger>\n <PopoverContent\n className=\"w-auto min-w-[28rem] max-h-[32rem] overflow-auto p-4\"\n align=\"end\"\n >\n <div className=\"grid gap-4\">\n <div className=\"space-y-2\">\n <h4 className=\"leading-none font-medium\">Filters</h4>\n </div>\n <FilterGroupUI\n group={localTree}\n depth={0}\n fieldTypeMap={fieldTypeMap}\n filterableColumns={filterableColumns}\n onChange={setLocalTree}\n />\n <div className=\"flex items-center justify-end gap-2 border-t pt-2\">\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={handleClearAllFilters}\n disabled={conditionCount === 0}\n >\n Clear all\n </Button>\n <Button size=\"sm\" onClick={handleApplyFilters}>\n Apply\n </Button>\n </div>\n </div>\n </PopoverContent>\n </Popover>\n </div>\n </div>\n </>\n );\n}\n","export type OperatorValueType = 'string' | 'number' | 'date' | 'datetime' | 'interval' | 'key' | 'none';\n\nexport interface FilterOperator {\n\toperator: string;\n\tlabel: string;\n\tvalueType: OperatorValueType;\n}\n\nconst TEXT_OPERATORS: FilterOperator[] = [\n\t{ operator: 'includesInsensitive', label: 'contains', valueType: 'string' },\n\t{ operator: 'equalTo', label: 'equals', valueType: 'string' },\n\t{ operator: 'notEqualTo', label: 'not equals', valueType: 'string' },\n\t{ operator: 'startsWithInsensitive', label: 'starts with', valueType: 'string' },\n\t{ operator: 'endsWithInsensitive', label: 'ends with', valueType: 'string' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst NUMERIC_OPERATORS: FilterOperator[] = [\n\t{ operator: 'equalTo', label: '=', valueType: 'number' },\n\t{ operator: 'notEqualTo', label: '\\u2260', valueType: 'number' },\n\t{ operator: 'greaterThan', label: '>', valueType: 'number' },\n\t{ operator: 'greaterThanOrEqualTo', label: '\\u2265', valueType: 'number' },\n\t{ operator: 'lessThan', label: '<', valueType: 'number' },\n\t{ operator: 'lessThanOrEqualTo', label: '\\u2264', valueType: 'number' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst BOOLEAN_OPERATORS: FilterOperator[] = [\n\t{ operator: 'equalTo:true', label: 'is true', valueType: 'none' },\n\t{ operator: 'equalTo:false', label: 'is false', valueType: 'none' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nfunction makeDateOperators(valueType: 'date' | 'datetime'): FilterOperator[] {\n\treturn [\n\t\t{ operator: 'equalTo', label: 'equals', valueType },\n\t\t{ operator: 'lessThan', label: 'before', valueType },\n\t\t{ operator: 'lessThanOrEqualTo', label: 'on or before', valueType },\n\t\t{ operator: 'greaterThan', label: 'after', valueType },\n\t\t{ operator: 'greaterThanOrEqualTo', label: 'on or after', valueType },\n\t\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n\t];\n}\n\nconst DATE_OPERATORS = makeDateOperators('date');\nconst DATETIME_OPERATORS = makeDateOperators('datetime');\n\nconst UUID_OPERATORS: FilterOperator[] = [\n\t{ operator: 'equalTo', label: 'equals', valueType: 'string' },\n\t{ operator: 'notEqualTo', label: 'not equals', valueType: 'string' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst INET_OPERATORS: FilterOperator[] = [\n\t{ operator: 'equalTo', label: 'equals', valueType: 'string' },\n\t{ operator: 'notEqualTo', label: 'not equals', valueType: 'string' },\n\t{ operator: 'contains', label: 'contains', valueType: 'string' },\n\t{ operator: 'containedBy', label: 'contained by', valueType: 'string' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst JSON_OPERATORS: FilterOperator[] = [\n\t{ operator: 'containsKey', label: 'has key', valueType: 'key' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst INTERVAL_OPERATORS: FilterOperator[] = [\n\t{ operator: 'equalTo', label: '=', valueType: 'interval' },\n\t{ operator: 'notEqualTo', label: '\\u2260', valueType: 'interval' },\n\t{ operator: 'greaterThan', label: '>', valueType: 'interval' },\n\t{ operator: 'greaterThanOrEqualTo', label: '\\u2265', valueType: 'interval' },\n\t{ operator: 'lessThan', label: '<', valueType: 'interval' },\n\t{ operator: 'lessThanOrEqualTo', label: '\\u2264', valueType: 'interval' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst ENUM_OPERATORS: FilterOperator[] = [\n\t{ operator: 'equalTo', label: 'equals', valueType: 'string' },\n\t{ operator: 'notEqualTo', label: 'not equals', valueType: 'string' },\n\t{ operator: 'isNull', label: 'is empty', valueType: 'none' },\n];\n\nconst GQL_TYPE_OPERATORS: Record<string, FilterOperator[]> = {\n\tString: TEXT_OPERATORS,\n\tInt: NUMERIC_OPERATORS,\n\tFloat: NUMERIC_OPERATORS,\n\tBigFloat: NUMERIC_OPERATORS,\n\tBigInt: NUMERIC_OPERATORS,\n\tBoolean: BOOLEAN_OPERATORS,\n\tDate: DATE_OPERATORS,\n\tDatetime: DATETIME_OPERATORS,\n\tUUID: UUID_OPERATORS,\n\tInternetAddress: INET_OPERATORS,\n\tJSON: JSON_OPERATORS,\n\tInterval: INTERVAL_OPERATORS,\n\tBitString: ENUM_OPERATORS,\n};\n\nconst UNFILTERABLE_TYPES = new Set(['GeoJSON', 'FullText']);\n\n/** Get available filter operators for a given gqlType. Returns empty array for unfilterable types. */\nexport function getOperatorsForGqlType(gqlType: string | null | undefined, isArray: boolean): FilterOperator[] {\n\tif (!gqlType || isArray || UNFILTERABLE_TYPES.has(gqlType)) return [];\n\treturn GQL_TYPE_OPERATORS[gqlType] ?? [];\n}\n\n/** Whether a field type can be filtered at all. */\nexport function isFilterableType(gqlType: string | null | undefined, isArray: boolean): boolean {\n\tif (!gqlType || isArray || UNFILTERABLE_TYPES.has(gqlType)) return false;\n\treturn gqlType in GQL_TYPE_OPERATORS;\n}\n\n/** Get the default (first) operator for a gqlType. */\nexport function getDefaultOperator(gqlType: string | null | undefined, isArray: boolean): string | undefined {\n\tconst ops = getOperatorsForGqlType(gqlType, isArray);\n\treturn ops[0]?.operator;\n}\n\n/** Whether an operator encodes its value and needs no user input. */\nexport function isValuelessOperator(operator: string): boolean {\n\treturn operator === 'isNull' || operator === 'equalTo:true' || operator === 'equalTo:false';\n}\n","/**\n * The right-click CONTEXT MENU (Stage B) — the showcase of the command layer: a menu is just\n * another EVENT SOURCE that resolves to named commands and runs through the SAME `dispatch`\n * pipeline as keys / clicks. Rendered ONCE at the grid level (never per-cell, so the per-cell\n * memo is untouched); the cell host calls `open(col, row, clientX, clientY)` on `onContextMenu`.\n *\n * Anchoring: Base UI's Menu anchors to its Trigger. We render a 0×0 FIXED trigger at the pointer\n * coordinates and toggle the controlled `open`, so the popup floats at the right-clicked cell.\n *\n * The ITEM MODEL is a pure builder (`buildContextMenuItems`) so the action→command mapping +\n * disabled gating is unit-testable WITHOUT the Base-UI popup (which needs a real layout env). The\n * component maps the model to <DropdownMenuItem>s. \"Delete row(s)\" is the one destructive action —\n * its `run` requests the SAME AlertDialog confirm the toolbar Delete uses.\n */\nimport { useState, type ReactNode } from 'react';\nimport { RiAddLine, RiClipboardLine, RiDeleteBin6Line, RiEraserLine, RiScissorsLine, RiFileCopyLine } from '@remixicon/react';\n\nimport {\n\tAlertDialog,\n\tAlertDialogAction,\n\tAlertDialogCancel,\n\tAlertDialogContent,\n\tAlertDialogDescription,\n\tAlertDialogFooter,\n\tAlertDialogHeader,\n\tAlertDialogTitle,\n} from '@constructive-io/ui/alert-dialog';\nimport {\n\tDropdownMenu,\n\tDropdownMenuContent,\n\tDropdownMenuItem,\n\tDropdownMenuSeparator,\n\tDropdownMenuShortcut,\n\tDropdownMenuTrigger,\n} from '@constructive-io/ui/dropdown-menu';\n\n/** Where the menu is anchored + the cell it acts on. `null` = closed. */\nexport interface ContextMenuState {\n\tclientX: number;\n\tclientY: number;\n}\n\n/** One row of the menu (or a separator). `run` fires on click; `disabled` greys it out. */\nexport interface ContextMenuItem {\n\tkey: string;\n\tseparator?: boolean;\n\tlabel?: string;\n\ticon?: ReactNode;\n\tshortcut?: string;\n\tdestructive?: boolean;\n\tdisabled?: boolean;\n\trun?: () => void;\n}\n\nexport interface BuildContextMenuItemsArgs {\n\t/** Dispatch a command id through the grid's stable dispatch pipeline. */\n\tonAction: (commandId: string) => void;\n\t/** True when the command's `canRun` passes against the latched context. */\n\tisEnabled: (commandId: string) => boolean;\n\t/** Append a draft row (the toolbar Add-row path). */\n\tonAddRow: () => void;\n\t/** Open the destructive delete confirm (the AlertDialog). */\n\trequestDelete: () => void;\n\t/** Count of currently selected rows — gates Delete + drives its label. */\n\tselectedRowCount: number;\n\tcanAddRows?: boolean;\n\tcanDeleteRows?: boolean;\n}\n\n/**\n * Pure menu model — the single source of truth for the items, their command mapping, and their\n * disabled state. Tested directly (no DOM). Clipboard / clear items dispatch their command id via\n * `onAction` and are disabled when `isEnabled(id)` is false; Add row / Delete use dedicated paths.\n */\nexport function buildContextMenuItems({\n\tonAction,\n\tisEnabled,\n\tonAddRow,\n\trequestDelete,\n\tselectedRowCount,\n\tcanAddRows = true,\n\tcanDeleteRows = true,\n}: BuildContextMenuItemsArgs): ContextMenuItem[] {\n\tconst cmd = (key: string, commandId: string, label: string, icon: ReactNode, shortcut?: string): ContextMenuItem => ({\n\t\tkey,\n\t\tlabel,\n\t\ticon,\n\t\tshortcut,\n\t\tdisabled: !isEnabled(commandId),\n\t\trun: () => onAction(commandId),\n\t});\n\treturn [\n\t\tcmd('copy', 'clipboard.copy', 'Copy', <RiFileCopyLine className='size-4' aria-hidden='true' />, '⌘C'),\n\t\tcmd('cut', 'clipboard.cut', 'Cut', <RiScissorsLine className='size-4' aria-hidden='true' />, '⌘X'),\n\t\tcmd('paste', 'clipboard.paste', 'Paste', <RiClipboardLine className='size-4' aria-hidden='true' />, '⌘V'),\n\t\tcmd('clear', 'cell.clear', 'Clear', <RiEraserLine className='size-4' aria-hidden='true' />),\n\t\t{ key: 'sep', separator: true },\n\t\t{\n\t\t\tkey: 'add-row',\n\t\t\tlabel: 'Add row',\n\t\t\ticon: <RiAddLine className='size-4' aria-hidden='true' />,\n\t\t\tdisabled: !canAddRows,\n\t\t\trun: onAddRow,\n\t\t},\n\t\t{\n\t\t\tkey: 'delete-rows',\n\t\t\tlabel: selectedRowCount > 1 ? `Delete ${selectedRowCount} rows` : 'Delete row',\n\t\t\ticon: <RiDeleteBin6Line className='size-4' aria-hidden='true' />,\n\t\t\tdestructive: true,\n\t\t\tdisabled: !canDeleteRows || selectedRowCount === 0,\n\t\t\trun: requestDelete,\n\t\t},\n\t];\n}\n\nexport interface SheetsContextMenuProps {\n\t/** Open anchor + position; `null` keeps the menu closed. */\n\tstate: ContextMenuState | null;\n\t/** Close the menu (clears `state`). */\n\tonClose: () => void;\n\t/** Dispatch a command id through the grid's stable dispatch pipeline. */\n\tonAction: (commandId: string) => void;\n\t/** True when the command's `canRun` passes against the latched context. */\n\tisEnabled: (commandId: string) => boolean;\n\t/** Append a draft row (the toolbar Add-row path). */\n\tonAddRow: () => void;\n\t/** Delete the selected row(s) (the toolbar deleteSelected path) — guarded by the AlertDialog. */\n\tonDeleteRows: () => void;\n\t/** Count of currently selected rows — drives the destructive dialog copy. */\n\tselectedRowCount: number;\n\tcanAddRows?: boolean;\n\tcanDeleteRows?: boolean;\n}\n\nexport function SheetsContextMenu({\n\tstate,\n\tonClose,\n\tonAction,\n\tisEnabled,\n\tonAddRow,\n\tonDeleteRows,\n\tselectedRowCount,\n\tcanAddRows = true,\n\tcanDeleteRows = true,\n}: SheetsContextMenuProps) {\n\tconst [confirmDelete, setConfirmDelete] = useState(false);\n\tconst open = state !== null;\n\n\tconst items = buildContextMenuItems({\n\t\tonAction,\n\t\tisEnabled,\n\t\tonAddRow,\n\t\trequestDelete: () => setConfirmDelete(true),\n\t\tselectedRowCount,\n\t\tcanAddRows,\n\t\tcanDeleteRows,\n\t});\n\n\treturn (\n\t\t<>\n\t\t\t<DropdownMenu open={open} onOpenChange={(next) => !next && onClose()}>\n\t\t\t\t{/* 0×0 fixed anchor at the pointer — the menu floats from here. */}\n\t\t\t\t<DropdownMenuTrigger\n\t\t\t\t\taria-hidden\n\t\t\t\t\ttabIndex={-1}\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\tposition: 'fixed',\n\t\t\t\t\t\tleft: state?.clientX ?? 0,\n\t\t\t\t\t\ttop: state?.clientY ?? 0,\n\t\t\t\t\t\twidth: 0,\n\t\t\t\t\t\theight: 0,\n\t\t\t\t\t}}\n\t\t\t\t/>\n\t\t\t\t<DropdownMenuContent align='start'>\n\t\t\t\t\t{items.map((item) =>\n\t\t\t\t\t\titem.separator ? (\n\t\t\t\t\t\t\t<DropdownMenuSeparator key={item.key} />\n\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t<DropdownMenuItem\n\t\t\t\t\t\t\t\tkey={item.key}\n\t\t\t\t\t\t\t\tvariant={item.destructive ? 'destructive' : 'default'}\n\t\t\t\t\t\t\t\tdisabled={item.disabled}\n\t\t\t\t\t\t\t\tonClick={() => {\n\t\t\t\t\t\t\t\t\t// Run then close — a menu pick is a one-shot (the popup dismisses).\n\t\t\t\t\t\t\t\t\titem.run?.();\n\t\t\t\t\t\t\t\t\tonClose();\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{item.icon}\n\t\t\t\t\t\t\t\t{item.label}\n\t\t\t\t\t\t\t\t{item.shortcut && <DropdownMenuShortcut>{item.shortcut}</DropdownMenuShortcut>}\n\t\t\t\t\t\t\t</DropdownMenuItem>\n\t\t\t\t\t\t),\n\t\t\t\t\t)}\n\t\t\t\t</DropdownMenuContent>\n\t\t\t</DropdownMenu>\n\n\t\t\t{/* Destructive confirm — mirrors the toolbar Delete AlertDialog. Driven open after the\n\t\t\t menu closes so the two overlays never fight for focus. */}\n\t\t\t<AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>\n\t\t\t\t<AlertDialogContent>\n\t\t\t\t\t<AlertDialogHeader>\n\t\t\t\t\t\t<AlertDialogTitle>Delete rows?</AlertDialogTitle>\n\t\t\t\t\t\t<AlertDialogDescription>\n\t\t\t\t\t\t\tThis will permanently delete {selectedRowCount} {selectedRowCount === 1 ? 'row' : 'rows'}. This action cannot be\n\t\t\t\t\t\t\tundone.\n\t\t\t\t\t\t</AlertDialogDescription>\n\t\t\t\t\t</AlertDialogHeader>\n\t\t\t\t\t<AlertDialogFooter>\n\t\t\t\t\t\t<AlertDialogCancel>Cancel</AlertDialogCancel>\n\t\t\t\t\t\t<AlertDialogAction\n\t\t\t\t\t\t\tclassName='bg-destructive text-white hover:bg-destructive/90'\n\t\t\t\t\t\t\tonClick={() => {\n\t\t\t\t\t\t\t\tonDeleteRows();\n\t\t\t\t\t\t\t\tsetConfirmDelete(false);\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\tDelete\n\t\t\t\t\t\t</AlertDialogAction>\n\t\t\t\t\t</AlertDialogFooter>\n\t\t\t\t</AlertDialogContent>\n\t\t\t</AlertDialog>\n\t\t</>\n\t);\n}\n","'use client';\n\nimport { createContext, useCallback, useContext, useEffect, useMemo, useReducer, useRef } from 'react';\n\nimport {\n\tcreateInitialState,\n\tfeedbackReducer,\n\tgenerateOperationId,\n\tgetDefaultDismissDuration,\n\ttype FeedbackState,\n\ttype OperationFeedback,\n} from './feedback-reducer';\n\ninterface FeedbackContextValue {\n\tstate: FeedbackState;\n\n\t// Operation feedback actions\n\tstartOperation: (type: OperationFeedback['type'], total: number) => string;\n\tupdateOperationProgress: (id: string, completed: number, failed: number) => void;\n\tcompleteOperation: (\n\t\tid: string,\n\t\tstatus: 'success' | 'partial' | 'error',\n\t\tmessage: string,\n\t\tdismissAfter?: number,\n\t) => void;\n\tclearOperationFeedback: () => void;\n}\n\nconst FeedbackContext = createContext<FeedbackContextValue | null>(null);\n\ninterface FeedbackProviderProps {\n\tchildren: React.ReactNode;\n}\n\nexport function FeedbackProvider({ children }: FeedbackProviderProps) {\n\tconst [state, dispatch] = useReducer(feedbackReducer, undefined, createInitialState);\n\n\t// Track timeout for auto-clearing operation feedback\n\tconst operationTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n\t// Cleanup timeout on unmount\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tif (operationTimeoutRef.current) {\n\t\t\t\tclearTimeout(operationTimeoutRef.current);\n\t\t\t}\n\t\t};\n\t}, []);\n\n\t// Operation feedback actions\n\tconst startOperation = useCallback((type: OperationFeedback['type'], total: number): string => {\n\t\t// Clear any pending operation timeout\n\t\tif (operationTimeoutRef.current) {\n\t\t\tclearTimeout(operationTimeoutRef.current);\n\t\t\toperationTimeoutRef.current = null;\n\t\t}\n\t\tconst id = generateOperationId();\n\t\tdispatch({ type: 'OPERATION_START', operationType: type, total, id });\n\t\treturn id;\n\t}, []);\n\n\tconst updateOperationProgress = useCallback((id: string, completed: number, failed: number) => {\n\t\tdispatch({ type: 'OPERATION_PROGRESS', id, completed, failed });\n\t}, []);\n\n\tconst completeOperation = useCallback(\n\t\t(id: string, status: 'success' | 'partial' | 'error', message: string, dismissAfter?: number) => {\n\t\t\tconst duration = dismissAfter ?? getDefaultDismissDuration(status);\n\t\t\tdispatch({ type: 'OPERATION_COMPLETE', id, status, message, dismissAfter: duration });\n\n\t\t\t// Auto-dismiss if duration > 0\n\t\t\tif (duration > 0) {\n\t\t\t\toperationTimeoutRef.current = setTimeout(() => {\n\t\t\t\t\tdispatch({ type: 'OPERATION_CLEAR' });\n\t\t\t\t\toperationTimeoutRef.current = null;\n\t\t\t\t}, duration);\n\t\t\t}\n\t\t},\n\t\t[],\n\t);\n\n\tconst clearOperationFeedback = useCallback(() => {\n\t\tif (operationTimeoutRef.current) {\n\t\t\tclearTimeout(operationTimeoutRef.current);\n\t\t\toperationTimeoutRef.current = null;\n\t\t}\n\t\tdispatch({ type: 'OPERATION_CLEAR' });\n\t}, []);\n\n\tconst value = useMemo<FeedbackContextValue>(\n\t\t() => ({\n\t\t\tstate,\n\t\t\tstartOperation,\n\t\t\tupdateOperationProgress,\n\t\t\tcompleteOperation,\n\t\t\tclearOperationFeedback,\n\t\t}),\n\t\t[state, startOperation, updateOperationProgress, completeOperation, clearOperationFeedback],\n\t);\n\n\treturn <FeedbackContext.Provider value={value}>{children}</FeedbackContext.Provider>;\n}\n\nexport function useFeedback(): FeedbackContextValue {\n\tconst context = useContext(FeedbackContext);\n\tif (!context) {\n\t\tthrow new Error('useFeedback must be used within a FeedbackProvider');\n\t}\n\treturn context;\n}\n\n/**\n * Hook for accessing only operation feedback - useful for dock status bar\n */\nexport function useOperationFeedback(): OperationFeedback | null {\n\tconst { state } = useFeedback();\n\treturn state.operation;\n}\n","/**\n * Grid Feedback Reducer\n *\n * Manages transient UI feedback state for data grid bulk operations.\n * Uses vanilla React (useReducer) instead of Zustand since this state is:\n * - Local to the data grid component tree\n * - Ephemeral (no persistence needed)\n * - Automatically cleaned up on unmount\n */\n\nexport type OperationStatus = 'idle' | 'pending' | 'success' | 'partial' | 'error';\n\nexport interface OperationFeedback {\n\tid: string;\n\ttype: 'delete' | 'submit' | 'update';\n\tstatus: OperationStatus;\n\tmessage: string;\n\ttotal: number;\n\tcompleted: number;\n\tfailed: number;\n\ttimestamp: number;\n\t/** Auto-dismiss duration in ms. 0 = persistent until manually cleared. */\n\tdismissAfter: number;\n}\n\nexport interface FeedbackState {\n\t/** Current bulk operation feedback (shown in floating status) */\n\toperation: OperationFeedback | null;\n}\n\n// Action types\ntype FeedbackAction =\n\t| { type: 'OPERATION_START'; operationType: OperationFeedback['type']; total: number; id: string }\n\t| { type: 'OPERATION_PROGRESS'; id: string; completed: number; failed: number }\n\t| {\n\t\t\ttype: 'OPERATION_COMPLETE';\n\t\t\tid: string;\n\t\t\tstatus: 'success' | 'partial' | 'error';\n\t\t\tmessage: string;\n\t\t\tdismissAfter: number;\n\t }\n\t| { type: 'OPERATION_CLEAR' };\n\n// Duration constants\nexport const FEEDBACK_DURATIONS = {\n\t/** Success operation message duration (ms) */\n\tOPERATION_SUCCESS: 3000,\n\t/** Error operation message - longer for reading (ms) */\n\tOPERATION_ERROR: 5000,\n\t/** Partial success duration (ms) */\n\tOPERATION_PARTIAL: 4000,\n} as const;\n\nexport function createInitialState(): FeedbackState {\n\treturn {\n\t\toperation: null,\n\t};\n}\n\nexport function feedbackReducer(state: FeedbackState, action: FeedbackAction): FeedbackState {\n\tswitch (action.type) {\n\t\tcase 'OPERATION_START': {\n\t\t\tconst typeLabels: Record<OperationFeedback['type'], string> = {\n\t\t\t\tdelete: 'Deleting',\n\t\t\t\tsubmit: 'Submitting',\n\t\t\t\tupdate: 'Updating',\n\t\t\t};\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\toperation: {\n\t\t\t\t\tid: action.id,\n\t\t\t\t\ttype: action.operationType,\n\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\tmessage: `${typeLabels[action.operationType]} ${action.total} ${action.total === 1 ? 'row' : 'rows'}...`,\n\t\t\t\t\ttotal: action.total,\n\t\t\t\t\tcompleted: 0,\n\t\t\t\t\tfailed: 0,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\tdismissAfter: 0,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tcase 'OPERATION_PROGRESS': {\n\t\t\tif (!state.operation || state.operation.id !== action.id) {\n\t\t\t\treturn state;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\toperation: {\n\t\t\t\t\t...state.operation,\n\t\t\t\t\tcompleted: action.completed,\n\t\t\t\t\tfailed: action.failed,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tcase 'OPERATION_COMPLETE': {\n\t\t\tif (!state.operation || state.operation.id !== action.id) {\n\t\t\t\treturn state;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\toperation: {\n\t\t\t\t\t...state.operation,\n\t\t\t\t\tstatus: action.status,\n\t\t\t\t\tmessage: action.message,\n\t\t\t\t\tdismissAfter: action.dismissAfter,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tcase 'OPERATION_CLEAR': {\n\t\t\treturn { ...state, operation: null };\n\t\t}\n\n\t\tdefault:\n\t\t\treturn state;\n\t}\n}\n\n// Helper to generate operation IDs\nexport function generateOperationId(): string {\n\treturn `op_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n}\n\n// Helper to get dismiss duration based on status\nexport function getDefaultDismissDuration(status: 'success' | 'partial' | 'error'): number {\n\tswitch (status) {\n\t\tcase 'success':\n\t\t\treturn FEEDBACK_DURATIONS.OPERATION_SUCCESS;\n\t\tcase 'partial':\n\t\t\treturn FEEDBACK_DURATIONS.OPERATION_PARTIAL;\n\t\tcase 'error':\n\t\t\treturn FEEDBACK_DURATIONS.OPERATION_ERROR;\n\t}\n}\n","'use client';\n\nimport { useCallback } from 'react';\nimport { RiCheckLine, RiCloseLine, RiErrorWarningLine, RiLoader4Line } from '@remixicon/react';\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { springs } from '../../utils/motion-config';\nimport { cn } from '../../utils/cn';\nimport { Button } from '@constructive-io/ui/button';\n\nimport { useOperationFeedback, useFeedback } from './feedback-context';\nimport type { OperationFeedback } from './feedback-reducer';\n\ninterface DockStatusBarProps {\n\tclassName?: string;\n\t/** Called when user clicks retry on a failed/partial operation */\n\tonRetry?: () => void;\n}\n\n/**\n * Inline status bar that appears in the floating dock during bulk operations.\n * Replaces toast notifications for delete, submit, and batch update operations.\n *\n * Shows:\n * - Progress spinner + message during pending operations\n * - Success checkmark + message (auto-dismisses)\n * - Error/partial warning + message with optional retry\n */\nexport function DockStatusBar({ className, onRetry }: DockStatusBarProps) {\n\tconst operation = useOperationFeedback();\n\tconst { clearOperationFeedback } = useFeedback();\n\n\tconst handleDismiss = useCallback(() => {\n\t\tclearOperationFeedback();\n\t}, [clearOperationFeedback]);\n\n\tif (!operation) {\n\t\treturn null;\n\t}\n\n\treturn (\n\t\t<AnimatePresence mode='wait'>\n\t\t\t<motion.div\n\t\t\t\tkey={operation.id}\n\t\t\t\tinitial={{ opacity: 0, x: 20 }}\n\t\t\t\tanimate={{ opacity: 1, x: 0 }}\n\t\t\t\texit={{ opacity: 0, x: -20 }}\n\t\t\t\ttransition={springs.snappy}\n\t\t\t\tclassName={cn('flex items-center gap-2', className)}\n\t\t\t>\n\t\t\t\t<StatusIcon status={operation.status} />\n\t\t\t\t<span className='text-sm font-medium'>{operation.message}</span>\n\n\t\t\t\t{/* Retry button for errors/partial failures */}\n\t\t\t\t{(operation.status === 'error' || operation.status === 'partial') && onRetry && (\n\t\t\t\t\t<Button variant='ghost' size='sm' className='h-7 px-2 text-xs' onClick={onRetry}>\n\t\t\t\t\t\tRetry\n\t\t\t\t\t</Button>\n\t\t\t\t)}\n\n\t\t\t\t{/* Dismiss button for completed operations */}\n\t\t\t\t{operation.status !== 'pending' && (\n\t\t\t\t\t<Button\n\t\t\t\t\t\tvariant='ghost'\n\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\tclassName='text-muted-foreground hover:text-foreground h-7 w-7 p-0'\n\t\t\t\t\t\tonClick={handleDismiss}\n\t\t\t\t\t\taria-label='Dismiss'\n\t\t\t\t\t>\n\t\t\t\t\t\t<RiCloseLine className='h-4 w-4' />\n\t\t\t\t\t</Button>\n\t\t\t\t)}\n\t\t\t</motion.div>\n\t\t</AnimatePresence>\n\t);\n}\n\nfunction StatusIcon({ status }: { status: OperationFeedback['status'] }) {\n\tswitch (status) {\n\t\tcase 'pending':\n\t\t\treturn <RiLoader4Line className='text-muted-foreground h-4 w-4 animate-spin' />;\n\t\tcase 'success':\n\t\t\treturn <RiCheckLine className='h-4 w-4 text-emerald-500' />;\n\t\tcase 'partial':\n\t\t\treturn <RiErrorWarningLine className='h-4 w-4 text-amber-500' />;\n\t\tcase 'error':\n\t\t\treturn <RiErrorWarningLine className='h-4 w-4 text-red-500' />;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Compact variant for space-constrained layouts.\n * Shows only icon + abbreviated message.\n */\nexport function DockStatusBarCompact({ className }: { className?: string }) {\n\tconst operation = useOperationFeedback();\n\tconst { clearOperationFeedback } = useFeedback();\n\n\tif (!operation) {\n\t\treturn null;\n\t}\n\n\tconst shortMessage = getShortMessage(operation);\n\n\treturn (\n\t\t<AnimatePresence mode='wait'>\n\t\t\t<motion.button\n\t\t\t\tkey={operation.id}\n\t\t\t\tinitial={{ opacity: 0, scale: 0.9 }}\n\t\t\t\tanimate={{ opacity: 1, scale: 1 }}\n\t\t\t\texit={{ opacity: 0, scale: 0.9 }}\n\t\t\t\ttransition={springs.snappy}\n\t\t\t\tclassName={cn(\n\t\t\t\t\t'flex items-center gap-1.5 rounded-full px-2.5 py-1',\n\t\t\t\t\toperation.status === 'pending' && 'bg-muted',\n\t\t\t\t\toperation.status === 'success' && 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',\n\t\t\t\t\toperation.status === 'partial' && 'bg-amber-500/10 text-amber-600 dark:text-amber-400',\n\t\t\t\t\toperation.status === 'error' && 'bg-red-500/10 text-red-600 dark:text-red-400',\n\t\t\t\t\tclassName,\n\t\t\t\t)}\n\t\t\t\tonClick={operation.status !== 'pending' ? clearOperationFeedback : undefined}\n\t\t\t\tdisabled={operation.status === 'pending'}\n\t\t\t>\n\t\t\t\t<StatusIcon status={operation.status} />\n\t\t\t\t<span className='text-xs font-medium'>{shortMessage}</span>\n\t\t\t</motion.button>\n\t\t</AnimatePresence>\n\t);\n}\n\nfunction getShortMessage(operation: OperationFeedback): string {\n\tif (operation.status === 'pending') {\n\t\treturn `${operation.completed}/${operation.total}`;\n\t}\n\tif (operation.status === 'success') {\n\t\treturn `${operation.total} done`;\n\t}\n\tif (operation.status === 'partial') {\n\t\treturn `${operation.failed} failed`;\n\t}\n\treturn 'Failed';\n}\n","import type { Transition } from 'motion/react';\n\n/**\n * Shared motion configuration for consistent animations across the app.\n * Based on practical animation tips from https://emilkowal.ski/ui/7-practical-animation-tips\n *\n * Key principles:\n * 1. Keep UI animations under 300ms\n * 2. Never animate from scale(0) - use 0.9+ for natural feel\n * 3. Use custom easing curves for more impactful animations\n * 4. Make animations origin-aware when possible\n * 5. Use blur to smooth transitions when needed\n */\n\n// =============================================================================\n// Easing Curves\n// =============================================================================\n\n/**\n * Standard easing curves for UI animations.\n * Reference: https://easings.co/\n */\nexport const easings = {\n\t/** Smooth deceleration - good for elements entering the screen */\n\teaseOut: [0.25, 0.1, 0.25, 1] as const,\n\n\t/** Smooth acceleration - good for elements leaving the screen */\n\teaseIn: [0.42, 0, 1, 1] as const,\n\n\t/** Smooth both ways - good for hover states and toggles */\n\teaseInOut: [0.42, 0, 0.58, 1] as const,\n\n\t/** Snappy entrance with soft landing - great for modals/dialogs */\n\tsnappy: [0.2, 0, 0, 1] as const,\n\n\t/** Bouncy feel - use sparingly for playful interactions */\n\tbounce: [0.34, 1.56, 0.64, 1] as const,\n\n\t/** Quick start, gradual stop - good for quick feedback */\n\temphasized: [0.4, 0, 0.2, 1] as const,\n\n\t/** Physical feel for exit animations */\n\tphysicalExit: [0.4, 0, 0.6, 1] as const,\n} as const;\n\n// =============================================================================\n// Duration Presets\n// =============================================================================\n\n/**\n * Duration presets in seconds.\n * Rule: UI animations should be under 300ms (0.3s)\n */\nexport const durations = {\n\t/** Instant feedback (button press, toggle) */\n\tinstant: 0.1,\n\n\t/** Quick transitions (tooltips, small elements) */\n\tfast: 0.15,\n\n\t/** Standard UI transitions (modals, panels) */\n\tnormal: 0.2,\n\n\t/** Deliberate animations (page transitions, complex reveals) */\n\tslow: 0.3,\n\n\t/** Maximum for UI - use rarely */\n\tdeliberate: 0.4,\n} as const;\n\n// =============================================================================\n// Spring Presets\n// =============================================================================\n\n/**\n * Spring configurations for physics-based animations.\n * These create more natural, organic motion.\n */\nexport const springs = {\n\t/** Snappy spring - good for quick interactions */\n\tsnappy: {\n\t\ttype: 'spring' as const,\n\t\tstiffness: 400,\n\t\tdamping: 30,\n\t\tmass: 0.8,\n\t},\n\n\t/** Bouncy spring - good for playful elements */\n\tbouncy: {\n\t\ttype: 'spring' as const,\n\t\tstiffness: 300,\n\t\tdamping: 20,\n\t\tmass: 0.6,\n\t},\n\n\t/** Gentle spring - good for large elements */\n\tgentle: {\n\t\ttype: 'spring' as const,\n\t\tstiffness: 150,\n\t\tdamping: 25,\n\t\tmass: 1,\n\t},\n\n\t/** Stiff spring - good for precise movements */\n\tstiff: {\n\t\ttype: 'spring' as const,\n\t\tstiffness: 500,\n\t\tdamping: 35,\n\t\tmass: 0.5,\n\t},\n\n\t/** Panel/sheet animations */\n\tpanel: {\n\t\ttype: 'spring' as const,\n\t\tstiffness: 150,\n\t\tdamping: 25,\n\t},\n} as const;\n\n// =============================================================================\n// Transition Presets\n// =============================================================================\n\n/**\n * Pre-configured transitions for common animation patterns.\n */\nexport const transitions = {\n\t/** Fast fade for overlays and simple elements */\n\tfade: {\n\t\tduration: durations.fast,\n\t\tease: easings.easeOut,\n\t} satisfies Transition,\n\n\t/** Standard enter/exit for UI elements */\n\tenterExit: {\n\t\tduration: durations.normal,\n\t\tease: easings.easeOut,\n\t} satisfies Transition,\n\n\t/** Snappy transition for interactive elements */\n\tsnappy: {\n\t\tduration: durations.fast,\n\t\tease: easings.snappy,\n\t} satisfies Transition,\n\n\t/** Panel slide transition */\n\tpanel: {\n\t\ttype: 'spring',\n\t\tstiffness: 150,\n\t\tdamping: 25,\n\t} satisfies Transition,\n\n\t/** Exit transition with physical feel */\n\texit: {\n\t\ttype: 'tween',\n\t\tduration: durations.normal,\n\t\tease: easings.physicalExit,\n\t} satisfies Transition,\n\n\t/** Layout animations */\n\tlayout: {\n\t\ttype: 'spring',\n\t\tstiffness: 300,\n\t\tdamping: 30,\n\t} satisfies Transition,\n} as const;\n\n// =============================================================================\n// Animation Variants\n// =============================================================================\n\n/**\n * Common animation variants for AnimatePresence patterns.\n * Follows the rule: never animate from scale(0), use 0.9+ instead.\n */\nexport const variants = {\n\t/** Fade with subtle scale - good for modals, cards */\n\tfadeScale: {\n\t\tinitial: { opacity: 0, scale: 0.95 },\n\t\tanimate: { opacity: 1, scale: 1 },\n\t\texit: { opacity: 0, scale: 0.95 },\n\t},\n\n\t/** Fade with subtle slide up - good for content reveals */\n\tfadeSlideUp: {\n\t\tinitial: { opacity: 0, y: 8 },\n\t\tanimate: { opacity: 1, y: 0 },\n\t\texit: { opacity: 0, y: -8 },\n\t},\n\n\t/** Fade with subtle slide down - good for dropdowns */\n\tfadeSlideDown: {\n\t\tinitial: { opacity: 0, y: -8 },\n\t\tanimate: { opacity: 1, y: 0 },\n\t\texit: { opacity: 0, y: 8 },\n\t},\n\n\t/** Simple fade - for overlays */\n\tfade: {\n\t\tinitial: { opacity: 0 },\n\t\tanimate: { opacity: 1 },\n\t\texit: { opacity: 0 },\n\t},\n\n\t/** Dock/floating element - scales from bottom */\n\tfloatUp: {\n\t\tinitial: { opacity: 0, y: 8, scale: 0.98 },\n\t\tanimate: { opacity: 1, y: 0, scale: 1 },\n\t\texit: { opacity: 0, y: 8, scale: 0.98 },\n\t},\n} as const;\n\n// =============================================================================\n// Convenience Aliases (from original template)\n// =============================================================================\n\nexport const MOTION_SPRING = springs.stiff;\nexport const MOTION_DURATION = { duration: durations.normal };\n","'use client';\n\nimport { useCallback } from 'react';\nimport { RiCheckLine, RiCloseLine, RiErrorWarningLine, RiLoader4Line } from '@remixicon/react';\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { springs } from '../../utils/motion-config';\nimport { cn } from '../../utils/cn';\n\nimport { useOperationFeedback, useFeedback } from './feedback-context';\nimport type { OperationFeedback } from './feedback-reducer';\n\ninterface FloatingStatusProps {\n\tclassName?: string;\n}\n\n/**\n * Standalone floating status indicator for bulk operations.\n * Shows independently of row selection, positioned at bottom-center of grid.\n */\nexport function FloatingStatus({ className }: FloatingStatusProps) {\n\tconst operation = useOperationFeedback();\n\tconst { clearOperationFeedback } = useFeedback();\n\n\tconst handleDismiss = useCallback(() => {\n\t\tclearOperationFeedback();\n\t}, [clearOperationFeedback]);\n\n\treturn (\n\t\t<AnimatePresence>\n\t\t\t{operation && (\n\t\t\t\t<motion.div\n\t\t\t\t\tkey={operation.id}\n\t\t\t\t\tinitial={{ opacity: 0, y: 20, scale: 0.95 }}\n\t\t\t\t\tanimate={{ opacity: 1, y: 0, scale: 1 }}\n\t\t\t\t\texit={{ opacity: 0, y: 10, scale: 0.95 }}\n\t\t\t\t\ttransition={springs.snappy}\n\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t'bg-background pointer-events-auto flex items-center gap-3 rounded-full border px-4 py-2 shadow-lg',\n\t\t\t\t\t\tclassName,\n\t\t\t\t\t)}\n\t\t\t\t>\n\t\t\t\t\t<StatusIcon status={operation.status} />\n\t\t\t\t\t<span className='text-sm font-medium'>{operation.message}</span>\n\n\t\t\t\t\t{/* Dismiss button for completed operations */}\n\t\t\t\t\t{operation.status !== 'pending' && (\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\ttype='button'\n\t\t\t\t\t\t\tclassName='text-muted-foreground hover:text-foreground -mr-1 rounded-full p-1 transition-colors'\n\t\t\t\t\t\t\tonClick={handleDismiss}\n\t\t\t\t\t\t\taria-label='Dismiss'\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<RiCloseLine className='h-4 w-4' />\n\t\t\t\t\t\t</button>\n\t\t\t\t\t)}\n\t\t\t\t</motion.div>\n\t\t\t)}\n\t\t</AnimatePresence>\n\t);\n}\n\nfunction StatusIcon({ status }: { status: OperationFeedback['status'] }) {\n\tconst baseClass = 'h-4 w-4';\n\n\tswitch (status) {\n\t\tcase 'pending':\n\t\t\treturn <RiLoader4Line className={cn(baseClass, 'text-muted-foreground animate-spin')} />;\n\t\tcase 'success':\n\t\t\treturn <RiCheckLine className={cn(baseClass, 'text-emerald-500')} />;\n\t\tcase 'partial':\n\t\t\treturn <RiErrorWarningLine className={cn(baseClass, 'text-amber-500')} />;\n\t\tcase 'error':\n\t\t\treturn <RiErrorWarningLine className={cn(baseClass, 'text-red-500')} />;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n","'use client';\n\nimport { Component, type ErrorInfo, type ReactNode } from 'react';\n\nimport { sheetsLogger } from '../../utils/sheets-logger';\nimport { SheetsErrorState } from './sheets-error-state';\n\ninterface SheetsErrorBoundaryProps {\n\tchildren: ReactNode;\n\t/** Called when a render error is caught. Mirrors SheetsConfig.onError. */\n\tonError?: (error: unknown, ctx?: { source?: 'grid' | 'editor' | 'mutation' | 'upload'; tableName?: string }) => void;\n\t/** Custom fallback. Receives the error and a reset callback to retry rendering. */\n\tfallback?: (error: unknown, reset: () => void) => ReactNode;\n}\n\ninterface SheetsErrorBoundaryState {\n\terror: unknown;\n}\n\n/**\n * Render-error boundary for the grid subtree. Catches exceptions thrown during\n * render of the DataEditor and editors, logs them through the injectable logger,\n * forwards them to the host via onError, and shows a recoverable error state.\n */\nexport class SheetsErrorBoundary extends Component<SheetsErrorBoundaryProps, SheetsErrorBoundaryState> {\n\tstate: SheetsErrorBoundaryState = { error: null };\n\n\tstatic getDerivedStateFromError(error: unknown): SheetsErrorBoundaryState {\n\t\treturn { error };\n\t}\n\n\tcomponentDidCatch(error: unknown, info: ErrorInfo): void {\n\t\tsheetsLogger().error('[sheets] render error', { error, componentStack: info.componentStack });\n\t\tthis.props.onError?.(error, { source: 'grid' });\n\t}\n\n\treset = (): void => {\n\t\tthis.setState({ error: null });\n\t};\n\n\trender(): ReactNode {\n\t\tconst { error } = this.state;\n\t\tif (error != null) {\n\t\t\treturn this.props.fallback?.(error, this.reset) ?? <SheetsErrorState error={error} onRetry={this.reset} />;\n\t\t}\n\t\treturn this.props.children;\n\t}\n}\n","'use client';\n\nimport { RiAddLine, RiErrorWarningLine, RiInboxLine } from '@remixicon/react';\n\nimport { Button } from '@constructive-io/ui/button';\nimport { cn } from '../../utils/cn';\n\nfunction getErrorMessage(error: unknown): string {\n\tif (error instanceof Error) return error.message;\n\tif (typeof error === 'string') return error;\n\treturn 'Something went wrong while loading this table.';\n}\n\ninterface SheetsStateShellProps {\n\tclassName?: string;\n\tchildren: React.ReactNode;\n}\n\n/** Centered, full-size container shared by the error/empty/loading states. */\nfunction SheetsStateShell({ className, children }: SheetsStateShellProps) {\n\treturn (\n\t\t<div\n\t\t\tclassName={cn(\n\t\t\t\t'bg-background flex h-full min-h-0 flex-1 flex-col items-center justify-center gap-3 rounded-lg border p-8 text-center',\n\t\t\t\tclassName,\n\t\t\t)}\n\t\t>\n\t\t\t{children}\n\t\t</div>\n\t);\n}\n\ninterface SheetsErrorStateProps {\n\terror: unknown;\n\tonRetry?: () => void;\n}\n\n/** Shown when the table data (or its metadata) fails to load. */\nexport function SheetsErrorState({ error, onRetry }: SheetsErrorStateProps) {\n\treturn (\n\t\t<SheetsStateShell>\n\t\t\t<RiErrorWarningLine className='text-destructive h-8 w-8' />\n\t\t\t<div className='space-y-1'>\n\t\t\t\t<p className='text-foreground text-sm font-medium'>Failed to load data</p>\n\t\t\t\t<p className='text-muted-foreground max-w-md text-sm'>{getErrorMessage(error)}</p>\n\t\t\t</div>\n\t\t\t{onRetry && (\n\t\t\t\t<Button variant='outline' size='sm' onClick={onRetry}>\n\t\t\t\t\tRetry\n\t\t\t\t</Button>\n\t\t\t)}\n\t\t</SheetsStateShell>\n\t);\n}\n\ninterface SheetsEmptyStateProps {\n\ttableName?: string;\n\tonAddRow?: () => void;\n\treadOnlyReason?: string | null;\n}\n\n/** Shown when the table loaded successfully but has no rows. */\nexport function SheetsEmptyState({ tableName, onAddRow, readOnlyReason }: SheetsEmptyStateProps) {\n\treturn (\n\t\t<SheetsStateShell>\n\t\t\t<RiInboxLine className='text-muted-foreground h-8 w-8' />\n\t\t\t<div className='space-y-1'>\n\t\t\t\t<p className='text-foreground text-sm font-medium'>No rows yet</p>\n\t\t\t\t<p className='text-muted-foreground max-w-md text-sm'>\n\t\t\t\t\t{readOnlyReason ?? (tableName ? `The \"${tableName}\" table is empty.` : 'This table is empty.')}\n\t\t\t\t</p>\n\t\t\t</div>\n\t\t\t{onAddRow && (\n\t\t\t\t<Button variant='outline' size='sm' onClick={onAddRow}>\n\t\t\t\t\t<RiAddLine className='h-4 w-4' />\n\t\t\t\t\t<span className='ms-1'>Add row</span>\n\t\t\t\t</Button>\n\t\t\t)}\n\t\t</SheetsStateShell>\n\t);\n}\n\n/** Column-width hints (px) for the skeleton bars — varied so it reads as a real table. */\nconst SKELETON_COLS = [120, 88, 152, 64, 108, 132, 80];\nconst SKELETON_ROWS = 12;\n\n/**\n * Shown during the initial data load. A STRUCTURAL skeleton of the grid (baseline-ui:\n * prefer skeletons over spinners) — mirrors the real grid's 40px header + 44px rows +\n * horizontal hairlines so the load→loaded swap doesn't jump. Pulse is motion-safe only.\n */\nexport function SheetsLoadingState() {\n\treturn (\n\t\t<div\n\t\t\tclassName='bg-background flex h-full min-h-0 flex-1 flex-col overflow-hidden rounded-lg border'\n\t\t\trole='status'\n\t\t\taria-busy='true'\n\t\t\taria-label='Loading data'\n\t\t>\n\t\t\t<div className='flex shrink-0 items-center gap-6 border-b px-3' style={{ height: 40 }}>\n\t\t\t\t{SKELETON_COLS.map((w, i) => (\n\t\t\t\t\t<div key={i} className='bg-muted h-2.5 shrink-0 rounded-sm' style={{ width: Math.round(w * 0.7) }} />\n\t\t\t\t))}\n\t\t\t</div>\n\t\t\t{Array.from({ length: SKELETON_ROWS }).map((_, r) => (\n\t\t\t\t<div key={r} className='flex shrink-0 items-center gap-6 border-b px-3' style={{ height: 44 }}>\n\t\t\t\t\t{SKELETON_COLS.map((w, i) => (\n\t\t\t\t\t\t<div key={i} className='bg-muted/60 h-3 shrink-0 rounded-sm motion-safe:animate-pulse' style={{ width: w }} />\n\t\t\t\t\t))}\n\t\t\t\t</div>\n\t\t\t))}\n\t\t</div>\n\t);\n}\n","import { RiArrowLeftSLine, RiArrowRightSLine, RiSkipBackLine, RiSkipForwardLine } from '@remixicon/react';\n\nimport { Button } from '@constructive-io/ui/button';\nimport { Pagination, PaginationContent, PaginationItem } from '@constructive-io/ui/pagination';\n\nexport interface SheetsPaginationProps {\n\tpageIndex: number;\n\tpageSize: number;\n\ttotalCount: number;\n\ttotalPages: number;\n\tsetPageIndex: React.Dispatch<React.SetStateAction<number>>;\n}\n\nexport function SheetsPagination(props: SheetsPaginationProps) {\n\tconst { pageIndex, pageSize, totalCount, totalPages, setPageIndex } = props;\n\n\treturn (\n\t\t<div\n\t\t\tdata-part-id='sheets-pagination'\n\t\t\tclassName='flex shrink-0 flex-col items-start justify-between gap-3 pt-4 sm:flex-row sm:items-center'\n\t\t>\n\t\t\t<p className='text-muted-foreground flex-1 text-sm whitespace-nowrap' aria-live='polite'>\n\t\t\t\tShowing <span className='text-foreground'>{(pageIndex * pageSize + 1).toLocaleString()}</span> to\n\t\t\t\t<span className='text-foreground'>\n\t\t\t\t\t{' '}\n\t\t\t\t\t{Math.min((pageIndex + 1) * pageSize, totalCount).toLocaleString()}\n\t\t\t\t</span> of <span className='text-foreground'>{totalCount.toLocaleString()}</span> results\n\t\t\t</p>\n\t\t\t<Pagination className='w-auto'>\n\t\t\t\t<PaginationContent className='gap-2'>\n\t\t\t\t\t<PaginationItem>\n\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\tvariant='secondary'\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\tonClick={() => setPageIndex(0)}\n\t\t\t\t\t\t\tdisabled={pageIndex === 0}\n\t\t\t\t\t\t\taria-label='Go to first page'\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<RiSkipBackLine size={16} />\n\t\t\t\t\t\t\t<span className='ml-1 hidden sm:inline'>First</span>\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</PaginationItem>\n\t\t\t\t\t<PaginationItem>\n\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\tvariant='secondary'\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\tonClick={() => setPageIndex((p) => Math.max(0, p - 1))}\n\t\t\t\t\t\t\tdisabled={pageIndex === 0}\n\t\t\t\t\t\t\taria-label='Go to previous page'\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<RiArrowLeftSLine size={16} />\n\t\t\t\t\t\t\t<span className='ml-1'>Previous</span>\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</PaginationItem>\n\t\t\t\t\t<PaginationItem>\n\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\tvariant='secondary'\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\tonClick={() => setPageIndex((p) => Math.min(totalPages - 1, p + 1))}\n\t\t\t\t\t\t\tdisabled={pageIndex >= totalPages - 1}\n\t\t\t\t\t\t\taria-label='Go to next page'\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span className='mr-1'>Next</span>\n\t\t\t\t\t\t\t<RiArrowRightSLine size={16} />\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</PaginationItem>\n\t\t\t\t\t<PaginationItem>\n\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\tvariant='secondary'\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\tonClick={() => setPageIndex(totalPages - 1)}\n\t\t\t\t\t\t\tdisabled={pageIndex >= totalPages - 1}\n\t\t\t\t\t\t\taria-label='Go to last page'\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span className='mr-1 hidden sm:inline'>Last</span>\n\t\t\t\t\t\t\t<RiSkipForwardLine size={16} />\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</PaginationItem>\n\t\t\t\t</PaginationContent>\n\t\t\t</Pagination>\n\t\t</div>\n\t);\n}\n","/**\n * useSheets — headless grid assembly hook.\n *\n * Computes the data/state bindings the default {@link Sheets} component renders\n * with the native TanStack DOM grid: columns, the native cell-content resolver,\n * value-commit helpers, and the draft / selection / pagination APIs. The built-in\n * {@link Sheets} component is a thin consumer of this hook.\n *\n * The STABLE headless surface is {@link UseSheetsResult}. A handful of additional\n * fields under the `_shell` group are returned only so the built-in `<Sheets>`\n * chrome (toolbar, pagination, dock) can render; they are intentionally NOT part\n * of the supported headless contract and may change.\n */\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\n\nimport type { SheetsSelection } from '../selection/selection-model';\nimport type { RelationInfo } from '../store/relation-info-slice';\n\nimport { useDataGridColumns, type RelationGridColumn } from '../hooks/use-relation-columns';\nimport { useSheetsContext } from '../context/sheets-context';\nimport { useSheetsStore } from '../store/sheets-store';\nimport { sheetsLogger } from '../utils/sheets-logger';\nimport { computeDraftMetaSignature } from '../store/draft-rows-slice';\nimport { toast } from '@constructive-io/ui/toast';\nimport type { DataGridProps, SheetsEvent } from './sheets.types';\nimport { attachDraftMeta, getDraftMeta, type SheetsRow } from './row-model';\n\nimport { createCellTypeRegistry, type CellTypeRegistry } from '../cell-types/cell-type-registry';\nimport { createSheetsCell } from '../cell-model/create-sheets-cell';\nimport { compileSlots } from '../cell-model/cell-slots';\nimport { DRAFT_ACTION_COLUMN_KEY } from './sheets.constants';\nimport { countConditions } from './sheets.controls';\nimport { useFeedback } from './feedback';\nimport {\n\tbuildWhereFromFilters,\n\tcreateHeaderClickHandler,\n\tmapFromFieldMetaMap,\n\tmapFromRelationInfoMap,\n\tnormalizeServerRow,\n} from './sheets.utils';\nimport { useSheetsMeta } from '../hooks/use-sheets-meta';\nimport type { DraftSubmitResult } from './draft-types';\nimport { useCellEditing } from './hooks/use-cell-editing';\nimport { useBatchCommit, type CellWrite, type CommitCellsOptions, type CommitCellsResult } from './hooks/use-batch-commit';\nimport { useUndoRedo } from './hooks/use-undo-redo';\nimport { useDraftRows } from './hooks/use-draft-rows';\nimport { useDraftSubmission } from './hooks/use-draft-submission';\nimport { useSheetsContent, type SheetsCellResolution } from '../grid-dom/use-sheets-content';\nimport { useGridOperations } from './hooks/use-grid-operations';\nimport { useGridSelectionState } from './hooks/use-grid-selection';\nimport { useGridState } from './hooks/use-grid-state';\nimport { useInfiniteGridData, type VisibleRowRange } from './hooks/use-infinite-grid-data';\nimport { useDataLoading } from './hooks/use-load-grid';\nimport {\n\tcanRunSheetsMutation,\n\tgetSheetsWriteCapability,\n\tresolveSheetsRowIdentity,\n\tsheetsRowKey,\n\ttype SheetsRowIdentifier,\n} from '../row-identity';\n\nconst EMPTY_RELATION_INFO_BY_FIELD = new Map<string, RelationInfo>();\n\n/** Draft-row bindings for a headless shell. */\nexport interface SheetsDraftBindings {\n\t/** Whether any client-side draft rows exist. */\n\thasDrafts: boolean;\n\t/** Append a new draft row. Returns the new row index. */\n\tappendRow: () => Promise<number | undefined>;\n\t/** Submit all pending draft rows. */\n\tsubmitDrafts: () => Promise<void>;\n\t/** Delete the currently selected rows (draft + server). */\n\tdeleteSelected: () => Promise<void>;\n}\n\n/**\n * Selection bindings for a headless shell.\n *\n * The selection value is the native {@link SheetsSelection} (RangeSet-backed `rows`).\n */\nexport interface SheetsSelectionBindings {\n\t/** Current native grid selection. */\n\tgridSelection: SheetsSelection | undefined;\n\t/** Setter. */\n\tsetGridSelection: (selection: SheetsSelection | undefined) => void;\n\t/** Park the active cell on `[col, row]` (preserves row/column selection). */\n\tsetActiveCell: (col: number, row: number) => void;\n\t/** Move the active cell by `[dCol, dRow]`, clamped to grid bounds. */\n\tmoveActive: (dCol: number, dRow: number, colCount: number, rowCount: number) => void;\n}\n\n/** Pagination bindings for a headless shell (paginated mode). */\nexport interface SheetsPaginationBindings {\n\t/** Current zero-based page index. */\n\tpageIndex: number;\n\t/** Total page count (>= 1). */\n\tpageCount: number;\n\t/** Set the page index (emits a `page:change` event). */\n\tsetPageIndex: (updater: number | ((prev: number) => number)) => void;\n}\n\n/**\n * Stable headless surface returned by {@link useSheets}. (The hook also returns a\n * few `_shell`-grouped extras consumed only by the built-in {@link Sheets} chrome —\n * those are not part of this supported contract.)\n */\nexport interface UseSheetsResult {\n\t/** Native column descriptors (key/title/width). */\n\tcolumns: RelationGridColumn[];\n\t/** Number of rows to render. */\n\trowCount: number;\n\t/** Draft-row bindings. */\n\tdraft: SheetsDraftBindings;\n\t/** Selection bindings. */\n\tselection: SheetsSelectionBindings;\n\t/** Pagination bindings. */\n\tpagination: SheetsPaginationBindings;\n\t/** True only during the very first load (refetches keep previous data). */\n\tisInitialLoading: boolean;\n\t/** Data-load error, if any. */\n\tdataError: Error | null;\n\t/** Whether the initial load has completed (success). */\n\thasCompletedInitialLoad: boolean;\n\t/** True when loaded, no server rows, no drafts, and no active filter. */\n\tisEmpty: boolean;\n\t/** Refetch the underlying data (mode-aware: infinite vs paginated). */\n\trefetch: () => void;\n}\n\n/**\n * Internal bindings consumed only by the built-in {@link Sheets} chrome\n * (toolbar, dock, pagination chrome). NOT a supported part of the headless contract.\n */\nexport interface SheetsShellBindings {\n\tcombinedRows: SheetsRow[];\n\tcolumnKeys: string[];\n\ttotalCount: number;\n\tserverRowCount: number;\n\tdraftRowCount: number;\n\tinfiniteScroll: boolean;\n\tfilterTree: ReturnType<typeof useGridState>['state']['filterTree'];\n\tfiltersOpen: boolean;\n\tsetFilterTree: ReturnType<typeof useGridState>['actions']['setFilterTree'];\n\tsetFiltersOpen: ReturnType<typeof useGridState>['actions']['setFiltersOpen'];\n\tclearAllFilters: ReturnType<typeof useGridState>['actions']['clearAllFilters'];\n\tapplyFilters: () => void;\n\tfieldTypeMap: Record<string, { gqlType: string; isArray: boolean }>;\n\tsetGridSelectionForControls: (selection: SheetsSelection | null) => void;\n\t/** Header sort toggle (colIndex → toggleSorting on the sortable column). */\n\tonHeaderClicked: (colIndex: number) => void;\n\t/** Prefetch the rows in an inclusive visible window (native range, infinite mode). */\n\tonVisibleRegionChanged: (range: VisibleRowRange) => void;\n\t/** @internal Sort state mirror ({ id, desc }) — the DOM header reads this for its caret. NOT a stable API. */\n\tsorting: ReturnType<typeof useGridState>['state']['sorting'];\n\t/** @internal Committed column widths (id → px) — the DOM grid maps these to v9 columnSizing. NOT a stable API. */\n\tcolumnWidths: ReturnType<typeof useGridState>['state']['columnWidths'];\n\t/** @internal Commit a column width (id, px) — the DOM resize handle drives this directly. NOT a stable API. */\n\tresizeColumn: ReturnType<typeof useGridState>['actions']['resizeColumn'];\n\tfrozenCount: number;\n\tselectedRowCount: number;\n\tcanCreate: boolean;\n\tcanUpdate: boolean;\n\tcanDelete: boolean;\n\t/** Human-readable reason shown when `_meta` proves the whole table is read-only. */\n\treadOnlyReason: string | null;\n\t/** Stable identity for selection, TanStack rows, and editor instances. */\n\tgetRowId: (row: SheetsRow | null | undefined, index: number) => string;\n\tisSubmittingDrafts: boolean;\n\tsubmitDraftButtonDisabled: boolean;\n\tsubmitDraftLabel: string;\n\t/** @internal Native DOM content resolver for the TanStack DOM grid. NOT a stable API. */\n\tgetSheetsCellContent: (rowIndex: number, colKey: string) => SheetsCellResolution;\n\t/** @internal Per-instance cell-type registry (consumer overrides over built-ins). NOT a stable API. */\n\tcellRegistry: CellTypeRegistry;\n\t/** @internal Native value-commit for the TanStack DOM portal editors. NOT a stable API. */\n\tcommitCellValue: (rowIndex: number, colKey: string, nextValue: unknown) => void;\n\t/** @internal Batched server-row value commit (paste/fill/bulk + the single cell). NOT a stable API. */\n\tcommitCells: (writes: CellWrite[], opts?: CommitCellsOptions) => Promise<CommitCellsResult>;\n\t/** @internal Native MULTI-field patch-commit for self-committing DOM portal editors (relation/image). NOT a stable API. */\n\tcommitCellPatch: (rowIndex: number, patch: Record<string, unknown>) => void;\n\t/** @internal Submit a client-side draft row for a self-committing DOM portal editor. NOT a stable API. */\n\tsubmitDraftRow: (draftRowId: string) => Promise<DraftSubmitResult>;\n\t/** @internal Invalidate cached grid data after a self-committing DOM portal editor mutates out-of-band. NOT a stable API. */\n\tinvalidateData: () => void;\n\t/** @internal Undo the last recorded server-row value write. NOT a stable API. */\n\tundo: () => Promise<void>;\n\t/** @internal Redo the last undone server-row value write. NOT a stable API. */\n\tredo: () => Promise<void>;\n\t/** @internal Whether an undo is available. NOT a stable API. */\n\tcanUndo: boolean;\n\t/** @internal Whether a redo is available. NOT a stable API. */\n\tcanRedo: boolean;\n\t/** @internal Observational event emitter (analytics/telemetry) — threaded into the command context. NOT a stable API. */\n\temit: (type: SheetsEvent['type'], meta?: Record<string, unknown>) => void;\n}\n\nexport type UseSheetsInternalResult<TRow extends SheetsRow = SheetsRow> = UseSheetsResult & {\n\t/** @internal Bindings for the built-in <Sheets> chrome — not a stable API. */\n\t_shell: SheetsShellBindings;\n};\n\n/**\n * Headless grid hook — returns the data/state bindings the built-in {@link Sheets}\n * component renders with the native DOM grid.\n *\n * Preconditions:\n * - You MUST render inside a `<FeedbackProvider>` (exported from this package) —\n * the hook uses the bulk-operation feedback context and throws without it.\n *\n * NOTE: the generic `TRow` flows through {@link DataGridProps}'s row callbacks\n * (e.g. `onRowSelect`). It does not retype the cell bindings, which operate on\n * the dynamic schema-derived row shape.\n */\nexport function useSheets<TRow extends SheetsRow = SheetsRow>(\n\tprops: DataGridProps<TRow>,\n): UseSheetsInternalResult<TRow> {\n\tconst {\n\t\ttableName,\n\t\tpageSize = 100,\n\t\tonRowSelect,\n\t\tonCellEdit,\n\t\trelationChipLimit,\n\t\trelationLabelMaxLength,\n\t\tinfiniteScroll = false,\n\t\tcellTypes,\n\t\tcellSlots,\n\t\tonEvent,\n\t} = props;\n\n\t// Get feedback context for bulk operation status indicators\n\tconst { startOperation, updateOperationProgress, completeOperation, clearOperationFeedback } = useFeedback();\n\n\t// Keep the latest onEvent in a ref so firing events never depends on (or churns)\n\t// the callbacks/effects below — purely observational, no behavioral coupling.\n\tconst onEventRef = useRef(onEvent);\n\tonEventRef.current = onEvent;\n\tconst emit = useCallback((type: SheetsEvent['type'], meta?: Record<string, unknown>) => {\n\t\tonEventRef.current?.({ type, tableName, at: Date.now(), meta });\n\t}, [tableName]);\n\n\tconst { config } = useSheetsContext();\n\n\t// Per-instance cell-type registry: consumer overrides (provider plugins, then\n\t// per-instance cellTypes) layered over the built-in native engine. With no consumer\n\t// cell types this delegates 1:1 to createSheetsCell.\n\tconst cellRegistry = useMemo(\n\t\t() =>\n\t\t\tcreateCellTypeRegistry(\n\t\t\t\t// Compiled cell-component slots go LAST so they win over plugins + cellTypes.\n\t\t\t\t[...(config.plugins ?? []).flatMap((p) => p.cellTypes), ...(cellTypes ?? []), ...compileSlots(cellSlots)],\n\t\t\t\t{\n\t\t\t\t\t// Native display builtin: the SheetsCell dispatcher.\n\t\t\t\t\ttoSheetsCell: (value, ctx) => createSheetsCell(value, ctx.metadata),\n\t\t\t\t},\n\t\t\t),\n\t\t[config.plugins, cellTypes, cellSlots],\n\t);\n\n\tconst tableKey = useMemo(() => {\n\t\tif (config.databaseId) return `${config.databaseId}::${tableName}`;\n\t\treturn `default::${tableName}`;\n\t}, [config.databaseId, tableName]);\n\n\t// Clear stale operation feedback when switching tables\n\tuseEffect(() => {\n\t\tclearOperationFeedback();\n\t}, [tableName, clearOperationFeedback]);\n\n\t// Centralized state management\n\tconst { state: gridState, actions: gridActions } = useGridState();\n\n\t// Build orderBy from grid state\n\tconst orderByClause = useMemo(\n\t\t() =>\n\t\t\tgridState.sorting.id\n\t\t\t\t? [{ field: gridState.sorting.id, direction: gridState.sorting.desc ? ('desc' as const) : ('asc' as const) }]\n\t\t\t\t: undefined,\n\t\t[gridState.sorting],\n\t);\n\n\t// ============== FILTER / SEARCH → WHERE CLAUSE ==============\n\t// Fetch meta independently so we can build the where clause before data hooks run\n\tconst { data: filterMeta } = useSheetsMeta();\n\tconst filterTableMeta = useMemo(\n\t\t() => filterMeta?._meta?.tables?.find((t) => t?.name === tableName) ?? null,\n\t\t[filterMeta, tableName],\n\t);\n\n\tconst effectiveWhere = useMemo(\n\t\t() => buildWhereFromFilters(gridState.filterTree, filterTableMeta),\n\t\t[gridState.filterTree, filterTableMeta],\n\t);\n\n\t// Reset to page 0 when filters change (paginated mode)\n\tconst prevWhereRef = useRef(effectiveWhere);\n\tuseEffect(() => {\n\t\tif (prevWhereRef.current !== effectiveWhere) {\n\t\t\tprevWhereRef.current = effectiveWhere;\n\t\t\tif (!infiniteScroll) {\n\t\t\t\tgridActions.setPageIndex(0);\n\t\t\t}\n\t\t}\n\t}, [effectiveWhere, infiniteScroll, gridActions]);\n\n\t// ============== INFINITE SCROLL MODE ==============\n\tconst infiniteGridData = useInfiniteGridData({\n\t\ttableName,\n\t\tpageSize,\n\t\torderBy: orderByClause,\n\t\twhere: effectiveWhere,\n\t\tenabled: infiniteScroll,\n\t});\n\n\t// ============== PAGINATED MODE ==============\n\tconst initialQueryOptions = useMemo(\n\t\t() => ({\n\t\t\tlimit: pageSize,\n\t\t\toffset: gridState.pageIndex * pageSize,\n\t\t\torderBy: orderByClause,\n\t\t\twhere: effectiveWhere,\n\t\t}),\n\t\t[pageSize, gridState.pageIndex, orderByClause, effectiveWhere],\n\t);\n\n\t// In infinite scroll mode we still use mutations from useDataLoading,\n\t// but disable row/count queries to avoid duplicate fetching.\n\tconst dataLoadingResult = useDataLoading({\n\t\ttableName,\n\t\tqueryOptions: initialQueryOptions,\n\t\tenabled: !infiniteScroll,\n\t});\n\n\t// ============== UNIFIED DATA ACCESS ==============\n\t// Choose data source based on mode\n\tconst {\n\t\tserverData,\n\t\ttotalCount,\n\t\ttableMeta,\n\t\tfieldMetaMap,\n\t\tallRelationFields,\n\t\thasCompletedInitialLoad,\n\t\tdataError,\n\t\tisInitialLoading,\n\t} = useMemo(() => {\n\t\tif (infiniteScroll) {\n\t\t\treturn {\n\t\t\t\tserverData: [] as any[], // Not used directly in infinite mode\n\t\t\t\ttotalCount: infiniteGridData.totalCount,\n\t\t\t\ttableMeta: infiniteGridData.tableMeta,\n\t\t\t\tfieldMetaMap: infiniteGridData.fieldMetaMap,\n\t\t\t\tallRelationFields: infiniteGridData.allRelationFields,\n\t\t\t\thasCompletedInitialLoad: infiniteGridData.hasInitialData,\n\t\t\t\tdataError: infiniteGridData.error,\n\t\t\t\t// Only the first load (no rows yet) should show the loading screen; refetches keep previous data.\n\t\t\t\tisInitialLoading: infiniteGridData.isLoading && !infiniteGridData.hasInitialData,\n\t\t\t};\n\t\t}\n\t\tconst ctx = dataLoadingResult.contextValue;\n\t\tconst rows = ctx.data || [];\n\t\treturn {\n\t\t\tserverData: rows,\n\t\t\ttotalCount: ctx.totalCount,\n\t\t\ttableMeta: ctx.tableMeta,\n\t\t\tfieldMetaMap: ctx.fieldMetaMap,\n\t\t\tallRelationFields: ctx.allRelationFields,\n\t\t\thasCompletedInitialLoad: !ctx.isLoading,\n\t\t\tdataError: ctx.error,\n\t\t\t// isLoading is true only until the active scope receives its first result.\n\t\t\tisInitialLoading: ctx.isLoading && rows.length === 0,\n\t\t};\n\t}, [infiniteScroll, infiniteGridData, dataLoadingResult.contextValue]);\n\n\tconst writeCapability = useMemo(() => getSheetsWriteCapability(tableMeta), [tableMeta]);\n\tconst canCreate = canRunSheetsMutation(writeCapability, 'create');\n\tconst canUpdate = canRunSheetsMutation(writeCapability, 'update');\n\tconst canDelete = canRunSheetsMutation(writeCapability, 'delete');\n\tconst primaryKeyFields = useMemo(\n\t\t() => new Set(writeCapability?.status === 'mutable' ? writeCapability.primaryKeyFields : []),\n\t\t[writeCapability],\n\t);\n\tconst supportsScalarSelfCommit =\n\t\twriteCapability?.status === 'mutable' &&\n\t\twriteCapability.primaryKeyFields.length === 1 &&\n\t\twriteCapability.primaryKeyFields[0] === 'id';\n\tconst readOnlyReason = writeCapability?.status === 'read-only'\n\t\t? 'This table is read-only because it has no primary key.'\n\t\t: null;\n\tconst getRowIdentifier = useCallback(\n\t\t(row: Readonly<Record<string, unknown>>): SheetsRowIdentifier | null => {\n\t\t\tif (!tableMeta) return null;\n\t\t\tconst resolution = resolveSheetsRowIdentity(tableMeta, row);\n\t\t\treturn resolution.status === 'identified' ? resolution.identifier : null;\n\t\t},\n\t\t[tableMeta],\n\t);\n\tconst getRowId = useCallback(\n\t\t(row: SheetsRow | null | undefined, index: number): string => {\n\t\t\tconst draftMeta = getDraftMeta(row);\n\t\t\tif (draftMeta) return draftMeta.draftRowId;\n\t\t\tif (row && tableMeta) return sheetsRowKey(tableMeta, row, index);\n\t\t\treturn `${tableMeta?.schemaName ?? ''}:${tableName}:row:${index}`;\n\t\t},\n\t\t[tableMeta, tableName],\n\t);\n\n\t// Emit load:success / load:error once per transition. Tracked via a ref so we\n\t// don't re-fire on unrelated re-renders.\n\tconst lastLoadEmitRef = useRef<'success' | 'error' | null>(null);\n\tuseEffect(() => {\n\t\tif (dataError) {\n\t\t\tif (lastLoadEmitRef.current !== 'error') {\n\t\t\t\tlastLoadEmitRef.current = 'error';\n\t\t\t\temit('load:error', { error: dataError });\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (hasCompletedInitialLoad && lastLoadEmitRef.current !== 'success') {\n\t\t\tlastLoadEmitRef.current = 'success';\n\t\t\temit('load:success', { totalCount });\n\t\t}\n\t}, [dataError, hasCompletedInitialLoad, totalCount, emit]);\n\n\t// Get CRUD operations (only available in paginated mode for now)\n\tconst { update, create, delete: deleteRow } = dataLoadingResult.contextValue;\n\n\tconst relationFieldNames = useMemo(() => new Set(allRelationFields), [allRelationFields]);\n\n\tconst normalizedServerData = useMemo(() => {\n\t\tif (infiniteScroll) return [] as any[]; // Not used in infinite mode\n\t\tif (!Array.isArray(serverData) || serverData.length === 0 || relationFieldNames.size === 0) {\n\t\t\treturn serverData as any[];\n\t\t}\n\t\treturn (serverData as any[]).map((row) => normalizeServerRow(row, relationFieldNames));\n\t}, [infiniteScroll, serverData, relationFieldNames]);\n\n\tconst {\n\t\tdraftRowsTable,\n\t\tdraftRows,\n\t\thasDraftRows,\n\t\tcombinedRows: paginatedCombinedRows,\n\t\tdraftRowIndices: paginatedDraftRowIndices,\n\t\tcreateDraftRow,\n\t\tupdateDraftCell,\n\t\tremoveDraftRow,\n\t\tsyncDraftRowsWithMeta,\n\t\tsetDraftRowStatus,\n\t} = useDraftRows({\n\t\ttableKey,\n\t\tserverRows: normalizedServerData as any[],\n\t\thasCompletedInitialLoad,\n\t});\n\n\tconst serverRowCount = infiniteScroll ? totalCount : normalizedServerData.length;\n\n\tconst draftDataRows = useMemo(() => {\n\t\tif (!draftRows.length) return [] as SheetsRow[];\n\t\treturn draftRows.map((draft) => {\n\t\t\tconst row = { ...draft.values } as SheetsRow;\n\t\t\treturn attachDraftMeta(row, {\n\t\t\t\tisDraft: true,\n\t\t\t\tdraftRowId: draft.id,\n\t\t\t\tstatus: draft.status,\n\t\t\t\terrors: draft.errors,\n\t\t\t});\n\t\t});\n\t}, [draftRows]);\n\n\t// ============== INFINITE SCROLL: Virtual rows array ==============\n\t// Create a proxy array for infinite scroll mode that uses getRowAtIndex and appends draft rows.\n\tconst infiniteRowsProxy = useMemo<SheetsRow[]>(() => {\n\t\tif (!infiniteScroll) return [];\n\n\t\t// Create an array-like object with a Proxy to intercept index access\n\t\tconst handler: ProxyHandler<any[]> = {\n\t\t\tget(target, prop) {\n\t\t\t\t// Handle array methods and properties\n\t\t\t\tif (prop === 'length') {\n\t\t\t\t\treturn serverRowCount + draftDataRows.length;\n\t\t\t\t}\n\t\t\t\tif (prop === Symbol.iterator) {\n\t\t\t\t\treturn function* () {\n\t\t\t\t\t\tconst len = serverRowCount + draftDataRows.length;\n\t\t\t\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\t\t\t\tif (i < serverRowCount) {\n\t\t\t\t\t\t\t\tyield infiniteGridData.getRowAtIndex(i);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tyield draftDataRows[i - serverRowCount];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\t// Handle numeric indices\n\t\t\t\tif (typeof prop === 'string' && !isNaN(Number(prop))) {\n\t\t\t\t\tconst index = Number(prop);\n\t\t\t\t\tif (index < serverRowCount) {\n\t\t\t\t\t\treturn infiniteGridData.getRowAtIndex(index);\n\t\t\t\t\t}\n\t\t\t\t\treturn draftDataRows[index - serverRowCount];\n\t\t\t\t}\n\t\t\t\t// Delegate to target for other properties\n\t\t\t\treturn Reflect.get(target, prop);\n\t\t\t},\n\t\t};\n\n\t\t// Single localized cast: the Proxy intercepts numeric index + length access to\n\t\t// surface server rows (via getRowAtIndex) and appended draft rows as SheetsRow,\n\t\t// so downstream `combinedRows[i]` reads are SheetsRow with no per-use cast.\n\t\treturn new Proxy([], handler) as unknown as SheetsRow[];\n\t}, [infiniteScroll, infiniteGridData, serverRowCount, draftDataRows]);\n\n\t// Choose the appropriate rows array based on mode\n\tconst combinedRows: SheetsRow[] = infiniteScroll ? infiniteRowsProxy : paginatedCombinedRows;\n\n\tconst draftRowIndices = useMemo(() => {\n\t\tif (!draftDataRows.length) return [] as number[];\n\t\tif (infiniteScroll) {\n\t\t\treturn draftDataRows.map((_, index) => serverRowCount + index);\n\t\t}\n\t\treturn paginatedDraftRowIndices;\n\t}, [draftDataRows, infiniteScroll, paginatedDraftRowIndices, serverRowCount]);\n\n\tconst fieldMetaByKey = useMemo(() => mapFromFieldMetaMap(fieldMetaMap), [fieldMetaMap]);\n\n\t// Build columns with actual data\n\t// In infinite scroll mode, check if we have initial data\n\tconst hasServerRows = infiniteScroll ? infiniteGridData.hasInitialData : normalizedServerData.length > 0;\n\n\tconst { columns: baseColumns, columnKeys } = useDataGridColumns(\n\t\ttableName,\n\t\thasServerRows ? combinedRows : undefined,\n\t);\n\n\tconst gridColumnKeys = useMemo(() => {\n\t\tif (!hasDraftRows) return columnKeys;\n\t\treturn [...columnKeys, DRAFT_ACTION_COLUMN_KEY];\n\t}, [columnKeys, hasDraftRows]);\n\n\t// Pagination helpers\n\tconst totalPages = Math.max(1, Math.ceil((totalCount || 0) / pageSize));\n\tuseEffect(() => {\n\t\tgridActions.resetPageIfNeeded(totalPages);\n\t}, [totalPages, gridActions]);\n\n\t// Apply custom widths and sort indicators to columns\n\tconst columns = useMemo<RelationGridColumn[]>(() => {\n\t\tconst sortedColId = gridState.sorting.id;\n\t\tconst isDesc = gridState.sorting.desc;\n\n\t\tconst mapped = baseColumns.map((col) => {\n\t\t\tconst isSorted = col.id === sortedColId;\n\t\t\t// Append sort indicator to title if this column is sorted\n\t\t\tconst sortIndicator = isSorted ? (isDesc ? ' ↓' : ' ↑') : '';\n\t\t\treturn {\n\t\t\t\t...col,\n\t\t\t\ttitle: col.title + sortIndicator,\n\t\t\t\twidth: gridState.columnWidths.get(col.id || '') ?? col.width,\n\t\t\t};\n\t\t});\n\n\t\tif (hasDraftRows) {\n\t\t\tmapped.push({\n\t\t\t\tid: DRAFT_ACTION_COLUMN_KEY,\n\t\t\t\ttitle: '',\n\t\t\t\twidth: gridState.columnWidths.get(DRAFT_ACTION_COLUMN_KEY) ?? 132,\n\t\t\t});\n\t\t}\n\n\t\treturn mapped;\n\t}, [baseColumns, gridState.columnWidths, gridState.sorting, hasDraftRows]);\n\n\t// Handle row selection\n\tuseEffect(() => {\n\t\tif (!onRowSelect || !gridState.gridSelection) return;\n\t\tconst selectedIndices = gridState.gridSelection.rows.toArray();\n\t\tconst selected = selectedIndices.map((i: number) => combinedRows[i]).filter(Boolean);\n\t\t// The grid's rows ARE the consumer's row type, so widen SheetsRow[] -> TRow[].\n\t\tonRowSelect(selected as TRow[]);\n\t}, [gridState.gridSelection, combinedRows, onRowSelect]);\n\n\t// ============== RELATION INFO (store-derived) ==============\n\t// The store owns relation metadata; ensure it for this table once and read the\n\t// per-field map. Used by the native content resolver + draft/relation routing.\n\tconst ensureRelationInfo = useSheetsStore((st) => st.ensureRelationInfo);\n\tconst relationInfoByFieldFromStore = useSheetsStore((st) =>\n\t\ttableName ? st.relationInfoMapCache[tableName] : undefined,\n\t);\n\tconst relationInfoByField = relationInfoByFieldFromStore ?? EMPTY_RELATION_INFO_BY_FIELD;\n\tuseEffect(() => {\n\t\tif (!tableName) return;\n\t\tensureRelationInfo(tableName, filterMeta);\n\t}, [tableName, filterMeta, ensureRelationInfo]);\n\n\tconst relationInfoObject = useMemo(() => mapFromRelationInfoMap(relationInfoByField), [relationInfoByField]);\n\n\t// Native DOM content resolver (mirrors the canvas getCellContent routing → SheetsCell).\n\tconst { getSheetsCell: getSheetsCellContent } = useSheetsContent({\n\t\tdata: combinedRows,\n\t\tcolumnKeys: gridColumnKeys,\n\t\tfieldMetaMap,\n\t\tregistry: cellRegistry,\n\t\ttableName,\n\t\toptions: { relationChipLimit, relationLabelMaxLength },\n\t\trelationInfoByField,\n\t\tmeta: filterMeta,\n\t\tserverRowsReadOnly: !canUpdate,\n\t\tserverReadOnlyFields: primaryKeyFields,\n\t\tgetRowIdentifier,\n\t\tsupportsScalarSelfCommit,\n\t});\n\n\tconst effectiveColumnOrder = useMemo(() => {\n\t\tif (columnKeys.length > 0) return columnKeys;\n\t\treturn Object.keys(fieldMetaByKey);\n\t}, [columnKeys, fieldMetaByKey]);\n\n\tconst metaSignature = useMemo(\n\t\t() => computeDraftMetaSignature(effectiveColumnOrder, fieldMetaByKey, relationInfoObject),\n\t\t[effectiveColumnOrder, fieldMetaByKey, relationInfoObject],\n\t);\n\n\tconst allowedColumns = useMemo(() => {\n\t\tconst tableFields = tableMeta?.fields as { name: string }[] | undefined;\n\t\treturn tableFields ? new Set(tableFields.map((field) => field.name).filter(Boolean) as string[]) : undefined;\n\t}, [tableMeta?.fields]);\n\n\tuseEffect(() => {\n\t\tif (!effectiveColumnOrder.length) return;\n\t\tsyncDraftRowsWithMeta({\n\t\t\ttableKey,\n\t\t\tcolumnOrder: effectiveColumnOrder,\n\t\t\tfieldMetaByKey,\n\t\t\trelationInfoByKey: relationInfoObject,\n\t\t\tmetaVersion: metaSignature,\n\t\t});\n\t}, [effectiveColumnOrder, fieldMetaByKey, relationInfoObject, metaSignature, syncDraftRowsWithMeta, tableKey]);\n\n\t/**\n\t * Unified optimistic update handler for overlay editors. Editors that handle\n\t * mutations internally (RelationEditor, ImageEditor, etc.) call this callback with\n\t * a patch to update the grid cache without full refetch. The DOM grid re-renders\n\t * reactively off `combinedRows`, so no surgical per-cell repaint is needed.\n\t */\n\tconst handleEditorSaveComplete = useCallback(\n\t\t(colKey: string, rowIndex: number, patch: Record<string, unknown>) => {\n\t\t\tvoid colKey;\n\t\t\tconst rowData = combinedRows[rowIndex];\n\n\t\t\t// Draft row: update draft store directly\n\t\t\tconst dm = getDraftMeta(rowData);\n\t\t\tif (dm) {\n\t\t\t\tfor (const [key, value] of Object.entries(patch)) {\n\t\t\t\t\tupdateDraftCell({ tableKey, draftRowId: dm.draftRowId, columnKey: key, value });\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Server row: update infinite scroll cache (paginated handled by React Query)\n\t\t\tif (!infiniteScroll) return;\n\n\t\t\t// Apply optimistic update to infinite scroll cache; self-heal on a cache\n\t\t\t// miss (patch targeted a not-yet-cached page) by falling back to a refetch.\n\t\t\tconst ok = infiniteGridData.updateRowAtIndex(rowIndex, patch);\n\t\t\tif (!ok) infiniteGridData.invalidate();\n\t\t},\n\t\t[combinedRows, infiniteScroll, infiniteGridData, updateDraftCell, tableKey],\n\t);\n\n\t// Ref to hold submitDraftRowForEditor - populated after useDraftSubmission\n\t// This breaks the circular dependency: editors need the function, but useDraftSubmission\n\t// needs hasDraftSelection which comes from useGridSelectionState which needs combinedRows\n\tconst submitDraftRowForEditorRef = useRef<((draftRowId: string) => Promise<DraftSubmitResult>) | null>(null);\n\n\tconst handleSubmitDraftRowForEditor = useCallback(\n\t\tasync (draftRowId: string): Promise<DraftSubmitResult> => {\n\t\t\tif (!submitDraftRowForEditorRef.current) {\n\t\t\t\treturn { createdRow: null };\n\t\t\t}\n\t\t\treturn submitDraftRowForEditorRef.current(draftRowId);\n\t\t},\n\t\t[],\n\t);\n\n\t// Memoize feedback callbacks for grid operations\n\tconst operationFeedback = useMemo(\n\t\t() => ({\n\t\t\tonStart: startOperation,\n\t\t\tonProgress: updateOperationProgress,\n\t\t\tonComplete: completeOperation,\n\t\t}),\n\t\t[startOperation, updateOperationProgress, completeOperation],\n\t);\n\n\tconst gridOpsOptions = useMemo(\n\t\t() => ({\n\t\t\tonRemoveDraftRow: (draftRowId: string) => removeDraftRow(tableKey, draftRowId),\n\t\t\tgetRowIdentifier,\n\t\t\tcanDeleteServerRows: canDelete,\n\t\t\tfeedback: operationFeedback,\n\t\t}),\n\t\t[removeDraftRow, tableKey, getRowIdentifier, canDelete, operationFeedback],\n\t);\n\n\tconst { deleteSelected: baseDeleteSelected } = useGridOperations(\n\t\tcombinedRows,\n\t\tdeleteRow,\n\t\tgridState.gridSelection,\n\t\t() => gridActions.setGridSelection(undefined),\n\t\t{\n\t\t\t...gridOpsOptions,\n\t\t\tonAfterServerDeletes: infiniteScroll ? infiniteGridData.invalidate : undefined,\n\t\t},\n\t);\n\n\t// Wrap the delete handler to emit an observational row:delete event with the\n\t// selected-row count, then delegate to the real deletion logic.\n\tconst deleteSelected = useCallback(async () => {\n\t\tconst count = gridState.gridSelection?.rows.length ?? 0;\n\t\temit('row:delete', { count });\n\t\tawait baseDeleteSelected();\n\t}, [baseDeleteSelected, emit, gridState.gridSelection]);\n\n\t// Infinite-mode optimistic cache patch, handed to `useCellEditing` so a server-row\n\t// edit flips the cell BEFORE the `update` round-trip. Snapshots the prior values for\n\t// the patched keys and returns a revert thunk replayed only if the mutation rejects.\n\t// A cache miss (unloaded page) self-heals via `invalidate()`. Paginated mode returns\n\t// undefined here — its optimism lives in the update mutation's onMutate (use-table.ts).\n\tconst applyOptimisticCellPatch = useCallback(\n\t\t(rowIndex: number, patch: Record<string, unknown>): (() => void) | void => {\n\t\t\tif (!infiniteScroll) return;\n\t\t\tconst current = infiniteGridData.getRowAtIndex(rowIndex) as Record<string, unknown> | null;\n\t\t\tconst ok = infiniteGridData.updateRowAtIndex(rowIndex, patch);\n\t\t\tif (!ok) {\n\t\t\t\tinfiniteGridData.invalidate();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst snapshot: Record<string, unknown> = {};\n\t\t\tfor (const key of Object.keys(patch)) snapshot[key] = current ? current[key] : undefined;\n\t\t\treturn () => {\n\t\t\t\tconst reverted = infiniteGridData.updateRowAtIndex(rowIndex, snapshot);\n\t\t\t\tif (!reverted) infiniteGridData.invalidate();\n\t\t\t};\n\t\t},\n\t\t[infiniteScroll, infiniteGridData],\n\t);\n\n\tconst editCell = useCellEditing({\n\t\tcombinedRows,\n\t\tfieldMetaMap,\n\t\trelationInfoByField,\n\t\tupdateDraftCell,\n\t\ttableKey,\n\t\tupdate,\n\t\tgetRowIdentifier,\n\t\treadOnlyFields: primaryKeyFields,\n\t\tcanUpdate,\n\t\tonCellEdit,\n\t\tapplyOptimisticPatch: applyOptimisticCellPatch,\n\t});\n\n\t// History (undo/redo) for server-row value writes. Draft edits are NOT recorded.\n\tconst history = useUndoRedo();\n\n\t// Re-sync a canonical server row over the optimistic patch after the mutation\n\t// resolves (infinite mode only; paginated reconciles via React Query).\n\tconst resyncRow = useCallback(\n\t\t(rowIndex: number, updatedRow: Record<string, unknown>) => {\n\t\t\tif (!infiniteScroll) return;\n\t\t\tconst ok = infiniteGridData.updateRowAtIndex(rowIndex, updatedRow);\n\t\t\tif (!ok) infiniteGridData.invalidate();\n\t\t},\n\t\t[infiniteScroll, infiniteGridData],\n\t);\n\n\t// BATCHED commit primitive — the single server-row value-write path (paste / fill /\n\t// bulk AND, routed below, the single cell). Coalesces optimistic patches + server\n\t// mutations per row and records an undoable HistoryEntry (unless opts.record===false).\n\tconst commitCells = useBatchCommit({\n\t\tcombinedRows,\n\t\tfieldMetaMap,\n\t\trelationInfoByField,\n\t\tupdate,\n\t\tgetRowIdentifier,\n\t\treadOnlyFields: primaryKeyFields,\n\t\tcanUpdate,\n\t\tapplyOptimisticPatch: applyOptimisticCellPatch,\n\t\tresyncRow,\n\t\teditCell,\n\t\tonCellEdit,\n\t\trecord: history.record,\n\t});\n\n\t// @internal NATIVE value-commit for the TanStack DOM grid's portal editors.\n\t// Maps a (rowIndex, colKey, rawValue) commit straight onto the native `editCell`\n\t// (draft `updateDraftCell` / server mutation) — the raw value flows through with\n\t// NO glide cell round-trip (this is what keeps a boolean `false` as `false`). For\n\t// server edits `editCell` already applied the OPTIMISTIC infinite-cache patch before\n\t// awaiting the mutation (and reverted it on failure); here we only re-sync the\n\t// canonical server row when it comes back, then emit the observational `cell:edit`.\n\t// The DOM grid re-renders reactively from `combinedRows`.\n\tconst commitCellValue = useCallback(\n\t\t(rowIndex: number, colKey: string, nextValue: unknown): void => {\n\t\t\tvoid (async () => {\n\t\t\t\ttry {\n\t\t\t\t\t// Single-cell edits route through the SAME batched primitive so a normal cell\n\t\t\t\t\t// edit becomes undoable (server rows) — coercion / readonly / optimistic patch\n\t\t\t\t\t// / re-sync all live inside commitCells (draft rows take its per-cell branch).\n\t\t\t\t\tconst isDraft = !!getDraftMeta(combinedRows[rowIndex]);\n\t\t\t\t\tconst { applied } = await commitCells([{ rowIndex, colKey, value: nextValue }]);\n\n\t\t\t\t\t// Observational: a real cell edit landed — skip no-ops (applied 0 + non-draft).\n\t\t\t\t\tif (applied > 0 || isDraft) {\n\t\t\t\t\t\temit('cell:edit', { field: colKey, rowIndex, target: isDraft ? 'draft' : 'server' });\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconst description = e instanceof Error ? e.message : 'Failed to update cell';\n\t\t\t\t\ttoast.error({ message: 'Update failed', description });\n\t\t\t\t\tsheetsLogger().error('Cell edit error:', e);\n\t\t\t\t\tconfig.onError?.(e, { source: 'mutation', tableName });\n\t\t\t\t}\n\t\t\t})();\n\t\t},\n\t\t[commitCells, combinedRows, config, tableName, emit],\n\t);\n\n\t// @internal NATIVE patch-commit for self-committing DOM portal editors (relation/\n\t// image). These editors mutate server-side themselves, then push a MULTI-field\n\t// patch — routes straight through the EXISTING `handleEditorSaveComplete` (draft\n\t// store update / infinite-cache patch), using the FIRST patch key as the primary colKey.\n\tconst commitCellPatch = useCallback(\n\t\t(rowIndex: number, patch: Record<string, unknown>): void => {\n\t\t\tconst primaryColKey = Object.keys(patch)[0];\n\t\t\tif (!primaryColKey) return;\n\t\t\thandleEditorSaveComplete(primaryColKey, rowIndex, patch);\n\t\t},\n\t\t[handleEditorSaveComplete],\n\t);\n\n\t// @internal NATIVE data-invalidate for self-committing DOM portal editors. Mirrors\n\t// the canvas wiring: infinite mode refetches via the React Query cache; paginated\n\t// invalidation is already handled by React Query in use-table, so this is a no-op there.\n\tconst invalidateData = useCallback(() => {\n\t\tif (infiniteScroll) infiniteGridData.invalidate();\n\t}, [infiniteScroll, infiniteGridData]);\n\n\tconst handleRowAppended = useCallback(async () => {\n\t\tif (!canCreate) return undefined;\n\t\tif (draftRows.length > 0) {\n\t\t\treturn serverRowCount + draftRows.length - 1;\n\t\t}\n\n\t\t// Silently skip if metadata isn't ready - this is a transient state\n\t\tif (!effectiveColumnOrder.length) return undefined;\n\n\t\tcreateDraftRow({\n\t\t\ttableKey,\n\t\t\tcolumnOrder: effectiveColumnOrder,\n\t\t\tfieldMetaByKey: fieldMetaByKey as Record<string, any>,\n\t\t\trelationInfoByKey: relationInfoObject,\n\t\t\tmetaVersion: metaSignature,\n\t\t});\n\n\t\tconst rowIndex = serverRowCount + draftRows.length;\n\t\temit('row:create', { rowIndex });\n\t\treturn rowIndex;\n\t}, [\n\t\tcreateDraftRow,\n\t\teffectiveColumnOrder,\n\t\tfieldMetaByKey,\n\t\trelationInfoObject,\n\t\tmetaSignature,\n\t\ttableKey,\n\t\tdraftRows,\n\t\tserverRowCount,\n\t\tcanCreate,\n\t\temit,\n\t]);\n\n\tconst { selectedRowCount, selectedDraftRowEntries, hasDraftSelection } = useGridSelectionState({\n\t\tgridSelection: gridState.gridSelection,\n\t\tcombinedRows,\n\t\tdraftRowsTable,\n\t});\n\n\tconst {\n\t\tisSubmittingDrafts,\n\t\tsubmitDraftButtonDisabled,\n\t\tsubmitDraftLabel,\n\t\thandleSubmitDraftRows,\n\t\tsubmitDraftRowForEditor,\n\t} = useDraftSubmission({\n\t\ttableKey,\n\t\tdraftRowsTable,\n\t\tselectedDraftRowEntries,\n\t\thasDraftSelection,\n\t\tcreate,\n\t\tremoveDraftRow,\n\t\tsetDraftRowStatus,\n\t\tclearSelection: () => gridActions.setGridSelection(undefined),\n\t\tallowedColumns,\n\t\trelationInfoByKey: relationInfoObject,\n\t\tfieldMetaByKey: fieldMetaByKey as Record<string, any>,\n\t\tonSubmittedSuccessfully: infiniteScroll ? infiniteGridData.invalidate : undefined,\n\t\tfeedback: operationFeedback,\n\t});\n\n\t// Populate the ref for editor access (breaks circular dependency)\n\tsubmitDraftRowForEditorRef.current = submitDraftRowForEditor;\n\n\t// Compute sortable columns (exclude relation fields - only simple data types are sortable)\n\tconst sortableColumns = useMemo(() => {\n\t\treturn new Set(gridColumnKeys.filter((key) => !relationFieldNames.has(key)));\n\t}, [gridColumnKeys, relationFieldNames]);\n\n\t// Header click handler for sorting (only allows sorting on non-relation columns; the\n\t// draft-action column is excluded because it is never in `sortableColumns`).\n\tconst onHeaderClicked = useMemo(\n\t\t() => createHeaderClickHandler(gridColumnKeys, gridActions.toggleSorting, sortableColumns),\n\t\t[gridColumnKeys, gridActions.toggleSorting, sortableColumns],\n\t);\n\n\t// Emit sort:change whenever the resolved sort state transitions. Watching the\n\t// state (rather than the toggle call) reflects the real outcome and covers any\n\t// path that mutates sorting. Skip the initial mount so we don't fire on render.\n\tconst didMountSortRef = useRef(false);\n\tuseEffect(() => {\n\t\tif (!didMountSortRef.current) {\n\t\t\tdidMountSortRef.current = true;\n\t\t\treturn;\n\t\t}\n\t\temit('sort:change', {\n\t\t\tfield: gridState.sorting.id || null,\n\t\t\tdirection: gridState.sorting.id ? (gridState.sorting.desc ? 'desc' : 'asc') : null,\n\t\t});\n\t}, [gridState.sorting, emit]);\n\n\t// ============== INFINITE SCROLL: onVisibleRegionChanged handler ==============\n\t// Translate the DOM viewport's inclusive {startIndex,endIndex} window into the\n\t// prefetch range the infinite source loads (clamped to the server row count).\n\tconst handleVisibleRegionChanged = useCallback(\n\t\t(range: VisibleRowRange) => {\n\t\t\tif (!infiniteScroll) return;\n\t\t\tif (serverRowCount <= 0) return;\n\n\t\t\tconst start = Math.max(0, Math.min(range.startIndex, serverRowCount - 1));\n\t\t\tconst end = Math.max(start, Math.min(range.endIndex, serverRowCount - 1));\n\t\t\tinfiniteGridData.onVisibleRegionChanged({ startIndex: start, endIndex: end });\n\t\t},\n\t\t[infiniteScroll, infiniteGridData, serverRowCount],\n\t);\n\n\tconst setGridSelectionForControls = useCallback(\n\t\t(selection: SheetsSelection | null) => {\n\t\t\tgridActions.setGridSelection(selection ?? undefined);\n\t\t},\n\t\t[gridActions],\n\t);\n\n\t// Build fieldTypeMap for filter controls\n\tconst fieldTypeMap = useMemo(() => {\n\t\tconst map: Record<string, { gqlType: string; isArray: boolean }> = {};\n\t\tfieldMetaMap.forEach((meta, key) => {\n\t\t\tif (meta?.type?.gqlType) {\n\t\t\t\tmap[key] = { gqlType: meta.type.gqlType, isArray: !!meta.type.isArray };\n\t\t\t}\n\t\t});\n\t\treturn map;\n\t}, [fieldMetaMap]);\n\n\tconst applyFilters = useCallback(() => {\n\t\tgridActions.setFiltersOpen(false);\n\t\temit('filter:apply', { conditionCount: countConditions(gridState.filterTree) });\n\t}, [gridActions, emit, gridState.filterTree]);\n\n\t// Compute frozen columns: id column if present\n\tconst frozenCount = useMemo(() => {\n\t\tconst idFrozen = columnKeys[0] === 'id' ? 1 : 0;\n\t\treturn idFrozen; // Row markers are separate\n\t}, [columnKeys]);\n\n\t// Unified, mode-aware refetch. Shared by the load-state retry path and the\n\t// imperative handle in the Sheets shell.\n\tconst refetch = useCallback(() => {\n\t\tif (infiniteScroll) {\n\t\t\tinfiniteGridData.invalidate();\n\t\t} else {\n\t\t\tvoid dataLoadingResult.contextValue.refetch?.();\n\t\t}\n\t}, [infiniteScroll, infiniteGridData, dataLoadingResult.contextValue]);\n\n\t// Pagination setter that mirrors the default chrome behavior (emit page:change).\n\tconst setPageIndex = useCallback(\n\t\t(updater: number | ((prev: number) => number)) => {\n\t\t\tconst next = typeof updater === 'function' ? updater(gridState.pageIndex) : updater;\n\t\t\tgridActions.setPageIndex(next);\n\t\t\temit('page:change', { pageIndex: next });\n\t\t},\n\t\t[gridActions, gridState.pageIndex, emit],\n\t);\n\n\t// Loaded successfully but no server rows and nothing drafted yet, with no active filter.\n\tconst isEmpty =\n\t\thasCompletedInitialLoad &&\n\t\tserverRowCount === 0 &&\n\t\tdraftRows.length === 0 &&\n\t\tcountConditions(gridState.filterTree) === 0;\n\n\treturn {\n\t\t// -- Stable headless surface (see UseSheetsResult) --\n\t\tcolumns,\n\t\trowCount: combinedRows.length,\n\t\tdraft: {\n\t\t\thasDrafts: hasDraftRows,\n\t\t\tappendRow: handleRowAppended,\n\t\t\tsubmitDrafts: handleSubmitDraftRows,\n\t\t\tdeleteSelected,\n\t\t},\n\t\tselection: {\n\t\t\tgridSelection: gridState.gridSelection,\n\t\t\tsetGridSelection: gridActions.setGridSelection,\n\t\t\tsetActiveCell: gridActions.setActiveCell,\n\t\t\tmoveActive: gridActions.moveActiveCell,\n\t\t},\n\t\tpagination: {\n\t\t\tpageIndex: gridState.pageIndex,\n\t\t\tpageCount: totalPages,\n\t\t\tsetPageIndex,\n\t\t},\n\t\tisInitialLoading,\n\t\tdataError,\n\t\thasCompletedInitialLoad,\n\t\tisEmpty,\n\t\trefetch,\n\n\t\t// -- Internal chrome bindings (not a stable API) --\n\t\t_shell: {\n\t\t\tcombinedRows,\n\t\t\tcolumnKeys,\n\t\t\ttotalCount,\n\t\t\tserverRowCount,\n\t\t\tdraftRowCount: draftRows.length,\n\t\t\tinfiniteScroll,\n\t\t\tfilterTree: gridState.filterTree,\n\t\t\tfiltersOpen: gridState.filtersOpen,\n\t\t\tsetFilterTree: gridActions.setFilterTree,\n\t\t\tsetFiltersOpen: gridActions.setFiltersOpen,\n\t\t\tclearAllFilters: gridActions.clearAllFilters,\n\t\t\tapplyFilters,\n\t\t\tfieldTypeMap,\n\t\t\tsetGridSelectionForControls,\n\t\t\tonHeaderClicked,\n\t\t\tonVisibleRegionChanged: handleVisibleRegionChanged,\n\t\t\tsorting: gridState.sorting,\n\t\t\tcolumnWidths: gridState.columnWidths,\n\t\t\tresizeColumn: gridActions.resizeColumn,\n\t\t\tfrozenCount,\n\t\t\tselectedRowCount,\n\t\t\tcanCreate,\n\t\t\tcanUpdate,\n\t\t\tcanDelete,\n\t\t\treadOnlyReason,\n\t\t\tgetRowId,\n\t\t\tisSubmittingDrafts,\n\t\t\tsubmitDraftButtonDisabled,\n\t\t\tsubmitDraftLabel,\n\t\t\tgetSheetsCellContent,\n\t\t\tcellRegistry,\n\t\t\tcommitCellValue,\n\t\t\tcommitCells,\n\t\t\tcommitCellPatch,\n\t\t\tsubmitDraftRow: handleSubmitDraftRowForEditor,\n\t\t\tinvalidateData,\n\t\t\tundo: history.undo,\n\t\t\tredo: history.redo,\n\t\t\tcanUndo: history.canUndo,\n\t\t\tcanRedo: history.canRedo,\n\t\t\temit,\n\t\t},\n\t};\n}\n","/**\n * Build data grid columns that understand relation metadata\n */\nimport { useCallback, useMemo } from 'react';\n\nimport { isImageField, resolveCellType, type FieldMetadata } from '../cell-types/cell-type-resolver';\nimport { getColumnWidthByMeta } from '../grid/sheets.utils';\n\nimport { useRelationMetadataCache, type RelationMetadata } from './use-relation-metadata-cache';\n\ntype RelationKind = 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';\n\n/** Native column descriptor — key/title/width, mappable 1:1 to {@link SheetsColumnDescriptor}. */\nexport interface RelationGridColumn {\n\tid: string;\n\ttitle: string;\n\twidth: number;\n}\n\n/**\n * Relation-aware column info with simple error handling\n */\nexport interface RelationColumnInfo {\n\tcolumns: RelationGridColumn[];\n\tcolumnKeys: string[];\n\trelationMetadata: Record<string, RelationMetadata>;\n\tmetaFields?: FieldMetadata[];\n\thasRelationErrors: boolean;\n\trelationCount: number;\n\t// Helper functions (backward compatible)\n\tisImageField: (fieldMeta: FieldMetadata | undefined, fieldName?: string) => boolean;\n\tfindImageColumnKey: (columnKeys: string[], fieldMetaMap: Map<string, unknown>, currentColKey?: string) => string;\n\tgetRelationKind: (fieldName: string) => RelationKind | null;\n\tisRelationField: (fieldName: string) => boolean;\n\tinvalidateRelationCache: () => Promise<void>;\n\t// For backward compatibility\n\trelationTypeByField: Map<string, RelationKind>;\n}\n\n/**\n * Create data grid columns with relation metadata baked in\n */\nexport function useRelationColumns(tableName?: string, rows?: unknown[]): RelationColumnInfo {\n\tconst { relationMetadata, tableRelations, cacheState, getRelationKind, isRelationField, invalidateRelationCache } =\n\t\tuseRelationMetadataCache(tableName);\n\n\tconst metaFields = useMemo<FieldMetadata[] | undefined>(() => {\n\t\treturn tableRelations?.fields.map((field) => ({\n\t\t\tname: field.name,\n\t\t\ttype: field.type,\n\t\t}));\n\t}, [tableRelations]);\n\n\tconst metaFieldByName = useMemo(() => {\n\t\tconst map = new Map<string, FieldMetadata>();\n\t\tfor (const field of metaFields ?? []) {\n\t\t\tif (field?.name) map.set(field.name, field);\n\t\t}\n\t\treturn map;\n\t}, [metaFields]);\n\n\tconst baseFieldNames = useMemo(() => {\n\t\tif (rows && rows.length > 0) {\n\t\t\tconst sample = rows[0] ?? {};\n\t\t\treturn Object.keys(sample);\n\t\t}\n\n\t\tif (metaFields?.length) {\n\t\t\tconst scalarNames = metaFields.map((field) => field?.name).filter((name): name is string => Boolean(name));\n\t\t\tconst relationNames: string[] = [];\n\t\t\trelationMetadata.forEach((rel) => {\n\t\t\t\tif (rel.sourceField === 'relation') relationNames.push(rel.fieldName);\n\t\t\t});\n\t\t\treturn Array.from(new Set([...scalarNames, ...relationNames]));\n\t\t}\n\n\t\treturn [] as string[];\n\t}, [rows, metaFields, relationMetadata]);\n\n\t// Extract column keys from data\n\tconst columnKeys: string[] = useMemo(() => {\n\t\tif (baseFieldNames.length === 0) return [];\n\t\tconst keys = [...baseFieldNames];\n\n\t\tconst belongsToForeignKeysToHide = new Set<string>();\n\t\tconst foreignKeysByRelationField = new Map<string, string[]>();\n\n\t\trelationMetadata.forEach((rel) => {\n\t\t\tif (rel.sourceField === 'foreignKey' && rel.relationFieldName) {\n\t\t\t\tconst existing = foreignKeysByRelationField.get(rel.relationFieldName);\n\t\t\t\tif (existing) {\n\t\t\t\t\texisting.push(rel.fieldName);\n\t\t\t\t} else {\n\t\t\t\t\tforeignKeysByRelationField.set(rel.relationFieldName, [rel.fieldName]);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\trelationMetadata.forEach((rel) => {\n\t\t\tif (rel.sourceField !== 'relation' || rel.relationKind !== 'belongsTo' || !rel.relationFieldName) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst foreignKeyEntries = foreignKeysByRelationField.get(rel.relationFieldName);\n\t\t\tif (foreignKeyEntries?.length) {\n\t\t\t\tforeignKeyEntries.forEach((fieldName) => {\n\t\t\t\t\tbelongsToForeignKeysToHide.add(fieldName);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\tconst filteredKeys = keys.filter((key) => !belongsToForeignKeysToHide.has(key));\n\n\t\t// Ensure id comes first if present\n\t\tconst idIdx = filteredKeys.indexOf('id');\n\t\tif (idIdx > -1) {\n\t\t\tfilteredKeys.splice(idIdx, 1);\n\t\t\tfilteredKeys.unshift('id');\n\t\t}\n\t\treturn filteredKeys;\n\t}, [baseFieldNames, relationMetadata]);\n\n\t// Create relation metadata map for quick lookup\n\tconst relationMetadataMap = useMemo(() => {\n\t\tconst map: Record<string, RelationMetadata> = {};\n\n\t\trelationMetadata.forEach((rel) => {\n\t\t\tmap[rel.fieldName] = rel;\n\t\t});\n\n\t\treturn map;\n\t}, [relationMetadata]);\n\n\t// Table fields metadata\n\t// Generate columns with improved error handling\n\tconst columns: RelationGridColumn[] = useMemo(() => {\n\t\treturn columnKeys.map((fieldName) => {\n\t\t\tconst metaField = metaFieldByName.get(fieldName);\n\t\t\tconst relationInfo = relationMetadataMap[fieldName];\n\t\t\tconst relationDisplayField = relationInfo?.relationFieldName || undefined;\n\t\t\tconst isForeignKeyRelationField = relationInfo?.sourceField === 'foreignKey';\n\n\t\t\t// Use centralized cell type resolution\n\t\t\tconst resolution = resolveCellType(fieldName, metaField);\n\t\t\tconst cellType = resolution.cellType;\n\n\t\t\t// For relation fields, use relation kind as type label\n\t\t\tconst typeLabel = relationInfo?.relationKind\n\t\t\t\t? relationInfo.relationKind\n\t\t\t\t: metaField\n\t\t\t\t\t? metaField.type?.pgAlias || metaField.type?.pgType || metaField.type?.gqlType\n\t\t\t\t\t: cellType;\n\n\t\t\tlet headerName = fieldName;\n\t\t\tif (relationInfo?.displayName) {\n\t\t\t\theaderName = relationInfo.displayName;\n\t\t\t} else if (relationDisplayField) {\n\t\t\t\theaderName = relationDisplayField;\n\t\t\t} else if (isForeignKeyRelationField) {\n\t\t\t\tconst stripped = fieldName.replace(/Id$/i, '');\n\t\t\t\theaderName = stripped.length > 0 ? stripped : fieldName;\n\t\t\t}\n\n\t\t\tconst titleRaw = typeLabel ? `${headerName} (${typeLabel})` : headerName;\n\n\t\t\treturn {\n\t\t\t\tid: fieldName,\n\t\t\t\ttitle: titleRaw,\n\t\t\t\twidth: metaField ? getColumnWidthByMeta(metaField) : 150,\n\t\t\t} satisfies RelationGridColumn;\n\t\t});\n\t}, [columnKeys, metaFieldByName, relationMetadataMap]);\n\n\t// Helper function using centralized image field detection\n\tconst checkIsImageField = useCallback((fieldMeta: FieldMetadata | undefined, fieldName?: string): boolean => {\n\t\treturn isImageField(fieldMeta, fieldName);\n\t}, []);\n\n\t// Helper function to find the correct column key for image cells\n\tconst findImageColumnKey = useCallback(\n\t\t(columnKeys: string[], fieldMetaMap: Map<string, unknown>, currentColKey?: string): string => {\n\t\t\t// If we already have a reliable column key, use it\n\t\t\tif (currentColKey && currentColKey !== 'id' && fieldMetaMap.has(currentColKey)) {\n\t\t\t\tconst fieldMeta = fieldMetaMap.get(currentColKey) as FieldMetadata | undefined;\n\t\t\t\tif (checkIsImageField(fieldMeta, currentColKey)) {\n\t\t\t\t\treturn currentColKey;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Look through all columns to find image-type fields\n\t\t\tfor (const key of columnKeys) {\n\t\t\t\tconst fieldMeta = fieldMetaMap.get(key) as FieldMetadata | undefined;\n\t\t\t\tif (fieldMeta && checkIsImageField(fieldMeta, key)) {\n\t\t\t\t\treturn key;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Fallback to the current column key or first non-id column\n\t\t\treturn currentColKey || columnKeys.find((k) => k !== 'id') || columnKeys[0] || '';\n\t\t},\n\t\t[checkIsImageField],\n\t);\n\n\t// Create backward compatibility map\n\tconst relationTypeByField = useMemo(() => {\n\t\tconst map = new Map<string, RelationKind>();\n\t\tObject.entries(relationMetadataMap).forEach(([fieldName, info]) => {\n\t\t\tmap.set(fieldName, info.relationKind);\n\t\t});\n\t\treturn map;\n\t}, [relationMetadataMap]);\n\n\treturn {\n\t\tcolumns,\n\t\tcolumnKeys,\n\t\trelationMetadata: relationMetadataMap,\n\t\tmetaFields,\n\t\thasRelationErrors: cacheState.isError,\n\t\trelationCount: cacheState.relationCount,\n\t\tisImageField: checkIsImageField,\n\t\tfindImageColumnKey,\n\t\tgetRelationKind,\n\t\tisRelationField,\n\t\tinvalidateRelationCache,\n\t\trelationTypeByField, // For backward compatibility\n\t};\n}\n\n/**\n * Drop-in replacement for the original useDataGridColumns hook\n * Maintains complete backward compatibility while providing improvements\n */\nexport function useDataGridColumns(tableName?: string, rows: unknown[] = []) {\n\tconst enhanced = useRelationColumns(tableName, rows);\n\n\t// Return exact same interface as original for backward compatibility\n\treturn {\n\t\tcolumns: enhanced.columns,\n\t\tcolumnKeys: enhanced.columnKeys,\n\t\tmetaFields: enhanced.metaFields,\n\t\tisImageField: enhanced.isImageField,\n\t\tfindImageColumnKey: enhanced.findImageColumnKey,\n\t\trelationTypeByField: enhanced.relationTypeByField,\n\t\t// Add new enhanced features for those who want them\n\t\trelationMetadata: enhanced.relationMetadata,\n\t\thasRelationErrors: enhanced.hasRelationErrors,\n\t\trelationCount: enhanced.relationCount,\n\t\tgetRelationKind: enhanced.getRelationKind,\n\t\tisRelationField: enhanced.isRelationField,\n\t\tinvalidateRelationCache: enhanced.invalidateRelationCache,\n\t};\n}\n","import type { CellType } from './types';\n\nimport type { CellPlugin, CellRegistryEntry, CellRenderer } from './types';\n\nclass CellRegistryClass {\n\tprivate entries = new Map<CellType, CellRegistryEntry>();\n\tprivate plugins = new Map<string, CellPlugin>();\n\n\t// Register a cell renderer for a cell type\n\tregister(entry: CellRegistryEntry): void {\n\t\tthis.entries.set(entry.type, entry);\n\t}\n\n\t// Register multiple entries at once\n\tregisterBatch(entries: CellRegistryEntry[]): void {\n\t\tentries.forEach((entry) => this.register(entry));\n\t}\n\n\t// Get cell renderer for a type\n\tget(type: CellType): CellRegistryEntry | undefined {\n\t\treturn this.entries.get(type);\n\t}\n\n\t// Get all registered cell types\n\tgetAll(): CellRegistryEntry[] {\n\t\treturn Array.from(this.entries.values());\n\t}\n\n\t// Get cell component for a type\n\tgetComponent(type: CellType): CellRenderer | undefined {\n\t\tconst entry = this.entries.get(type);\n\t\treturn entry?.component;\n\t}\n\n\t// Find cell entry by match function\n\t// NOTE: Cell type is determined ONLY from schema metadata, never from runtime values\n\tfindByMatch(metadata: {\n\t\tgqlType: string;\n\t\tisArray: boolean;\n\t\tpgAlias?: string | null;\n\t\tpgType?: string | null;\n\t\tsubtype?: string | null;\n\t\tfieldName?: string;\n\t}): CellRegistryEntry | undefined {\n\t\t// Iterate through all entries and find the first one with a matching match function\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.match && entry.match(metadata)) {\n\t\t\t\treturn entry;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Get cell component using match function first, then fallback to type\n\t// NOTE: Cell type is determined ONLY from schema metadata, never from runtime values\n\tgetComponentWithMatch(\n\t\ttype: CellType,\n\t\tmetadata?: {\n\t\t\tgqlType: string;\n\t\t\tisArray: boolean;\n\t\t\tpgAlias?: string | null;\n\t\t\tpgType?: string | null;\n\t\t\tsubtype?: string | null;\n\t\t\tfieldName?: string;\n\t\t},\n\t): CellRenderer | undefined {\n\t\t// First try to find by match function if metadata is provided\n\t\tif (metadata) {\n\t\t\tconst matchedEntry = this.findByMatch(metadata);\n\t\t\tif (matchedEntry) {\n\t\t\t\treturn matchedEntry.component;\n\t\t\t}\n\t\t}\n\n\t\t// Fallback to regular type-based lookup\n\t\treturn this.getComponent(type);\n\t}\n\n\t// Get edit component for a type\n\tgetEditComponent(type: CellType): CellRenderer | undefined {\n\t\tconst entry = this.entries.get(type);\n\t\treturn entry?.editComponent || entry?.component;\n\t}\n\n\t// Check if a type is registered\n\thas(type: CellType): boolean {\n\t\treturn this.entries.has(type);\n\t}\n\n\t// Install a plugin\n\tinstallPlugin(plugin: CellPlugin): void {\n\t\tif (this.plugins.has(plugin.name)) {\n\t\t\tconsole.warn(`Plugin ${plugin.name} is already installed`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Install plugin cells\n\t\tplugin.cells.forEach((cell) => this.register(cell));\n\n\t\t// Run plugin install hook\n\t\tplugin.install?.();\n\n\t\tthis.plugins.set(plugin.name, plugin);\n\t}\n\n\t// Uninstall a plugin\n\tuninstallPlugin(pluginName: string): void {\n\t\tconst plugin = this.plugins.get(pluginName);\n\t\tif (!plugin) {\n\t\t\tconsole.warn(`Plugin ${pluginName} is not installed`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Remove plugin cells\n\t\tplugin.cells.forEach((cell) => this.entries.delete(cell.type));\n\n\t\t// Run plugin uninstall hook\n\t\tplugin.uninstall?.();\n\n\t\tthis.plugins.delete(pluginName);\n\t}\n\n\t// Get installed plugins\n\tgetInstalledPlugins(): CellPlugin[] {\n\t\treturn Array.from(this.plugins.values());\n\t}\n\n\t// Clear all entries (useful for testing)\n\tclear(): void {\n\t\tthis.entries.clear();\n\t\tthis.plugins.clear();\n\t}\n\n\t// Get entries by category\n\tgetByCategory(category: string): CellRegistryEntry[] {\n\t\treturn Array.from(this.entries.values()).filter((entry) => entry.metadata?.category === category);\n\t}\n}\n\n// Export singleton instance\n/**\n * @deprecated since 0.2.0 — pass cell types via <SheetsProvider config={{ plugins }}> or <Sheets cellTypes>. CellRegistry only ever affected detection.\n */\nexport const CellRegistry = new CellRegistryClass();\n\n// Export factory function for testing\nexport function createCellRegistry(): CellRegistryClass {\n\treturn new CellRegistryClass();\n}\n","import { ENHANCED_TYPES, MEDIA_TYPES, STRUCTURED_DATA_TYPES } from './cell-type-groups';\nimport type { CellType, ColumnSchema } from './types';\n\n/**\n * Maps GraphQL field metadata to frontend cell types\n * Uses priority: pgAlias > pgType > gqlType for type determination\n * This is completely backend-agnostic and focuses only on frontend rendering needs\n */\nexport function mapToFrontendCellType(metadata: {\n\tgqlType: string;\n\tisArray: boolean;\n\tpgAlias?: string | null;\n\tpgType?: string | null;\n\tsubtype?: string | null;\n\tencoding?: { kind: string; geometrySubtype?: string | null } | null;\n}): CellType {\n\tconst { gqlType, isArray, pgAlias, pgType } = metadata;\n\n\tconst encodedType = mapEncodingToCellType(metadata.encoding);\n\tif (encodedType) return encodedType;\n\n\t// Priority 1: Use pgAlias if available (most specific)\n\t// This must be checked FIRST, even for arrays, to preserve types like 'array' vs 'text-array'\n\tif (pgAlias) {\n\t\tconst aliasType = mapAliasToCellType(pgAlias);\n\t\tif (aliasType !== 'unknown') return aliasType;\n\t}\n\n\t// Handle arrays after pgAlias check\n\tif (isArray) {\n\t\tconst result = mapGraphQLTypeToCellType(gqlType, isArray, metadata.subtype, null);\n\t\treturn result;\n\t}\n\n\t// Priority 2: Use pgType if available (backend-specific but still useful)\n\tif (pgType) {\n\t\tconst pgTypeMapped = mapBackendTypeToCellType(pgType);\n\t\tif (pgTypeMapped !== 'unknown') return pgTypeMapped;\n\t}\n\n\t// Priority 3: Fall back to GraphQL type\n\tconst fallbackResult = mapGraphQLTypeToCellType(gqlType, isArray, metadata.subtype, null);\n\treturn fallbackResult;\n}\n\nfunction mapEncodingToCellType(\n\tencoding?: { kind: string; geometrySubtype?: string | null } | null,\n): CellType | null {\n\tif (!encoding) return null;\n\n\tswitch (encoding.kind) {\n\t\tcase 'bigint': return 'integer';\n\t\tcase 'datetime': return 'datetime';\n\t\tcase 'date': return 'date';\n\t\tcase 'time': return 'time';\n\t\tcase 'interval': return 'interval';\n\t\tcase 'uuid': return 'uuid';\n\t\tcase 'inet': return 'inet';\n\t\tcase 'point': return 'geometry-point';\n\t\tcase 'geojson':\n\t\t\treturn encoding.geometrySubtype === 'Point' ? 'geometry-point' : 'geometry';\n\t\tcase 'vector': return 'number-array';\n\t\tcase 'composite': return 'json';\n\t\tcase 'ltree':\n\t\tcase 'bytea':\n\t\t\treturn 'text';\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Maps PostgreSQL aliases to frontend cell types\n */\nfunction mapAliasToCellType(alias: string): CellType {\n\tconst aliasMap: Record<string, CellType> = {\n\t\t// Media types\n\t\timage: 'image',\n\t\tfile: 'file',\n\t\tvideo: 'video',\n\t\taudio: 'audio',\n\t\tupload: 'upload',\n\n\t\t// Relation types\n\t\trelation: 'relation',\n\n\t\t// Special text types\n\t\temail: 'email',\n\t\turl: 'url',\n\t\tphone: 'phone',\n\t\tcitext: 'citext',\n\t\ttextarea: 'textarea',\n\n\t\t// Enhanced numeric types\n\t\tnumber: 'number',\n\t\tcurrency: 'currency',\n\t\tpercentage: 'percentage',\n\t\tnumeric: 'decimal',\n\t\tdecimal: 'decimal',\n\t\tint: 'integer',\n\t\tinteger: 'integer',\n\t\tsmallint: 'smallint',\n\n\t\t// Boolean types\n\t\tboolean: 'boolean',\n\t\ttoggle: 'toggle',\n\n\t\t// Date/time types\n\t\tdate: 'date',\n\t\tdatetime: 'datetime',\n\t\ttime: 'time',\n\t\ttimestamptz: 'timestamptz',\n\t\tinterval: 'interval',\n\n\t\t// JSON types\n\t\tjson: 'json',\n\t\tjsonb: 'jsonb',\n\n\t\t// Network types\n\t\tinet: 'inet',\n\n\t\t// Geometric types\n\t\tgeometry: 'geometry',\n\t\t'geometry-point': 'geometry-point',\n\t\t'geometry-collection': 'geometry-collection',\n\n\t\t// Special types\n\t\tcolor: 'color',\n\t\trating: 'rating',\n\t\ttags: 'tags',\n\t\tuuid: 'uuid',\n\t\ttsvector: 'tsvector',\n\t\torigin: 'origin',\n\n\t\t// Character types\n\t\tchar: 'bpchar',\n\t\tbpchar: 'bpchar',\n\t\ttext: 'text',\n\n\t\t// Binary types\n\t\tbit: 'bit',\n\n\t\t// Array types (for when pgAlias is used with arrays)\n\t\tarray: 'array',\n\t\t'text-array': 'text-array',\n\t\t'integer-array': 'integer-array',\n\t\t'number-array': 'number-array',\n\t\t'uuid-array': 'uuid-array',\n\t\t'date-array': 'date-array',\n\t};\n\n\treturn aliasMap[alias.toLowerCase()] || 'unknown';\n}\n\n/**\n * Maps backend-specific types to frontend cell types\n */\nfunction mapBackendTypeToCellType(pgType: string): CellType {\n\tconst typeMap: Record<string, CellType> = {\n\t\t// Text types\n\t\ttext: 'text',\n\t\tvarchar: 'text',\n\t\tcharacter: 'text',\n\t\tchar: 'text',\n\t\t'character varying': 'text',\n\t\tcitext: 'citext',\n\t\tbpchar: 'bpchar',\n\n\t\t// Numeric types\n\t\tinteger: 'integer',\n\t\tint4: 'integer',\n\t\tsmallint: 'smallint',\n\t\tint2: 'smallint',\n\t\tbigint: 'integer',\n\t\tint8: 'integer',\n\t\tnumeric: 'decimal',\n\t\tdecimal: 'decimal',\n\t\treal: 'number',\n\t\tfloat4: 'number',\n\t\t'double precision': 'number',\n\t\tfloat8: 'number',\n\t\tmoney: 'currency',\n\n\t\t// Boolean\n\t\tboolean: 'boolean',\n\t\tbool: 'boolean',\n\n\t\t// Binary/Bit types\n\t\tbit: 'bit',\n\t\t'bit varying': 'bit',\n\t\tvarbit: 'bit',\n\n\t\t// Date/time types\n\t\tdate: 'date',\n\t\ttimestamp: 'datetime',\n\t\ttimestamptz: 'timestamptz',\n\t\t'timestamp with time zone': 'timestamptz',\n\t\t'timestamp without time zone': 'datetime',\n\t\ttime: 'time',\n\t\ttimetz: 'time',\n\t\t'time with time zone': 'time',\n\t\t'time without time zone': 'time',\n\t\tinterval: 'interval',\n\n\t\t// JSON types\n\t\tjson: 'json',\n\t\tjsonb: 'jsonb',\n\n\t\t// UUID\n\t\tuuid: 'uuid',\n\n\t\t// Full-text search\n\t\ttsvector: 'tsvector',\n\n\t\t// Network types\n\t\tinet: 'inet',\n\t\tcidr: 'inet',\n\t\tmacaddr: 'text',\n\t\tmacaddr8: 'text',\n\n\t\t// Geometric types\n\t\tpoint: 'geometry-point',\n\t\tline: 'geometry',\n\t\tlseg: 'geometry',\n\t\tbox: 'geometry',\n\t\tpath: 'geometry',\n\t\tpolygon: 'geometry',\n\t\tcircle: 'geometry',\n\t\tgeometry: 'geometry',\n\t\tgeography: 'geometry',\n\n\t\t// Custom types\n\t\temail: 'email',\n\t\turl: 'url',\n\t\timage: 'image',\n\t\tupload: 'upload',\n\t\torigin: 'origin',\n\n\t\t// Arrays are handled by isArray flag\n\t\t_text: 'array',\n\t\t_varchar: 'array',\n\t\t_integer: 'array',\n\t};\n\n\treturn typeMap[pgType.toLowerCase()] || 'unknown';\n}\n\n/**\n * Maps GraphQL types to frontend cell types based on actual _meta data structure\n */\nfunction mapGraphQLTypeToCellType(\n\tgqlType: string,\n\tisArray: boolean,\n\tsubtype?: string | null,\n\t_typmod?: unknown,\n): CellType {\n\t// Handle array types specifically\n\tif (isArray) {\n\t\t// Extract base type from array notation like [String], [UUID], etc.\n\t\tconst baseType = gqlType.replace(/[!\\[\\]]/g, '');\n\n\t\t// Map specific array types to their array cell types\n\t\tconst arrayTypeMap: Record<string, CellType> = {\n\t\t\tString: 'text-array',\n\t\t\tUUID: 'uuid-array',\n\t\t\tBigFloat: 'number-array',\n\t\t\tInt: 'integer-array',\n\t\t\tDate: 'date-array',\n\t\t};\n\n\t\treturn arrayTypeMap[baseType] || 'array'; // fallback to generic array\n\t}\n\n\t// Remove GraphQL type modifiers for base type matching\n\tconst baseType = gqlType.replace(/[!\\[\\]]/g, '');\n\n\t// Handle complex types based on actual metadata patterns\n\n\t// 1. Relation types\n\tif (baseType === 'Relation') {\n\t\treturn 'relation';\n\t}\n\n\t// 2. Interval types\n\tif (baseType === 'Interval') {\n\t\treturn 'interval';\n\t}\n\n\t// 3. GeometryGeometryCollection types\n\tif (baseType === 'GeometryGeometryCollection') {\n\t\treturn 'geometry-collection';\n\t}\n\n\t// 4. GeoJSON types with subtypes\n\tif (baseType === 'GeoJSON') {\n\t\tif (subtype === 'GeometryPoint') {\n\t\t\treturn 'geometry-point';\n\t\t}\n\t\tif (subtype === 'GeometryPolygon') {\n\t\t\treturn 'geometry-collection'; // Could be 'geometry-polygon' if you create that cell type\n\t\t}\n\t\t// Default for other GeoJSON types - should be geometry, not json\n\t\t// This ensures null geometry values are properly handled\n\t\treturn 'geometry';\n\t}\n\n\tconst typeMap: Record<string, CellType> = {\n\t\t// GraphQL scalar types\n\t\tString: 'text',\n\t\tInt: 'integer',\n\t\tFloat: 'number',\n\t\tBoolean: 'boolean',\n\t\tID: 'uuid',\n\n\t\t// Common GraphQL custom scalars\n\t\tDateTime: 'datetime',\n\t\tDatetime: 'datetime', // Handle both cases\n\t\tDate: 'date',\n\t\tTime: 'time',\n\t\tJSON: 'json',\n\t\tJSONObject: 'json',\n\t\tUpload: 'file',\n\t\tURL: 'url',\n\t\tEmailAddress: 'email',\n\t\tPhoneNumber: 'phone',\n\t\tUUID: 'uuid',\n\t\tBigFloat: 'number',\n\t\tBigInt: 'integer',\n\t};\n\n\treturn typeMap[baseType] || 'text'; // Default to text for unknown GraphQL types\n}\n\n/**\n * Determines if a field represents structured data that should be rendered as JSON\n */\nexport function isStructuredDataType(cellType: CellType): boolean {\n\treturn STRUCTURED_DATA_TYPES.has(cellType);\n}\n\n/**\n * Determines if a field represents media content\n */\nexport function isMediaType(cellType: CellType): boolean {\n\treturn MEDIA_TYPES.has(cellType);\n}\n\n/**\n * Determines if a field is a special frontend-enhanced type\n */\nexport function isEnhancedType(cellType: CellType): boolean {\n\treturn ENHANCED_TYPES.has(cellType);\n}\n\n/**\n * Create a ColumnSchema from GraphQL meta field data\n */\nexport function createColumnSchemaFromMeta(field: {\n\tname: string;\n\ttype: {\n\t\tgqlType: string;\n\t\tisArray: boolean;\n\t\tmodifier?: string | number | null;\n\t\tpgAlias?: string | null;\n\t\tpgType?: string | null;\n\t\tsubtype?: string | null;\n\t\ttypmod?: any;\n\t\tencoding?: { kind: string; geometrySubtype?: string | null } | null;\n\t};\n}): ColumnSchema {\n\tconst { name, type } = field;\n\tconst { gqlType, isArray, subtype } = type;\n\n\t// Determine if field is nullable (GraphQL types ending with ! are non-null)\n\tconst nullable = !gqlType.endsWith('!');\n\n\t// Map to frontend cell type using metadata\n\tconst cellType = mapToFrontendCellType(field.type);\n\n\t// Generate human-friendly label\n\tconst label = name\n\t\t.replace(/([A-Z])/g, ' $1')\n\t\t.replace(/^./, (str) => str.toUpperCase())\n\t\t.trim();\n\n\treturn {\n\t\tid: name,\n\t\tname,\n\t\ttype: cellType,\n\t\tnullable,\n\t\tmetadata: {\n\t\t\tlabel,\n\t\t\tdescription: `${gqlType}${isArray ? '[]' : ''}${subtype ? ` (${subtype})` : ''}`,\n\t\t\tsortable: !isArray && cellType !== 'json' && cellType !== 'geometry-collection',\n\t\t\tfilterable: cellType !== 'geometry-collection',\n\t\t},\n\t};\n}\n","import { CellRegistry } from './cell-registry';\nimport { NON_EDITABLE_TYPES, VIEWER_ONLY_TYPES } from './cell-type-groups';\nimport { mapToFrontendCellType } from './type-mapping';\n\nexport interface FieldMetadata {\n\tname: string;\n\ttype?: {\n\t\tgqlType: string;\n\t\tpgType?: string | null;\n\t\tpgAlias?: string | null;\n\t\tisArray?: boolean;\n\t\tsubtype?: string | null;\n\t};\n}\n\nexport interface CellTypeResolution {\n\tcellType: string;\n\tcanEdit: boolean;\n\tcanActivate: boolean;\n\tactivationBehavior: 'single-click' | 'double-click';\n\tisReadonly: boolean;\n}\n\n// Use double-click to activate overlay for all cell types\nconst SINGLE_CLICK_CELL_TYPES = new Set<string>();\n\nconst READONLY_CONDITIONS = new Map([\n\t['id', (fieldMeta?: FieldMetadata) => fieldMeta?.type?.gqlType === 'UUID'],\n\t['createdAt', () => true],\n\t['updatedAt', () => true],\n]);\n\nexport function resolveCellType(fieldName: string, fieldMeta?: FieldMetadata): CellTypeResolution {\n\t// Check for readonly fields first\n\tconst readonlyCheck = READONLY_CONDITIONS.get(fieldName);\n\tconst isReadonly = readonlyCheck?.(fieldMeta) ?? false;\n\n\tlet cellType: string = 'text'; // Default fallback\n\n\tif (fieldMeta?.type) {\n\t\t// First try CellRegistry matching (same as existing logic)\n\t\t// NOTE: Cell type is determined ONLY from schema metadata, never from runtime values\n\t\tconst matchedEntry = CellRegistry.findByMatch({\n\t\t\tgqlType: fieldMeta.type.gqlType || '',\n\t\t\tisArray: !!fieldMeta.type.isArray,\n\t\t\tpgAlias: fieldMeta.type.pgAlias,\n\t\t\tpgType: fieldMeta.type.pgType,\n\t\t\tsubtype: fieldMeta.type.subtype ?? null,\n\t\t\tfieldName,\n\t\t});\n\n\t\tif (matchedEntry) {\n\t\t\tcellType = matchedEntry.type;\n\t\t} else {\n\t\t\t// Fallback: Map GraphQL field metadata to frontend cell types\n\t\t\tcellType = mapToFrontendCellType({\n\t\t\t\tgqlType: fieldMeta.type.gqlType,\n\t\t\t\tisArray: !!fieldMeta.type.isArray,\n\t\t\t\tpgAlias: fieldMeta.type.pgAlias,\n\t\t\t\tpgType: fieldMeta.type.pgType,\n\t\t\t\tsubtype: fieldMeta.type.subtype ?? null,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Determine editing capabilities\n\tconst canEdit = !isReadonly && !NON_EDITABLE_TYPES.has(cellType);\n\tconst canActivate = canEdit || VIEWER_ONLY_TYPES.has(cellType);\n\tconst activationBehavior = SINGLE_CLICK_CELL_TYPES.has(cellType) ? 'single-click' : 'double-click';\n\n\treturn {\n\t\tcellType,\n\t\tcanEdit,\n\t\tcanActivate,\n\t\tactivationBehavior,\n\t\tisReadonly,\n\t};\n}\n\nexport function shouldShowCellActivation(fieldName: string, cellType: string): boolean {\n\t// Disable activation for specific readonly fields\n\tif (fieldName === 'createdAt' || fieldName === 'updatedAt') {\n\t\treturn false;\n\t}\n\n\tif (VIEWER_ONLY_TYPES.has(cellType)) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n// Helper for checking if a field is an image type (used by existing column logic)\nexport function isImageField(fieldMeta?: FieldMetadata, fieldName?: string): boolean {\n\tif (!fieldMeta || !fieldName) return false;\n\n\t// Check if this field is configured as an image type\n\tconst isImageByType =\n\t\tfieldMeta.type?.gqlType === 'JSON' && // Image fields are often JSON\n\t\t(fieldName.toLowerCase().includes('image') ||\n\t\t\tfieldName.toLowerCase().includes('picture') ||\n\t\t\tfieldName.toLowerCase().includes('photo') ||\n\t\t\tfieldName.toLowerCase().includes('avatar'));\n\n\t// Also check using CellRegistry matching\n\tconst matchedEntry = CellRegistry.findByMatch({\n\t\tgqlType: fieldMeta.type?.gqlType || '',\n\t\tisArray: !!fieldMeta.type?.isArray,\n\t\tpgAlias: fieldMeta.type?.pgAlias,\n\t\tpgType: fieldMeta.type?.pgType,\n\t\tsubtype: fieldMeta.type?.subtype ?? null,\n\t\tfieldName,\n\t});\n\n\treturn isImageByType || matchedEntry?.type === 'image';\n}\n","import { CellRegistry } from '../cell-types/cell-registry';\nimport { prepareCreateInput, type MetaField, type Filter } from '@constructive-io/data';\nimport { mapToFrontendCellType } from '../cell-types/type-mapping';\nimport type { RelationInfo } from '../store/relation-info-slice';\n\nimport type { FieldMetadata } from '../cell-types/cell-type-resolver';\nimport type { FilterCondition, FilterGroup, FilterNode, FilterValue } from './sheets.controls';\nimport { isFilterableType, isValuelessOperator } from './filter-operators';\nimport { compactJsonPreview } from './sheets.formatters';\n\nexport function formatColumnHeader(fieldName: string): string {\n\treturn fieldName\n\t\t.replace(/([A-Z])/g, ' $1')\n\t\t.replace(/^./, (str) => str.toUpperCase())\n\t\t.replace(/_/g, ' ')\n\t\t.trim();\n}\n\nexport function getColumnWidthByMeta(field: FieldMetadata): number {\n\tconst t = field.type;\n\tif (!t) return 150;\n\tconst cellType = mapToFrontendCellType({\n\t\tgqlType: t.gqlType,\n\t\tisArray: !!t.isArray,\n\t\tpgAlias: t.pgAlias,\n\t\tpgType: t.pgType,\n\t\tsubtype: t.subtype ?? null,\n\t});\n\tconst entry = CellRegistry.get(cellType);\n\treturn entry?.metadata?.width ?? 150;\n}\n\ntype FilterableFieldMeta = {\n\tname?: string | null;\n\ttype?: {\n\t\tgqlType?: string | null;\n\t\tisArray?: boolean | null;\n\t\tpgType?: string | null;\n\t} | null;\n};\n\ntype FilterableTableMeta = {\n\tfields?: Array<FilterableFieldMeta | null> | null;\n} | null | undefined;\n\n/** Coerce a raw string value to the appropriate JS type based on gqlType. */\nfunction coerceFilterValue(gqlType: string | null | undefined, strVal: string): unknown {\n\tswitch (gqlType) {\n\t\tcase 'Int': {\n\t\t\tconst n = parseInt(strVal, 10);\n\t\t\treturn Number.isNaN(n) ? null : n;\n\t\t}\n\t\tcase 'Float': {\n\t\t\tconst n = parseFloat(strVal);\n\t\t\treturn Number.isNaN(n) ? null : n;\n\t\t}\n\t\tcase 'Interval': {\n\t\t\t// Value is a JSON-encoded IntervalInput object from the structured UI\n\t\t\ttry {\n\t\t\t\tconst obj = JSON.parse(strVal);\n\t\t\t\tif (obj && typeof obj === 'object' && !Array.isArray(obj)) return obj;\n\t\t\t\treturn null;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\t// Everything else passes through as string\n\t\tdefault:\n\t\t\treturn strVal;\n\t}\n}\n\n/**\n * Build the filter expression for a single field using an explicit operator.\n * Returns null for types that cannot be filtered (arrays, GeoJSON, FullText, unknown types).\n */\nfunction buildFieldFilter(\n\tfieldMeta: FilterableFieldMeta | null | undefined,\n\toperator: string,\n\trawValue: FilterValue,\n): Record<string, unknown> | null {\n\t// Value-less operators encode their value in the operator name\n\tif (isValuelessOperator(operator)) {\n\t\tif (operator === 'isNull') return { isNull: true };\n\t\tif (operator === 'equalTo:true') return { equalTo: true };\n\t\tif (operator === 'equalTo:false') return { equalTo: false };\n\t}\n\n\tconst gqlType = fieldMeta?.type?.gqlType;\n\tconst isArray = !!fieldMeta?.type?.isArray;\n\n\t// Skip unfilterable types (arrays, GeoJSON, FullText, unknown)\n\tif (!isFilterableType(gqlType, isArray)) return null;\n\n\tconst strVal = String(rawValue);\n\tconst coerced = coerceFilterValue(gqlType, strVal);\n\tif (coerced === null) return null;\n\n\treturn { [operator]: coerced };\n}\n\n/** Convert a single condition node to a PostGraphile filter expression. */\nfunction conditionToWhere(\n\tcondition: FilterCondition,\n\tfieldsByName: Map<string, FilterableFieldMeta>,\n): Filter | null {\n\t// Skip empty-value conditions (unless valueless operator)\n\tif (\n\t\t!isValuelessOperator(condition.operator) &&\n\t\t(condition.value === '' || condition.value === null || condition.value === undefined)\n\t) {\n\t\treturn null;\n\t}\n\tconst fieldMeta = fieldsByName.get(condition.field);\n\tconst filterExpr = buildFieldFilter(fieldMeta, condition.operator, condition.value);\n\treturn filterExpr ? ({ [condition.field]: filterExpr } as Filter) : null;\n}\n\n/** Recursively convert a filter tree node to a PostGraphile Filter object. */\nfunction filterNodeToWhere(\n\tnode: FilterNode,\n\tfieldsByName: Map<string, FilterableFieldMeta>,\n): Filter | null {\n\tif (node.type === 'condition') {\n\t\treturn conditionToWhere(node, fieldsByName);\n\t}\n\n\tconst childFilters = node.children\n\t\t.map((child) => filterNodeToWhere(child, fieldsByName))\n\t\t.filter((f): f is Filter => f !== null);\n\n\tif (childFilters.length === 0) return null;\n\tif (childFilters.length === 1) return childFilters[0];\n\treturn { [node.conjunction]: childFilters };\n}\n\nexport function buildWhereFromFilters(\n\tfilterTree: FilterGroup,\n\ttableMeta: FilterableTableMeta,\n): Filter | undefined {\n\tif (!filterTree.children.length) return undefined;\n\n\t// Pre-build field lookup map\n\tconst fieldsByName = new Map<string, FilterableFieldMeta>();\n\tfor (const field of tableMeta?.fields ?? []) {\n\t\tif (field?.name) fieldsByName.set(field.name, field);\n\t}\n\n\tconst treeWhere = filterNodeToWhere(filterTree, fieldsByName);\n\treturn treeWhere ?? undefined;\n}\n\nexport function mapFromFieldMetaMap(fieldMetaMap: Map<string, MetaField>): Record<string, MetaField | undefined> {\n\tconst record: Record<string, MetaField | undefined> = {};\n\tfieldMetaMap.forEach((value, key) => {\n\t\trecord[key] = value;\n\t});\n\treturn record;\n}\n\nexport function mapFromRelationInfoMap(\n\trelationInfoMap: Map<string, RelationInfo | undefined>,\n): Record<string, RelationInfo | undefined> {\n\tconst record: Record<string, RelationInfo | undefined> = {};\n\trelationInfoMap.forEach((value, key) => {\n\t\trecord[key] = value;\n\t});\n\treturn record;\n}\n\nfunction unwrapConnectionNode(entry: unknown): unknown {\n\tif (!entry || typeof entry !== 'object') return entry;\n\n\tconst record = entry as Record<string, unknown>;\n\tif ('node' in record && record.node !== undefined) {\n\t\treturn unwrapConnectionNode(record.node);\n\t}\n\treturn entry;\n}\n\nexport function unwrapRelationValue<T = unknown>(value: T): T {\n\tif (Array.isArray(value)) {\n\t\treturn value.map((entry) => unwrapRelationValue(entry)) as unknown as T;\n\t}\n\n\tif (value && typeof value === 'object') {\n\t\tconst record = value as Record<string, unknown>;\n\n\t\tif (Array.isArray(record.nodes)) {\n\t\t\treturn record.nodes.map((entry) => unwrapRelationValue(entry)) as unknown as T;\n\t\t}\n\n\t\tif (Array.isArray(record.edges)) {\n\t\t\treturn record.edges.map((edge) => unwrapRelationValue(unwrapConnectionNode(edge))) as unknown as T;\n\t\t}\n\n\t\tif ('node' in record && record.node !== undefined) {\n\t\t\treturn unwrapRelationValue(record.node) as unknown as T;\n\t\t}\n\t}\n\n\treturn value;\n}\n\nexport function normalizeServerRow(row: Record<string, unknown>, relationFields: Set<string>): Record<string, unknown> {\n\tif (!row || typeof row !== 'object') {\n\t\treturn row;\n\t}\n\n\tconst next: Record<string, unknown> = { ...row };\n\trelationFields.forEach((fieldName) => {\n\t\tnext[fieldName] = unwrapRelationValue(next[fieldName]);\n\t});\n\treturn next;\n}\n\ninterface DraftSubmissionOptions {\n\tallowedColumns?: ReadonlySet<string>;\n\trelationInfoByKey?: Record<string, RelationInfo | undefined>;\n}\n\nexport interface DraftValidationFieldMeta {\n\tname?: string | null;\n\tisNotNull?: boolean | null;\n\thasDefault?: boolean | null;\n\ttype?: { gqlType?: string | null; isArray?: boolean | null } | null;\n}\n\nexport function validateDraftRowRequiredFields(\n\tvalues: Record<string, unknown>,\n\tfieldMetaByKey: Record<string, DraftValidationFieldMeta | undefined>,\n\toptions?: {\n\t\tallowedColumns?: ReadonlySet<string>;\n\t\trelationInfoByKey?: Record<string, RelationInfo | undefined>;\n\t},\n): Record<string, string> {\n\tconst errors: Record<string, string> = {};\n\tconst { allowedColumns, relationInfoByKey } = options ?? {};\n\tconst allowsAll = !allowedColumns || allowedColumns.size === 0;\n\n\tfor (const [key, meta] of Object.entries(fieldMetaByKey)) {\n\t\tif (!meta) continue;\n\t\tif (!meta.isNotNull) continue;\n\t\tif (meta.hasDefault) continue;\n\t\tif (key === 'id') continue;\n\t\tif (!allowsAll && !allowedColumns?.has(key)) continue;\n\n\t\tconst relInfo = relationInfoByKey?.[key];\n\t\tif (relInfo && relInfo.relationField === key) continue;\n\n\t\tconst value = values[key];\n\t\tif (value == null || value === '') {\n\t\t\terrors[key] = `${formatColumnHeader(key)} is required`;\n\t\t}\n\t}\n\n\treturn errors;\n}\n\nexport function prepareDraftSubmissionPayload(\n\tvalues: Record<string, unknown>,\n\toptions: DraftSubmissionOptions = {},\n): Record<string, unknown> {\n\tconst { allowedColumns, relationInfoByKey } = options;\n\tconst allowsAll = !allowedColumns || allowedColumns.size === 0;\n\n\t// Step 1: Filter nullish values using centralized utility\n\t// Draft submission is a CREATE operation, so null/undefined are filtered\n\tconst { id: _id, ...valuesWithoutId } = values;\n\tconst filtered = prepareCreateInput(valuesWithoutId);\n\n\t// Step 2: Apply relation-specific transformations\n\tconst payload: Record<string, unknown> = {};\n\n\tconst normalizeForeignKeyValue = (input: unknown): unknown => {\n\t\tif (input === undefined || input === null) return undefined;\n\n\t\tconst extractId = (candidate: unknown): string | number | null => {\n\t\t\tif (candidate === null || candidate === undefined) return null;\n\t\t\tif (typeof candidate === 'object') {\n\t\t\t\tconst record = candidate as Record<string, unknown>;\n\t\t\t\tconst id = record.id;\n\t\t\t\tif (typeof id === 'string' || typeof id === 'number') {\n\t\t\t\t\treturn id;\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (typeof candidate === 'string' || typeof candidate === 'number') {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input\n\t\t\t\t.map((entry) => extractId(entry))\n\t\t\t\t.filter((entry): entry is string | number => entry !== undefined && entry !== null);\n\t\t}\n\n\t\treturn extractId(input);\n\t};\n\n\tfor (const [key, value] of Object.entries(filtered)) {\n\t\tconst isAllowed = allowsAll || allowedColumns?.has(key);\n\t\tif (!isAllowed) continue;\n\n\t\tconst relInfo = relationInfoByKey?.[key];\n\n\t\tif (relInfo?.relationField === key) {\n\t\t\t// Skip relation display fields; rely on the corresponding foreign key entry\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (relInfo?.foreignKeyField === key) {\n\t\t\tconst normalized = normalizeForeignKeyValue(value);\n\t\t\tif (normalized === undefined) continue;\n\t\t\tpayload[key] = normalized;\n\t\t\tcontinue;\n\t\t}\n\n\t\tpayload[key] = value;\n\t}\n\n\treturn payload;\n}\n\nexport function prepareDraftRelationValue(\n\trawValue: unknown,\n\trelationInfo: RelationInfo,\n): {\n\trelationData: unknown;\n\tforeignKeyUpdates?: Record<string, unknown>;\n\trelationReferences?: unknown;\n} {\n\tlet value = rawValue;\n\n\tif (typeof value === 'string') {\n\t\tconst trimmed = value.trim();\n\t\tif (!trimmed) {\n\t\t\tvalue = null;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tvalue = JSON.parse(trimmed);\n\t\t\t} catch {\n\t\t\t\tvalue = trimmed;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst isListRelation = relationInfo.kind === 'hasMany' || relationInfo.kind === 'manyToMany';\n\n\tif (isListRelation) {\n\t\tconst entries = Array.isArray(value) ? value : value == null ? [] : [value];\n\t\tconst normalized = entries\n\t\t\t.map(normalizeRelationEntry)\n\t\t\t.filter((entry): entry is RelationNormalization => entry !== null);\n\n\t\tconst relationData = normalized.map((entry) => entry.value);\n\t\tconst relationReferences = normalized.map((entry) => entry.reference ?? null);\n\n\t\tconst fkField = relationInfo.foreignKeyField;\n\t\tconst foreignKeyUpdates = fkField\n\t\t\t? {\n\t\t\t\t\t[fkField]: normalized.map((entry) => (entry.reference === undefined ? null : entry.reference)),\n\t\t\t\t}\n\t\t\t: undefined;\n\n\t\treturn {\n\t\t\trelationData,\n\t\t\tforeignKeyUpdates,\n\t\t\trelationReferences,\n\t\t};\n\t}\n\n\tconst normalizedEntry = normalizeRelationEntry(Array.isArray(value) ? (value[0] ?? null) : value);\n\n\tconst relationData = normalizedEntry?.value ?? null;\n\tconst relationReference = normalizedEntry?.reference ?? null;\n\n\tconst fkField = relationInfo.foreignKeyField;\n\tconst foreignKeyUpdates = fkField\n\t\t? {\n\t\t\t\t[fkField]: normalizedEntry?.reference ?? null,\n\t\t\t}\n\t\t: undefined;\n\n\treturn {\n\t\trelationData,\n\t\tforeignKeyUpdates,\n\t\trelationReferences: relationReference,\n\t};\n}\n\ntype RelationNormalization = {\n\tvalue: unknown;\n\treference: string | number | null | undefined;\n};\n\nfunction normalizeRelationEntry(entry: unknown): RelationNormalization | null {\n\tif (entry === null || entry === undefined || entry === '') {\n\t\treturn null;\n\t}\n\n\tif (Array.isArray(entry)) {\n\t\treturn normalizeRelationEntry(entry[0]);\n\t}\n\n\tif (typeof entry === 'object') {\n\t\tconst record = entry as Record<string, unknown>;\n\t\tconst id = record.id;\n\t\treturn {\n\t\t\tvalue: record,\n\t\t\treference: typeof id === 'string' || typeof id === 'number' ? (id as string | number) : null,\n\t\t};\n\t}\n\n\tif (typeof entry === 'string' || typeof entry === 'number') {\n\t\treturn {\n\t\t\tvalue: entry,\n\t\t\treference: entry,\n\t\t};\n\t}\n\n\treturn null;\n}\n\n// Infer cell type from data content when location/metadata is not available\nexport function inferCellTypeFromData(data: string): string | undefined {\n\tif (!data || typeof data !== 'string') return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(data);\n\n\t\t// Check for geometry data patterns (wrapped format with geojson property)\n\t\tif (parsed && typeof parsed === 'object' && parsed.geojson) {\n\t\t\t// This is the wrapped geometry format: {\"geojson\": {...}, \"srid\": ..., \"x\": ..., \"y\": ...}\n\t\t\t// But sometimes it might only have the geojson property\n\t\t\tif (parsed.geojson.type === 'Point') {\n\t\t\t\treturn 'geometry-point';\n\t\t\t} else if (parsed.geojson.type === 'GeometryCollection') {\n\t\t\t\treturn 'geometry-collection';\n\t\t\t} else {\n\t\t\t\treturn 'geometry';\n\t\t\t}\n\t\t}\n\n\t\t// Check for raw GeoJSON (direct GeoJSON object)\n\t\tif (parsed && typeof parsed === 'object' && parsed.type && parsed.coordinates) {\n\t\t\tconst validGeoJSONTypes = [\n\t\t\t\t'Point',\n\t\t\t\t'LineString',\n\t\t\t\t'Polygon',\n\t\t\t\t'MultiPoint',\n\t\t\t\t'MultiLineString',\n\t\t\t\t'MultiPolygon',\n\t\t\t\t'GeometryCollection',\n\t\t\t];\n\t\t\tif (validGeoJSONTypes.includes(parsed.type)) {\n\t\t\t\tif (parsed.type === 'Point') {\n\t\t\t\t\treturn 'geometry-point';\n\t\t\t\t} else if (parsed.type === 'GeometryCollection') {\n\t\t\t\t\treturn 'geometry-collection';\n\t\t\t\t} else {\n\t\t\t\t\treturn 'geometry';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check for array data\n\t\tif (Array.isArray(parsed)) {\n\t\t\treturn 'array';\n\t\t}\n\n\t\t// Check for interval data (objects with days/hours/minutes/seconds properties)\n\t\tif (\n\t\t\tparsed &&\n\t\t\ttypeof parsed === 'object' &&\n\t\t\t(parsed.days !== undefined ||\n\t\t\t\tparsed.hours !== undefined ||\n\t\t\t\tparsed.minutes !== undefined ||\n\t\t\t\tparsed.seconds !== undefined)\n\t\t) {\n\t\t\treturn 'interval';\n\t\t}\n\n\t\t// Check for image data (objects with url/src/href/path properties)\n\t\tif (parsed && typeof parsed === 'object' && (parsed.url || parsed.src || parsed.href || parsed.path)) {\n\t\t\treturn 'image';\n\t\t}\n\n\t\t// Check for date strings (ISO format)\n\t\tif (typeof parsed === 'string' && /^\\d{4}-\\d{2}-\\d{2}/.test(parsed)) {\n\t\t\tif (parsed.includes('T')) {\n\t\t\t\treturn 'datetime';\n\t\t\t} else {\n\t\t\t\treturn 'date';\n\t\t\t}\n\t\t}\n\n\t\t// Generic JSON object\n\t\treturn 'json';\n\t} catch {\n\t\t// Not valid JSON, could be other data types\n\n\t\t// Check for date strings\n\t\tif (/^\\d{4}-\\d{2}-\\d{2}/.test(data)) {\n\t\t\tif (data.includes('T')) {\n\t\t\t\treturn 'datetime';\n\t\t\t} else {\n\t\t\t\treturn 'date';\n\t\t\t}\n\t\t}\n\n\t\t// Check for time strings\n\t\tif (/^\\d{2}:\\d{2}/.test(data)) {\n\t\t\treturn 'time';\n\t\t}\n\n\t\treturn undefined;\n\t}\n}\n\n// Utility functions for array previews\nexport function formatArrayPreview(arr: any[]): string {\n\tconst max = 3;\n\tconst items = arr.slice(0, max).map((v) => (typeof v === 'object' ? compactJsonPreview(v, 20) : String(v)));\n\tconst more = arr.length > max ? ` +${arr.length - max}` : '';\n\treturn items.join(', ') + more;\n}\n\n\n// Row operations\nexport async function handleRowAppend(\n\tcreateFunction: (data: any) => Promise<any>,\n): Promise<'top' | 'bottom' | number | undefined> {\n\tconst { createdRow } = await createFunction({});\n\tif (createdRow) {\n\t\treturn 'bottom';\n\t}\n\treturn undefined;\n}\n\n// Type-safe header click handler for sorting\n// Only allows sorting on columns in the sortableColumns set (excludes relation columns)\nexport function createHeaderClickHandler(\n\tcolumnKeys: string[],\n\ttoggleSorting: (colId: string) => void,\n\tsortableColumns?: Set<string>,\n) {\n\treturn (colIndex: number) => {\n\t\tconst colId = columnKeys[colIndex];\n\t\tif (!colId) return;\n\n\t\t// If sortableColumns is provided, only allow sorting on those columns\n\t\tif (sortableColumns && !sortableColumns.has(colId)) {\n\t\t\treturn;\n\t\t}\n\n\t\ttoggleSorting(colId);\n\t};\n}\n\n// Type-safe column resize handler\nexport function createColumnResizeHandler(resizeColumn: (id: string, width: number) => void) {\n\treturn (column: { id?: string }, newSize: number) => {\n\t\tif (column.id) {\n\t\t\tresizeColumn(column.id, newSize);\n\t\t}\n\t};\n}\n","/**\n * Light-weight relation metadata cache with straightforward error handling\n */\nimport { useCallback, useMemo } from 'react';\nimport { useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport { pluralize } from 'inflekt';\nimport { cleanTable, pgFieldToCamelCase, type CleanTable } from '@constructive-io/data';\nimport { useSheetsMeta } from './use-sheets-meta';\nimport { useSheetsContext, type SheetsScopeKey } from '../context/sheets-context';\nimport { sheetsQueryKeys } from './query-keys';\nimport { getJunctionTableNames, isJunctionTablePure } from '../utils/relation-utils';\nimport { sheetsLogger } from '../utils/sheets-logger';\n\n/**\n * Simple cache keys for relations\n */\nexport const RELATION_CACHE_KEYS = {\n\ttableRelations: (scope: SheetsScopeKey, tableName: string) => sheetsQueryKeys.relations(scope, tableName),\n} as const;\n\n/**\n * Cache timing tuned for relation metadata\n */\nexport const RELATION_CACHE_CONFIG = {\n\tstaleTime: 5 * 60 * 1000, // 5 minutes - reasonable for relation metadata\n\tgcTime: 30 * 60 * 1000, // 30 minutes - keep in memory longer\n\tretry: 3, // Retry failed requests\n\tretryDelay: (attemptIndex: number) => Math.min(1000 * 2 ** attemptIndex, 5000),\n} as const;\n\nexport type RelationMetadataSource = 'relation' | 'foreignKey';\n\nexport interface RelationMetadata {\n\ttableName: string;\n\tfieldName: string;\n\trelationKind: 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';\n\ttargetTable: string;\n\tisOptional: boolean;\n\tforeignKeyFields: string[];\n\t/** Headline relation field name when this metadata originates from a foreign key */\n\trelationFieldName?: string | null;\n\t/** Primary foreign key field associated with the relation */\n\tforeignKeyField?: string;\n\t/** Indicates whether the metadata entry is for the relation field or the FK column */\n\tsourceField: RelationMetadataSource;\n\tjunctionTable?: string;\n\tdisplayName?: string;\n}\n\n/**\n * Simple error state tracking\n */\nexport interface RelationCacheState {\n\tisLoading: boolean;\n\tisError: boolean;\n\terror: Error | null;\n\thasData: boolean;\n\trelationCount: number;\n}\n\nexport interface RelationMetadataSet {\n\trelationFields: RelationMetadata[];\n\tforeignKeyFields: RelationMetadata[];\n}\n\n/**\n * Cache and expose relation metadata for a table\n */\nexport function useRelationMetadataCache(tableName?: string) {\n\tconst queryClient = useQueryClient();\n\tconst { scopeKey } = useSheetsContext();\n\tconst { data: metaData, isError: metaError, error: metaErrorDetails } = useSheetsMeta();\n\n\t// Get table relations with improved error handling\n\tconst {\n\t\tdata: tableRelations,\n\t\tisLoading,\n\t\tisError,\n\t\terror,\n\t} = useQuery({\n\t\tqueryKey: RELATION_CACHE_KEYS.tableRelations(scopeKey, tableName || ''),\n\t\tqueryFn: async (): Promise<CleanTable | null> => {\n\t\t\tif (!metaData?._meta?.tables || !tableName) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst metaTable = metaData._meta.tables.find((t) => t?.name === tableName);\n\t\t\tif (!metaTable) {\n\t\t\t\t// Don't throw error for missing table - just return null\n\t\t\t\tsheetsLogger().debug?.(`Table \"${tableName}\" not found in metadata`);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn cleanTable(metaTable);\n\t\t},\n\t\t...RELATION_CACHE_CONFIG,\n\t\trefetchOnMount: true, // Respect staleTime and refresh stale relation metadata on mount\n\t\tenabled: Boolean(metaData && tableName),\n\t});\n\n\t// Extract relation metadata with error handling\n\tconst { relationFields, foreignKeyFields } = useMemo((): RelationMetadataSet => {\n\t\tif (!tableRelations?.relations || isError) {\n\t\t\treturn { relationFields: [], foreignKeyFields: [] };\n\t\t}\n\n\t\tconst relationFieldEntries: RelationMetadata[] = [];\n\t\tconst foreignKeyEntries: RelationMetadata[] = [];\n\t\tconst relations = tableRelations.relations;\n\n\t\ttry {\n\t\t\t// Process belongsTo relations\n\t\t\trelations.belongsTo.forEach((rel) => {\n\t\t\t\tif (!rel) return;\n\t\t\t\tconst foreignKeys = rel.keys.map((k) => k.name);\n\t\t\t\tconst primaryForeignKey = foreignKeys[0];\n\t\t\t\tif (rel.fieldName) {\n\t\t\t\t\trelationFieldEntries.push({\n\t\t\t\t\t\ttableName: tableName || '',\n\t\t\t\t\t\tfieldName: rel.fieldName,\n\t\t\t\t\t\trelationKind: 'belongsTo',\n\t\t\t\t\t\ttargetTable: rel.referencesTable,\n\t\t\t\t\t\tisOptional: !rel.isUnique,\n\t\t\t\t\t\tforeignKeyFields: foreignKeys,\n\t\t\t\t\t\trelationFieldName: rel.fieldName,\n\t\t\t\t\t\tforeignKeyField: primaryForeignKey,\n\t\t\t\t\t\tsourceField: 'relation',\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tforeignKeys.forEach((fk) => {\n\t\t\t\t\tif (!fk) return;\n\t\t\t\t\tforeignKeyEntries.push({\n\t\t\t\t\t\ttableName: tableName || '',\n\t\t\t\t\t\tfieldName: fk,\n\t\t\t\t\t\trelationKind: 'belongsTo',\n\t\t\t\t\t\ttargetTable: rel.referencesTable,\n\t\t\t\t\t\tisOptional: !rel.isUnique,\n\t\t\t\t\t\tforeignKeyFields: foreignKeys,\n\t\t\t\t\t\trelationFieldName: rel.fieldName ?? null,\n\t\t\t\t\t\tforeignKeyField: fk,\n\t\t\t\t\t\tsourceField: 'foreignKey',\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tconst rawMetaTables = (metaData?._meta?.tables ?? []).filter(\n\t\t\t\t(t): t is NonNullable<typeof t> => t != null,\n\t\t\t);\n\n\t\t\t// Resolve FK field in the related table using foreignKeyConstraints from _meta\n\t\t\tconst findFk = (relatedTableName: string): string | undefined => {\n\t\t\t\tconst rawRelated = rawMetaTables.find((t) => t?.name === relatedTableName);\n\t\t\t\tif (!rawRelated) return undefined;\n\t\t\t\t// v5 nested: constraints.foreignKey[]\n\t\t\t\tconst v5Fks = Array.isArray(rawRelated.constraints) ? [] : rawRelated.constraints?.foreignKey;\n\t\t\t\t// v4 flat: foreignKeyConstraints[]\n\t\t\t\tconst fks = v5Fks ?? rawRelated.foreignKeyConstraints ?? [];\n\t\t\t\tfor (const fk of fks) {\n\t\t\t\t\tif (!fk) continue;\n\t\t\t\t\tconst refName = fk.refTable?.name;\n\t\t\t\t\tif (refName && refName.toLowerCase() === (tableName || '').toLowerCase()) {\n\t\t\t\t\t\tconst fieldName = fk.fields?.[0]?.name;\n\t\t\t\t\t\tif (fieldName) return pgFieldToCamelCase(fieldName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t};\n\n\t\t\t// Process hasOne relations\n\t\t\trelations.hasOne.forEach((rel) => {\n\t\t\t\tif (rel.fieldName) {\n\t\t\t\t\trelationFieldEntries.push({\n\t\t\t\t\t\ttableName: tableName || '',\n\t\t\t\t\t\tfieldName: rel.fieldName,\n\t\t\t\t\t\trelationKind: 'hasOne',\n\t\t\t\t\t\ttargetTable: rel.referencedByTable,\n\t\t\t\t\t\tisOptional: true,\n\t\t\t\t\t\tforeignKeyFields: rel.keys.map((k) => k.name),\n\t\t\t\t\t\trelationFieldName: rel.fieldName,\n\t\t\t\t\t\tforeignKeyField: findFk(rel.referencedByTable),\n\t\t\t\t\t\tsourceField: 'relation',\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tconst junctionTableNames = getJunctionTableNames(relations, rawMetaTables);\n\n\t\t\t// Process hasMany relations (skip those pointing to junction tables)\n\t\t\trelations.hasMany.forEach((rel) => {\n\t\t\t\tif (!rel.fieldName) return;\n\t\t\t\t// Skip hasMany relations pointing to junction tables (M:N covers these)\n\t\t\t\tif (junctionTableNames.has(rel.referencedByTable)) return;\n\t\t\t\trelationFieldEntries.push({\n\t\t\t\t\ttableName: tableName || '',\n\t\t\t\t\tfieldName: rel.fieldName,\n\t\t\t\t\trelationKind: 'hasMany',\n\t\t\t\t\ttargetTable: rel.referencedByTable,\n\t\t\t\t\tisOptional: true,\n\t\t\t\t\tforeignKeyFields: rel.keys.map((k) => k.name),\n\t\t\t\t\trelationFieldName: rel.fieldName,\n\t\t\t\t\tforeignKeyField: findFk(rel.referencedByTable),\n\t\t\t\t\tsourceField: 'relation',\n\t\t\t\t});\n\t\t\t});\n\n\t\t\t// Process manyToMany relations (already deduped by rightTable in cleanTable())\n\t\t\t// Skip non-pure junction tables — they have required fields beyond the two FK columns\n\t\t\trelations.manyToMany.forEach((rel) => {\n\t\t\t\tif (rel.fieldName) {\n\t\t\t\t\tconst leftFk = rel.junctionLeftKeyFields?.[0];\n\t\t\t\t\tconst rightFk = rel.junctionRightKeyFields?.[0];\n\t\t\t\t\tif (rel.junctionTable && !isJunctionTablePure(rel.junctionTable, leftFk, rightFk, rawMetaTables)) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\trelationFieldEntries.push({\n\t\t\t\t\t\ttableName: tableName || '',\n\t\t\t\t\t\tfieldName: rel.fieldName,\n\t\t\t\t\t\trelationKind: 'manyToMany',\n\t\t\t\t\t\ttargetTable: rel.rightTable,\n\t\t\t\t\t\tisOptional: true,\n\t\t\t\t\t\tforeignKeyFields: [],\n\t\t\t\t\t\trelationFieldName: rel.fieldName,\n\t\t\t\t\t\tforeignKeyField: undefined,\n\t\t\t\t\t\tsourceField: 'relation',\n\t\t\t\t\t\tjunctionTable: rel.junctionTable,\n\t\t\t\t\t\tdisplayName: pluralize(rel.rightTable),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (processError) {\n\t\t\tsheetsLogger().warn('Error processing relation metadata:', processError);\n\t\t}\n\n\t\treturn { relationFields: relationFieldEntries, foreignKeyFields: foreignKeyEntries };\n\t}, [tableRelations, tableName, isError, metaData]);\n\n\tconst relationMetadata = useMemo(() => relationFields.concat(foreignKeyFields), [relationFields, foreignKeyFields]);\n\n\tconst relationMap = useMemo(() => {\n\t\tconst map = new Map<string, RelationMetadata>();\n\t\trelationFields.forEach((rel) => {\n\t\t\tmap.set(rel.fieldName, rel);\n\t\t});\n\t\tforeignKeyFields.forEach((rel) => {\n\t\t\tmap.set(rel.fieldName, rel);\n\t\t});\n\t\treturn map;\n\t}, [relationFields, foreignKeyFields]);\n\n\t// Simple cache invalidation\n\tconst invalidateRelationCache = useCallback(async () => {\n\t\tif (tableName) {\n\t\t\tawait queryClient.invalidateQueries({\n\t\t\t\tqueryKey: RELATION_CACHE_KEYS.tableRelations(scopeKey, tableName),\n\t\t\t});\n\t\t}\n\t}, [queryClient, scopeKey, tableName]);\n\n\t// Get relation info for a specific field\n\tconst getRelationInfo = useCallback(\n\t\t(fieldName: string): RelationMetadata | null => {\n\t\t\treturn relationMap.get(fieldName) || null;\n\t\t},\n\t\t[relationMap],\n\t);\n\n\t// Check if field is a relation\n\tconst isRelationField = useCallback(\n\t\t(fieldName: string): boolean => {\n\t\t\treturn relationMap.has(fieldName);\n\t\t},\n\t\t[relationMap],\n\t);\n\n\t// Get relation kind for backward compatibility\n\tconst getRelationKind = useCallback(\n\t\t(fieldName: string): 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany' | null => {\n\t\t\tconst relation = relationMap.get(fieldName);\n\t\t\treturn relation?.relationKind || null;\n\t\t},\n\t\t[relationMap],\n\t);\n\n\t// Simple cache state\n\tconst cacheState: RelationCacheState = useMemo(\n\t\t() => ({\n\t\t\tisLoading: isLoading || (!metaData && !metaError),\n\t\t\tisError: isError || metaError,\n\t\t\terror: error || metaErrorDetails || null,\n\t\t\thasData: Boolean(tableRelations && relationMetadata.length > 0),\n\t\t\trelationCount: relationMetadata.length,\n\t\t}),\n\t\t[isLoading, metaData, metaError, isError, error, metaErrorDetails, tableRelations, relationMetadata.length],\n\t);\n\n\treturn {\n\t\t// Data\n\t\trelationMetadata,\n\t\trelationFields,\n\t\tforeignKeyFields,\n\t\trelationMap,\n\t\ttableRelations,\n\n\t\t// State\n\t\tcacheState,\n\t\tisLoading,\n\t\tisError,\n\t\terror,\n\n\t\t// Utilities\n\t\tgetRelationInfo,\n\t\tisRelationField,\n\t\tgetRelationKind,\n\t\tinvalidateRelationCache,\n\t};\n}\n","// Typed row + draft-metadata model for the sheets grid.\n//\n// Draft metadata is attached to a row under a non-enumerable Symbol key so it\n// never collides with real column data and stays invisible to JSON.stringify\n// and key enumeration. NOTE: exactly like the previous non-enumerable string\n// markers (`__isDraft` etc.), this metadata does NOT survive an object spread\n// (`{ ...row }`) — callers must thread the row reference through rather than a\n// shallow copy.\nimport type { DraftRow } from '../store/draft-rows-slice';\n\n/** A grid row: arbitrary column values keyed by field name, plus an optional id. */\nexport type SheetsRow = Record<string, unknown> & { id?: string | number };\n\n/** Client-side draft metadata carried by a not-yet-persisted row. */\nexport interface DraftMeta {\n\treadonly isDraft: true;\n\treadonly draftRowId: string;\n\treadonly status: DraftRow['status'];\n\treadonly errors: Record<string, string> | null;\n}\n\nconst DRAFT_META: unique symbol = Symbol('sheets.draftMeta');\n\n/** A row that may carry draft metadata under the (non-enumerable) Symbol key. */\nexport type RowWithDraft<TRow extends SheetsRow = SheetsRow> = TRow & { readonly [DRAFT_META]?: DraftMeta };\n\n/** Attach draft metadata to a row in place (non-enumerable). Returns the same row, typed. */\nexport function attachDraftMeta<TRow extends SheetsRow>(row: TRow, meta: DraftMeta): RowWithDraft<TRow> {\n\tObject.defineProperty(row, DRAFT_META, { value: meta, enumerable: false, configurable: true });\n\treturn row as RowWithDraft<TRow>;\n}\n\n/** Read draft metadata, or undefined for a normal (server) row. */\nexport function getDraftMeta(row: SheetsRow | null | undefined): DraftMeta | undefined {\n\treturn row ? (row as RowWithDraft)[DRAFT_META] : undefined;\n}\n\n/** True when the row is a client-side draft. */\nexport function isDraftRow(row: SheetsRow | null | undefined): boolean {\n\treturn getDraftMeta(row)?.isDraft === true;\n}\n","// Per-instance cell-type registry.\n//\n// This is a thin OVERRIDE LAYER over the built-in native rendering engine:\n// consumer definitions (from `SheetsConfig.plugins` and `<Sheets cellTypes>`)\n// win by `typeKey` and by `match()`, and anything they don't define falls back\n// to the built-in `toSheetsCell`. The built-in engine is injected so this module\n// stays free of a cell-types -> grid import cycle. The registry is created once\n// per <SheetsProvider> (same lifetime as the store), so it is SSR- and\n// multi-tenant-safe — no module singleton.\nimport type {\n\tCellTypeDefinition,\n\tCellTypeMatchInput,\n\tSheetsCellRenderContext,\n} from './define-cell-type';\nimport type { SheetsCell } from '../cell-model/sheets-cell';\nimport type { CellProps } from '../cell-model/cell-props';\nimport type { EditorProps } from '../grid-dom/editors/editor-props';\n\n/** The built-in engine the registry falls back to (injected to avoid a cycle). */\nexport interface CellTypeBuiltins {\n\ttoSheetsCell: (value: unknown, ctx: SheetsCellRenderContext) => SheetsCell;\n}\n\nexport interface CellTypeRegistry {\n\t/** Detection: consumer `match()` chain first (later defs win), else the built-in resolver. */\n\tresolveTypeKey(meta: CellTypeMatchInput, builtinFallback: () => string): string;\n\t/** Native display: consumer `def.toSheetsCell` for this typeKey, else the built-in renderer. */\n\ttoSheetsCell(typeKey: string, value: unknown, ctx: SheetsCellRenderContext): SheetsCell;\n\t/** The registered definition for a typeKey, if any (consumer defs only). */\n\tget(typeKey: string): CellTypeDefinition<any> | undefined;\n\t/** The native cell COMPONENT override for a typeKey, if any (consumer `def.cell`). */\n\tgetCellComponent(typeKey: string): React.ComponentType<CellProps> | undefined;\n\t/** The native EDITOR override for a typeKey, if any (consumer `def.editorComponent`). */\n\tgetEditorComponent(typeKey: string): React.ComponentType<EditorProps> | undefined;\n}\n\n/**\n * Build a registry. `cellTypes` are consumer definitions in precedence order\n * (provider `plugins` first, then per-instance `cellTypes`); later entries win,\n * so an instance-level def overrides a provider-level one with the same typeKey.\n */\nexport function createCellTypeRegistry(cellTypes: CellTypeDefinition<any>[], builtins: CellTypeBuiltins): CellTypeRegistry {\n\t// Index by typeKey — last write wins (instance overrides provider).\n\tconst byKey = new Map<string, CellTypeDefinition<any>>();\n\tfor (const def of cellTypes) byKey.set(def.typeKey, def);\n\n\t// Match list in REVERSE precedence so later (instance) defs are tried first.\n\tconst matchers = [...cellTypes].reverse().filter((d) => d.match);\n\n\treturn {\n\t\tresolveTypeKey(meta, builtinFallback) {\n\t\t\tfor (const def of matchers) {\n\t\t\t\tif (def.match!(meta)) return def.typeKey;\n\t\t\t}\n\t\t\treturn builtinFallback();\n\t\t},\n\t\ttoSheetsCell(typeKey, value, ctx) {\n\t\t\tconst def = byKey.get(typeKey);\n\t\t\treturn def?.toSheetsCell ? def.toSheetsCell(value, ctx) : builtins.toSheetsCell(value, ctx);\n\t\t},\n\t\tget(typeKey) {\n\t\t\treturn byKey.get(typeKey);\n\t\t},\n\t\tgetCellComponent(typeKey) {\n\t\t\treturn byKey.get(typeKey)?.cell;\n\t\t},\n\t\tgetEditorComponent(typeKey) {\n\t\t\treturn byKey.get(typeKey)?.editorComponent;\n\t\t},\n\t};\n}\n","// Consumer-facing cell-component override slots. A thin sugar over the native\n// `cell` field of a CellTypeDefinition: a `CellSlots` map (keyed by cell typeKey)\n// compiles down to component-only CellTypeDefinitions that the registry resolves\n// via `getCellComponent`. Pure logic — no React render, no glide.\n\nimport type { CellTypeDefinition } from '../cell-types/define-cell-type';\nimport type { CellProps } from './cell-props';\nimport type { EditorProps } from '../grid-dom/editors/editor-props';\n\n/**\n * A single slot: either a bare cell component, or an object overriding the cell\n * view and/or the native editor for a typeKey. The object form lets a consumer\n * override JUST the editor (`{ editor: MyEditor }`) without touching the view.\n */\nexport type CellSlot =\n\t| React.ComponentType<CellProps>\n\t| { cell?: React.ComponentType<CellProps>; editor?: React.ComponentType<EditorProps> };\n\n/** Consumer cell-component / editor overrides keyed by cell typeKey. */\nexport type CellSlots = Record<string, CellSlot>;\n\n/**\n * Compile a {@link CellSlots} map into {@link CellTypeDefinition}s. The function\n * form yields `{ typeKey, cell }` (view-only); the object form yields\n * `{ typeKey, cell?, editorComponent? }`. Entries that resolve to neither a cell\n * nor an editor (e.g. `{ json: {} }`) are skipped. Returns `[]` for empty/undefined.\n */\nexport function compileSlots(slots: CellSlots | undefined): CellTypeDefinition[] {\n\tif (!slots) return [];\n\tconst defs: CellTypeDefinition[] = [];\n\tfor (const [typeKey, slot] of Object.entries(slots)) {\n\t\tif (typeof slot === 'function') {\n\t\t\tdefs.push({ typeKey, cell: slot });\n\t\t\tcontinue;\n\t\t}\n\t\tconst { cell, editor } = slot;\n\t\tif (!cell && !editor) continue;\n\t\tdefs.push({ typeKey, cell, editorComponent: editor });\n\t}\n\treturn defs;\n}\n","export const DRAFT_ACTION_COLUMN_KEY = '__draft_action__';\n","import { useCallback } from 'react';\n\nimport { DRAFT_ACTION_COLUMN_KEY } from '../sheets.constants';\nimport { prepareDraftRelationValue } from '../sheets.utils';\nimport type { DraftRowsState } from './use-draft-rows';\nimport { getDraftMeta } from '../row-model';\nimport type { SheetsRowIdentifier } from '../../row-identity';\n\n/** Result from the useCellEditing hook */\nexport interface CellEditingResult {\n\t/** Type of edit: 'draft' for local draft row, 'server' for server mutation, 'noop' for no action */\n\ttype: 'draft' | 'server' | 'noop';\n\t/** The updated row data from the server (only for 'server' type) */\n\tupdatedRow?: Record<string, unknown> | null;\n\t/** The field that was patched (only for 'server' type) */\n\tpatchField?: string;\n\t/** The value that was sent (only for 'server' type) */\n\tpatchValue?: unknown;\n}\n\ninterface UseCellEditingParams {\n\tcombinedRows: any[];\n\tfieldMetaMap: Map<string, any>;\n\trelationInfoByField: Map<string, any>;\n\tupdateDraftCell: DraftRowsState['updateDraftCell'];\n\ttableKey: string;\n\tupdate: (id: SheetsRowIdentifier, data: Record<string, unknown>) => Promise<{ updatedRow?: Record<string, unknown> | null }>;\n\tgetRowIdentifier?: (row: Readonly<Record<string, unknown>>) => SheetsRowIdentifier | null;\n\treadOnlyFields?: ReadonlySet<string>;\n\tcanUpdate?: boolean;\n\tonCellEdit?: (id: SheetsRowIdentifier, field: string, value: unknown) => void;\n\t/**\n\t * Optimistic server-row cache patch. Applied to the local (infinite) cache BEFORE\n\t * the `update` round-trip so the cell flips instantly; returns a revert thunk that\n\t * the hook calls if `update` rejects. Omitted (e.g. paginated mode / unit tests) =>\n\t * no pre-await patch and the consumer reconciles after the await as before.\n\t */\n\tapplyOptimisticPatch?: (rowIndex: number, patch: Record<string, unknown>) => (() => void) | void;\n}\n\nfunction legacyRowIdentifier(row: Readonly<Record<string, unknown>>): SheetsRowIdentifier | null {\n\treturn typeof row.id === 'string' || typeof row.id === 'number' ? row.id : null;\n}\n\n/**\n * Normalize a relation value for a server PATCH: a JSON string is parsed, an array\n * is mapped to its ids (single id for belongsTo/hasOne, list otherwise), a single\n * object to its id. Mirrors the relation branch the canvas `handleCellEdit` ran,\n * but on the RAW native value instead of an extracted glide cell.\n */\nexport function normalizeRelationPatchValue(rawValue: unknown, relationKind: string | undefined): unknown {\n\tlet value = rawValue;\n\n\tif (typeof value === 'string') {\n\t\tconst trimmed = value.trim();\n\t\tif (trimmed === '') {\n\t\t\tvalue = null;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tvalue = JSON.parse(trimmed);\n\t\t\t} catch {\n\t\t\t\tvalue = trimmed;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (Array.isArray(value)) {\n\t\tconst mapped = value\n\t\t\t.map((entry) => (entry && typeof entry === 'object' ? ((entry as any).id ?? entry) : entry))\n\t\t\t.filter((entry) => entry !== undefined && entry !== null);\n\t\tvalue = relationKind === 'belongsTo' || relationKind === 'hasOne' ? (mapped[0] ?? null) : mapped;\n\t} else if (value && typeof value === 'object') {\n\t\tvalue = (value as any).id ?? null;\n\t}\n\n\tif (value === '') value = null;\n\treturn value;\n}\n\n/** The resolved server PATCH for one cell write, or a reason it is a no-op. */\nexport type ServerPatchResolution =\n\t| { kind: 'patch'; field: string; value: unknown }\n\t| { kind: 'noop' };\n\n/**\n * Derive the single-field server PATCH for a server-row cell write — the ONE place\n * that owns server-row coercion + readonly guards (UUID id / relation-not-inline /\n * undefined). Shared by `useCellEditing` (single cell) and the batched `commitCells`\n * (paste/fill/bulk) so neither forks the rules. PURE; never touches the cache or\n * network. `rowData` is the target row (skip callers must null-guard before calling).\n */\nexport function resolveServerPatch(\n\tcolKey: string,\n\trawValue: unknown,\n\tfieldMetaMap: Map<string, any>,\n\trelationInfoByField: Map<string, any>,\n\treadOnlyFields?: ReadonlySet<string>,\n): ServerPatchResolution {\n\tif (!colKey || colKey === DRAFT_ACTION_COLUMN_KEY) return { kind: 'noop' };\n\tif (readOnlyFields?.has(colKey)) return { kind: 'noop' };\n\n\t// Block edits to the UUID primary key id.\n\tconst metaField = fieldMetaMap.get(colKey);\n\tif (colKey === 'id' && metaField?.type?.gqlType === 'UUID') return { kind: 'noop' };\n\n\tconst relationInfo = relationInfoByField.get(colKey);\n\tlet value: unknown = rawValue;\n\n\tif (relationInfo) {\n\t\tconst patchFieldCandidate = relationInfo.foreignKeyField || colKey;\n\t\tconst canEditRelationInline = relationInfo.kind === 'belongsTo' && fieldMetaMap.has(patchFieldCandidate);\n\t\tif (!canEditRelationInline) return { kind: 'noop' };\n\t\tvalue = normalizeRelationPatchValue(rawValue, relationInfo.kind);\n\t}\n\n\tif (value === undefined) return { kind: 'noop' };\n\n\tconst field = relationInfo?.foreignKeyField || colKey;\n\treturn { kind: 'patch', field, value };\n}\n\nexport function useCellEditing({\n\tcombinedRows,\n\tfieldMetaMap,\n\trelationInfoByField,\n\tupdateDraftCell,\n\ttableKey,\n\tupdate,\n\tgetRowIdentifier = legacyRowIdentifier,\n\treadOnlyFields,\n\tcanUpdate = true,\n\tonCellEdit,\n\tapplyOptimisticPatch,\n}: UseCellEditingParams) {\n\treturn useCallback(\n\t\t// NATIVE signature: the DOM editors / inline-toggle pass a raw value that flows\n\t\t// straight through — no glide cell round-trip. This is what fixes the boolean\n\t\t// toggle: a raw `false` persists as `false`, never stringified to \"false\".\n\t\tasync (rowIndex: number, colKey: string, rawValue: unknown): Promise<CellEditingResult> => {\n\t\t\tconst rowData = combinedRows[rowIndex];\n\t\t\tif (!colKey || !rowData) return { type: 'noop' };\n\n\t\t\tif (colKey === DRAFT_ACTION_COLUMN_KEY) {\n\t\t\t\treturn { type: 'noop' };\n\t\t\t}\n\n\t\t\tconst draftMeta = getDraftMeta(rowData);\n\t\t\tif (draftMeta?.isDraft && colKey === 'id') {\n\t\t\t\treturn { type: 'noop' };\n\t\t\t}\n\n\t\t\tif (draftMeta?.isDraft) {\n\t\t\t\tconst draftRowId: string | undefined = draftMeta.draftRowId;\n\t\t\t\tif (!draftRowId) return { type: 'noop' };\n\n\t\t\t\tconst baseValue = rawValue;\n\t\t\t\tconst relationInfo = relationInfoByField.get(colKey);\n\n\t\t\t\tlet storedValue: unknown = baseValue;\n\t\t\t\tlet extraValues: Record<string, unknown> | undefined;\n\n\t\t\t\tif (relationInfo) {\n\t\t\t\t\tconst { relationData, foreignKeyUpdates, relationReferences } = prepareDraftRelationValue(\n\t\t\t\t\t\tbaseValue,\n\t\t\t\t\t\trelationInfo,\n\t\t\t\t\t);\n\t\t\t\t\tconst relationFieldKey = relationInfo.relationField;\n\t\t\t\t\tconst foreignKeyFieldKey = relationInfo.foreignKeyField;\n\t\t\t\t\tconst editingRelationField = relationFieldKey ? relationFieldKey === colKey : false;\n\t\t\t\t\tconst editingForeignKeyField = foreignKeyFieldKey ? foreignKeyFieldKey === colKey : false;\n\n\t\t\t\t\tconst processedRelationData = Array.isArray(relationData)\n\t\t\t\t\t\t? relationData.filter((entry) => entry !== undefined)\n\t\t\t\t\t\t: relationData;\n\n\t\t\t\t\tconst relationExtra = relationFieldKey\n\t\t\t\t\t\t? processedRelationData === undefined\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: processedRelationData === null\n\t\t\t\t\t\t\t\t? { [relationFieldKey]: null }\n\t\t\t\t\t\t\t\t: typeof processedRelationData === 'object'\n\t\t\t\t\t\t\t\t\t? { [relationFieldKey]: processedRelationData }\n\t\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tconst processedReferenceValue = Array.isArray(relationReferences)\n\t\t\t\t\t\t? relationReferences.filter((entry) => entry !== undefined)\n\t\t\t\t\t\t: relationReferences;\n\n\t\t\t\t\tconst foreignKeyExtra = foreignKeyFieldKey\n\t\t\t\t\t\t? processedReferenceValue !== undefined\n\t\t\t\t\t\t\t? { [foreignKeyFieldKey]: processedReferenceValue }\n\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tif (editingRelationField) {\n\t\t\t\t\t\tstoredValue = processedRelationData;\n\t\t\t\t\t\textraValues = {\n\t\t\t\t\t\t\t...(foreignKeyUpdates ?? {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t} else if (editingForeignKeyField) {\n\t\t\t\t\t\tstoredValue = processedReferenceValue ?? processedRelationData;\n\t\t\t\t\t\textraValues = {\n\t\t\t\t\t\t\t...(foreignKeyUpdates ?? {}),\n\t\t\t\t\t\t\t...(relationExtra ?? {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstoredValue = processedRelationData;\n\t\t\t\t\t\textraValues = {\n\t\t\t\t\t\t\t...(foreignKeyUpdates ?? {}),\n\t\t\t\t\t\t\t...(relationExtra ?? {}),\n\t\t\t\t\t\t\t...(foreignKeyExtra ?? {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tupdateDraftCell({\n\t\t\t\t\ttableKey,\n\t\t\t\t\tdraftRowId,\n\t\t\t\t\tcolumnKey: colKey,\n\t\t\t\t\tvalue: storedValue,\n\t\t\t\t\textraValues: extraValues && Object.keys(extraValues).length > 0 ? extraValues : undefined,\n\t\t\t\t});\n\t\t\t\treturn { type: 'draft' };\n\t\t\t}\n\n\t\t\t// Server row edit — derive the PATCH via the shared resolver (the single owner\n\t\t\t// of server-row coercion + readonly guards, also used by batched `commitCells`).\n\t\t\tif (!canUpdate) return { type: 'noop' };\n\t\t\tconst resolution = resolveServerPatch(colKey, rawValue, fieldMetaMap, relationInfoByField, readOnlyFields);\n\t\t\tif (resolution.kind === 'noop') return { type: 'noop' };\n\t\t\tconst { field: patchField, value } = resolution;\n\t\t\tconst rowIdentifier = getRowIdentifier(rowData);\n\t\t\tif (rowIdentifier === null) return { type: 'noop' };\n\n\t\t\t// Optimistic: patch the local cache with the new value BEFORE awaiting the\n\t\t\t// server so the cell updates instantly. `applyOptimisticPatch` returns a revert\n\t\t\t// thunk (snapshot of the prior value) which we replay only if `update` rejects.\n\t\t\tconst revertOptimisticPatch = applyOptimisticPatch?.(rowIndex, { [patchField]: value });\n\n\t\t\tlet result: { updatedRow?: Record<string, unknown> | null };\n\t\t\ttry {\n\t\t\t\tresult = await update(rowIdentifier, { [patchField]: value });\n\t\t\t} catch (error) {\n\t\t\t\tif (typeof revertOptimisticPatch === 'function') revertOptimisticPatch();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tonCellEdit?.(rowIdentifier, patchField, value);\n\n\t\t\treturn {\n\t\t\t\ttype: 'server',\n\t\t\t\tupdatedRow: result?.updatedRow ?? null,\n\t\t\t\tpatchField,\n\t\t\t\tpatchValue: value,\n\t\t\t};\n\t\t},\n\t\t[combinedRows, fieldMetaMap, relationInfoByField, tableKey, update, getRowIdentifier, readOnlyFields, canUpdate, onCellEdit, updateDraftCell, applyOptimisticPatch],\n\t);\n}\n","/**\n * useBatchCommit — the batched cell-value commit primitive behind paste / fill /\n * bulk-edit AND (routed through it) the single-cell edit, so EVERY server-row value\n * write is one undoable, coalesced operation.\n *\n * It owns NO coercion/readonly rules of its own: server-row writes go through the\n * shared {@link resolveServerPatch} (the same resolver `useCellEditing` uses), so the\n * UUID-id guard, relation normalization and readonly skips stay in ONE place.\n *\n * Coalescing contract (load-bearing for a 1000-cell paste):\n * • prior values are captured from `combinedRows` BEFORE any optimistic patch, so\n * undo restores the EXACT pre-edit value.\n * • ONE optimistic cache patch is applied per affected ROW (merged col patches),\n * not per cell — N rows -> N patches, never N×cols.\n * • ONE server `update(rowId, {merged})` is issued per row.\n * • when recording, the HistoryEntry's `undo`/`redo` re-enter `commitCells` with\n * `{ record: false }` so replays never double-record.\n *\n * Draft-row writes are NOT batched here — they route to the existing per-cell draft\n * path (`editCell`) and are excluded from history (draft undo is out of P3 scope).\n */\nimport { useCallback, useRef } from 'react';\n\nimport { resolveServerPatch } from './use-cell-editing';\nimport type { CellEditingResult } from './use-cell-editing';\nimport { getDraftMeta, type SheetsRow } from '../row-model';\nimport type { SheetsRowIdentifier } from '../../row-identity';\n\n/** A single cell write request. */\nexport interface CellWrite {\n\trowIndex: number;\n\tcolKey: string;\n\tvalue: unknown;\n}\n\nexport interface CommitCellsOptions {\n\t/** When false, the commit is NOT pushed to history (used by undo/redo replays). Default true. */\n\trecord?: boolean;\n}\n\nexport interface CommitCellsResult {\n\t/** Number of server cells actually written (post readonly/null/no-op filtering). */\n\tapplied: number;\n}\n\ninterface UseBatchCommitParams {\n\tcombinedRows: SheetsRow[];\n\tfieldMetaMap: Map<string, any>;\n\trelationInfoByField: Map<string, any>;\n\tupdate: (id: SheetsRowIdentifier, data: Record<string, unknown>) => Promise<{ updatedRow?: Record<string, unknown> | null }>;\n\tgetRowIdentifier?: (row: Readonly<Record<string, unknown>>) => SheetsRowIdentifier | null;\n\treadOnlyFields?: ReadonlySet<string>;\n\tcanUpdate?: boolean;\n\t/** Single-write optimistic cache patch (infinite mode) — returns a revert thunk. */\n\tapplyOptimisticPatch?: (rowIndex: number, patch: Record<string, unknown>) => (() => void) | void;\n\t/** Re-sync a server row over the optimistic patch after the mutation resolves (infinite mode). */\n\tresyncRow?: (rowIndex: number, updatedRow: Record<string, unknown>) => void;\n\t/** Existing per-cell editor (draft routing + single-cell server coercion). */\n\teditCell: (rowIndex: number, colKey: string, rawValue: unknown) => Promise<CellEditingResult>;\n\t/** Observational per-server-write callback (mirrors useCellEditing's onCellEdit). */\n\tonCellEdit?: (id: SheetsRowIdentifier, field: string, value: unknown) => void;\n\t/** Push a reversible step to the history. */\n\trecord: (entry: { label: string; undo: () => Promise<void> | void; redo: () => Promise<void> | void }) => void;\n}\n\n/** A resolved server write: its row, the patch field, the next + prior values. */\ninterface ResolvedWrite {\n\trowIndex: number;\n\trowId: SheetsRowIdentifier;\n\tfield: string;\n\tvalue: unknown;\n\tprior: unknown;\n}\n\nfunction legacyRowIdentifier(row: Readonly<Record<string, unknown>>): SheetsRowIdentifier | null {\n\treturn typeof row.id === 'string' || typeof row.id === 'number' ? row.id : null;\n}\n\nexport function useBatchCommit({\n\tcombinedRows,\n\tfieldMetaMap,\n\trelationInfoByField,\n\tupdate,\n\tgetRowIdentifier = legacyRowIdentifier,\n\treadOnlyFields,\n\tcanUpdate = true,\n\tapplyOptimisticPatch,\n\tresyncRow,\n\teditCell,\n\tonCellEdit,\n\trecord,\n}: UseBatchCommitParams) {\n\t// Holds the latest commitCells so a recorded HistoryEntry (captured at record-time)\n\t// always re-enters the CURRENT closure — avoids a stale-row snapshot. Per-hook\n\t// instance, so multiple grids never share a commit fn.\n\tconst commitRef = useRef<((writes: CellWrite[], opts?: CommitCellsOptions) => Promise<CommitCellsResult>) | null>(null);\n\n\tconst commitCells = useCallback(\n\t\tasync (writes: CellWrite[], opts?: CommitCellsOptions): Promise<CommitCellsResult> => {\n\t\t\tif (!writes.length) return { applied: 0 };\n\n\t\t\tconst resolved: ResolvedWrite[] = [];\n\t\t\tconst draftWrites: CellWrite[] = [];\n\n\t\t\tfor (const w of writes) {\n\t\t\t\tconst rowData = combinedRows[w.rowIndex] as Record<string, unknown> | null | undefined;\n\t\t\t\t// Null-guard unfetched proxy rows — skip writes whose row is not loaded.\n\t\t\t\tif (!rowData) continue;\n\n\t\t\t\t// Draft rows keep their existing per-cell path; excluded from coalescing + history.\n\t\t\t\tif (getDraftMeta(rowData)) {\n\t\t\t\t\tdraftWrites.push(w);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (!canUpdate) continue;\n\t\t\t\tconst resolution = resolveServerPatch(w.colKey, w.value, fieldMetaMap, relationInfoByField, readOnlyFields);\n\t\t\t\tif (resolution.kind === 'noop') continue;\n\t\t\t\tconst rowIdentifier = getRowIdentifier(rowData);\n\t\t\t\tif (rowIdentifier === null) continue;\n\n\t\t\t\tresolved.push({\n\t\t\t\t\trowIndex: w.rowIndex,\n\t\t\t\t\trowId: rowIdentifier,\n\t\t\t\t\tfield: resolution.field,\n\t\t\t\t\tvalue: resolution.value,\n\t\t\t\t\t// Capture the PRIOR value of the patched field BEFORE any optimistic patch.\n\t\t\t\t\tprior: rowData[resolution.field],\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Fire draft writes through the existing path (not batched, not recorded).\n\t\t\tfor (const dw of draftWrites) {\n\t\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\t\tawait editCell(dw.rowIndex, dw.colKey, dw.value);\n\t\t\t}\n\n\t\t\tif (!resolved.length) return { applied: 0 };\n\n\t\t\t// Group by row: one merged optimistic patch + one merged server PATCH per row.\n\t\t\tconst byRow = new Map<number, ResolvedWrite[]>();\n\t\t\tfor (const r of resolved) {\n\t\t\t\tconst list = byRow.get(r.rowIndex);\n\t\t\t\tif (list) list.push(r);\n\t\t\t\telse byRow.set(r.rowIndex, [r]);\n\t\t\t}\n\n\t\t\t// Apply ONE optimistic patch per row (merged) and collect revert thunks.\n\t\t\tconst reverts: Array<() => void> = [];\n\t\t\tfor (const [rowIndex, group] of byRow) {\n\t\t\t\tconst patch: Record<string, unknown> = {};\n\t\t\t\tfor (const r of group) patch[r.field] = r.value;\n\t\t\t\tconst revert = applyOptimisticPatch?.(rowIndex, patch);\n\t\t\t\tif (revert) reverts.push(revert);\n\t\t\t}\n\n\t\t\t// Issue ONE server mutation per row; revert ALL optimistic patches on first failure.\n\t\t\ttry {\n\t\t\t\tfor (const [rowIndex, group] of byRow) {\n\t\t\t\t\tconst patch: Record<string, unknown> = {};\n\t\t\t\t\tfor (const r of group) patch[r.field] = r.value;\n\t\t\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\t\t\tconst result = await update(group[0].rowId, patch);\n\t\t\t\t\tif (result?.updatedRow) resyncRow?.(rowIndex, result.updatedRow);\n\t\t\t\t\tfor (const r of group) onCellEdit?.(r.rowId, r.field, r.value);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tfor (const revert of reverts) revert();\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\t// Record the inverse (prior values) so undo restores the exact pre-edit state.\n\t\t\tif (opts?.record !== false) {\n\t\t\t\tconst priorWrites: CellWrite[] = resolved.map((r) => ({\n\t\t\t\t\trowIndex: r.rowIndex,\n\t\t\t\t\tcolKey: r.field,\n\t\t\t\t\tvalue: r.prior,\n\t\t\t\t}));\n\t\t\t\tconst redoWrites: CellWrite[] = resolved.map((r) => ({\n\t\t\t\t\trowIndex: r.rowIndex,\n\t\t\t\t\tcolKey: r.field,\n\t\t\t\t\tvalue: r.value,\n\t\t\t\t}));\n\t\t\t\t// Capture the live commit fn via the closure below (commitRef).\n\t\t\t\trecord({\n\t\t\t\t\tlabel: resolved.length > 1 ? `Edit ${resolved.length} cells` : 'Edit cell',\n\t\t\t\t\tundo: () => void commitRef.current?.(priorWrites, { record: false }),\n\t\t\t\t\tredo: () => void commitRef.current?.(redoWrites, { record: false }),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn { applied: resolved.length };\n\t\t},\n\t\t[combinedRows, fieldMetaMap, relationInfoByField, update, getRowIdentifier, readOnlyFields, canUpdate, applyOptimisticPatch, resyncRow, editCell, onCellEdit, record],\n\t);\n\n\tcommitRef.current = commitCells;\n\treturn commitCells;\n}\n","/**\n * useUndoRedo — a tiny two-stack history for grid mutations.\n *\n * Each {@link HistoryEntry} carries its own inverse: `undo` reverts the change,\n * `redo` re-applies it (both may be async — a server mutation). `record` pushes a\n * new entry onto the undo stack and CLEARS the redo stack (a fresh edit forks the\n * timeline). `undo`/`redo` move the top entry across the two stacks, running the\n * matching thunk.\n *\n * The stacks live in refs so the handler identities (`undo`/`redo`/`record`) stay\n * STABLE across renders — keydown wiring binds them once. `canUndo`/`canRedo` are\n * reactive (state) so chrome can disable buttons. Depth is capped to bound memory.\n */\nimport { useCallback, useRef, useState } from 'react';\n\n/** One reversible step: a label plus its undo / redo thunks. */\nexport interface HistoryEntry {\n\tlabel: string;\n\tundo: () => Promise<void> | void;\n\tredo: () => Promise<void> | void;\n}\n\nexport interface UseUndoRedoResult {\n\t/** Push a new entry; clears the redo stack. */\n\trecord: (entry: HistoryEntry) => void;\n\t/** Pop the top undo entry, run its `undo`, push it to the redo stack. No-op when empty. */\n\tundo: () => Promise<void>;\n\t/** Pop the top redo entry, run its `redo`, push it to the undo stack. No-op when empty. */\n\tredo: () => Promise<void>;\n\t/** True when the undo stack is non-empty. */\n\tcanUndo: boolean;\n\t/** True when the redo stack is non-empty. */\n\tcanRedo: boolean;\n\t/** Drop all history. */\n\tclear: () => void;\n}\n\nconst DEFAULT_MAX_DEPTH = 100;\n\nexport function useUndoRedo(maxDepth: number = DEFAULT_MAX_DEPTH): UseUndoRedoResult {\n\tconst undoStack = useRef<HistoryEntry[]>([]);\n\tconst redoStack = useRef<HistoryEntry[]>([]);\n\tconst [canUndo, setCanUndo] = useState(false);\n\tconst [canRedo, setCanRedo] = useState(false);\n\n\tconst sync = useCallback(() => {\n\t\tsetCanUndo(undoStack.current.length > 0);\n\t\tsetCanRedo(redoStack.current.length > 0);\n\t}, []);\n\n\tconst record = useCallback(\n\t\t(entry: HistoryEntry) => {\n\t\t\tundoStack.current.push(entry);\n\t\t\tif (undoStack.current.length > maxDepth) undoStack.current.shift();\n\t\t\tredoStack.current = [];\n\t\t\tsync();\n\t\t},\n\t\t[maxDepth, sync],\n\t);\n\n\tconst undo = useCallback(async () => {\n\t\tconst entry = undoStack.current.pop();\n\t\tif (!entry) return;\n\t\tredoStack.current.push(entry);\n\t\tsync();\n\t\tawait entry.undo();\n\t}, [sync]);\n\n\tconst redo = useCallback(async () => {\n\t\tconst entry = redoStack.current.pop();\n\t\tif (!entry) return;\n\t\tundoStack.current.push(entry);\n\t\tsync();\n\t\tawait entry.redo();\n\t}, [sync]);\n\n\tconst clear = useCallback(() => {\n\t\tundoStack.current = [];\n\t\tredoStack.current = [];\n\t\tsync();\n\t}, [sync]);\n\n\treturn { record, undo, redo, canUndo, canRedo, clear };\n}\n","import { useMemo } from 'react';\n\nimport { useSheetsStore } from '../../store/sheets-store';\nimport type { DraftRow, DraftRowsSlice } from '../../store/draft-rows-slice';\nimport { attachDraftMeta, isDraftRow } from '../row-model';\n\ninterface DraftRowsTableState {\n\torder: string[];\n\tmap: Record<string, DraftRow>;\n\ttemplate: Record<string, unknown>;\n\tmetaVersion: string;\n\tcolumnOrder: string[];\n}\n\ninterface UseDraftRowsParams {\n\ttableKey: string;\n\tserverRows: any[];\n\thasCompletedInitialLoad: boolean;\n}\n\nexport interface DraftRowsState {\n\tdraftRowsTable?: DraftRowsTableState;\n\tdraftRows: DraftRow[];\n\thasDraftRows: boolean;\n\tcombinedRows: any[];\n\tdraftRowIndices: number[];\n\tcreateDraftRow: DraftRowsSlice['createDraftRow'];\n\tupdateDraftCell: DraftRowsSlice['updateDraftCell'];\n\tremoveDraftRow: DraftRowsSlice['removeDraftRow'];\n\tsyncDraftRowsWithMeta: DraftRowsSlice['syncDraftRowsWithMeta'];\n\tsetDraftRowStatus: DraftRowsSlice['setDraftRowStatus'];\n}\n\nexport function useDraftRows({\n\ttableKey,\n\tserverRows,\n\thasCompletedInitialLoad,\n}: UseDraftRowsParams): DraftRowsState {\n\tconst draftRowsTable = useSheetsStore(\n\t\t(state) => state.draftRowsByTable[tableKey] as DraftRowsTableState | undefined,\n\t);\n\tconst createDraftRow = useSheetsStore((state) => state.createDraftRow);\n\tconst updateDraftCell = useSheetsStore((state) => state.updateDraftCell);\n\tconst removeDraftRow = useSheetsStore((state) => state.removeDraftRow);\n\tconst syncDraftRowsWithMeta = useSheetsStore((state) => state.syncDraftRowsWithMeta);\n\tconst setDraftRowStatus = useSheetsStore((state) => state.setDraftRowStatus);\n\n\tconst draftRows = useMemo(() => {\n\t\tif (!draftRowsTable) return [] as DraftRow[];\n\t\treturn draftRowsTable.order.map((id) => draftRowsTable.map[id]).filter((row): row is DraftRow => Boolean(row));\n\t}, [draftRowsTable]);\n\n\tconst mayShowDrafts = hasCompletedInitialLoad || serverRows.length > 0 || draftRows.length > 0;\n\n\tconst combinedRows = useMemo(() => {\n\t\tif (!draftRows.length || !mayShowDrafts) return serverRows as any[];\n\n\t\tconst draftDataRows = draftRows.map((draft) => {\n\t\t\tconst row = { ...draft.values } as Record<string, unknown>;\n\t\t\treturn attachDraftMeta(row, {\n\t\t\t\tisDraft: true,\n\t\t\t\tdraftRowId: draft.id,\n\t\t\t\tstatus: draft.status,\n\t\t\t\terrors: draft.errors,\n\t\t\t});\n\t\t});\n\n\t\treturn [...(serverRows as any[]), ...draftDataRows];\n\t}, [serverRows, draftRows, mayShowDrafts]);\n\n\tconst draftRowIndices = useMemo(() => {\n\t\tconst indices: number[] = [];\n\t\tcombinedRows.forEach((row, index) => {\n\t\t\tif (isDraftRow(row)) {\n\t\t\t\tindices.push(index);\n\t\t\t}\n\t\t});\n\t\treturn indices;\n\t}, [combinedRows]);\n\n\tconst hasDraftRows = draftRows.length > 0 && mayShowDrafts;\n\n\treturn {\n\t\tdraftRowsTable,\n\t\tdraftRows,\n\t\thasDraftRows,\n\t\tcombinedRows,\n\t\tdraftRowIndices,\n\t\tcreateDraftRow,\n\t\tupdateDraftCell,\n\t\tremoveDraftRow,\n\t\tsyncDraftRowsWithMeta,\n\t\tsetDraftRowStatus,\n\t};\n}\n","import { useCallback, useMemo, useState } from 'react';\n\nimport type { RelationInfo } from '../../store/relation-info-slice';\nimport type { DraftRow } from '../../store/draft-rows-slice';\nimport { SHEETS_CONCURRENCY } from '../../config/sheets-concurrency';\n\nimport { prepareDraftSubmissionPayload, validateDraftRowRequiredFields, type DraftValidationFieldMeta } from '../sheets.utils';\nimport type { DraftSubmitResult } from '../draft-types';\nimport type { DraftRowEntry } from './use-grid-selection';\nimport { sheetsLogger } from '../../utils/sheets-logger';\n\ninterface DraftRowsTableState {\n\torder: string[];\n\tmap: Record<string, DraftRow>;\n\ttemplate: Record<string, unknown>;\n\tmetaVersion: string;\n\tcolumnOrder: string[];\n}\n\ninterface OperationFeedbackCallbacks {\n\tonStart?: (type: 'submit', total: number) => string;\n\tonProgress?: (id: string, completed: number, failed: number) => void;\n\tonComplete?: (id: string, status: 'success' | 'partial' | 'error', message: string) => void;\n}\n\ninterface UseDraftSubmissionParams {\n\ttableKey: string;\n\tdraftRowsTable?: DraftRowsTableState;\n\tselectedDraftRowEntries: DraftRowEntry[];\n\thasDraftSelection: boolean;\n\tcreate: (data: Record<string, unknown>) => Promise<{ createdRow?: Record<string, unknown> | null }>;\n\tremoveDraftRow: (tableKey: string, draftRowId: string) => void;\n\tsetDraftRowStatus: (args: {\n\t\ttableKey: string;\n\t\tdraftRowId: string;\n\t\tstatus: DraftRow['status'];\n\t\terrors?: Record<string, string> | null;\n\t}) => void;\n\tclearSelection: () => void;\n\tallowedColumns?: ReadonlySet<string>;\n\trelationInfoByKey?: Record<string, RelationInfo | undefined>;\n\tfieldMetaByKey?: Record<string, DraftValidationFieldMeta | undefined>;\n\tonSubmittedSuccessfully?: (result: { success: number; failed: number }) => void;\n\t/** Feedback callbacks for inline status indicators */\n\tfeedback?: OperationFeedbackCallbacks;\n}\n\nexport function useDraftSubmission({\n\ttableKey,\n\tdraftRowsTable,\n\tselectedDraftRowEntries,\n\thasDraftSelection,\n\tcreate,\n\tremoveDraftRow,\n\tsetDraftRowStatus,\n\tclearSelection,\n\tallowedColumns,\n\trelationInfoByKey,\n\tfieldMetaByKey,\n\tonSubmittedSuccessfully,\n\tfeedback,\n}: UseDraftSubmissionParams) {\n\tconst [isSubmittingDrafts, setIsSubmittingDrafts] = useState(false);\n\n\tconst submitDraftEntries = useCallback(\n\t\tasync (entries: DraftRowEntry[], operationId?: string): Promise<{ success: number; failed: number }> => {\n\t\t\tif (!entries.length) {\n\t\t\t\treturn { success: 0, failed: 0 };\n\t\t\t}\n\n\t\t\tsetIsSubmittingDrafts(true);\n\n\t\t\tconst submissionResults = {\n\t\t\t\tsuccess: 0,\n\t\t\t\tfailed: 0,\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tlet nextEntryIndex = 0;\n\t\t\t\tconst workerCount = Math.min(SHEETS_CONCURRENCY.draftSubmit, entries.length);\n\n\t\t\t\tconst runSubmitWorker = async () => {\n\t\t\t\t\twhile (nextEntryIndex < entries.length) {\n\t\t\t\t\t\tconst currentIndex = nextEntryIndex;\n\t\t\t\t\t\tnextEntryIndex += 1;\n\t\t\t\t\t\tconst { draftRowId, draftRow } = entries[currentIndex];\n\n\t\t\t\t\t\t// Pre-validate required fields before sending to server\n\t\t\t\t\t\tif (fieldMetaByKey) {\n\t\t\t\t\t\t\tconst validationErrors = validateDraftRowRequiredFields(\n\t\t\t\t\t\t\t\tdraftRow.values,\n\t\t\t\t\t\t\t\tfieldMetaByKey,\n\t\t\t\t\t\t\t\t{ allowedColumns, relationInfoByKey },\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (Object.keys(validationErrors).length > 0) {\n\t\t\t\t\t\t\t\tsubmissionResults.failed += 1;\n\t\t\t\t\t\t\t\tsetDraftRowStatus({ tableKey, draftRowId, status: 'error', errors: validationErrors });\n\t\t\t\t\t\t\t\tif (operationId) {\n\t\t\t\t\t\t\t\t\tfeedback?.onProgress?.(operationId, submissionResults.success, submissionResults.failed);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsetDraftRowStatus({ tableKey, draftRowId, status: 'saving', errors: null });\n\t\t\t\t\t\tconst payload = prepareDraftSubmissionPayload(draftRow.values, {\n\t\t\t\t\t\t\tallowedColumns,\n\t\t\t\t\t\t\trelationInfoByKey,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait create(payload);\n\t\t\t\t\t\t\tremoveDraftRow(tableKey, draftRowId);\n\t\t\t\t\t\t\tsubmissionResults.success += 1;\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tsubmissionResults.failed += 1;\n\t\t\t\t\t\t\tconst message = error instanceof Error ? error.message : 'Failed to submit draft row';\n\t\t\t\t\t\t\tsheetsLogger().error('submitDraftRow failed', error);\n\t\t\t\t\t\t\tsetDraftRowStatus({ tableKey, draftRowId, status: 'error', errors: { submit: message } });\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (operationId) {\n\t\t\t\t\t\t\tfeedback?.onProgress?.(\n\t\t\t\t\t\t\t\toperationId,\n\t\t\t\t\t\t\t\tsubmissionResults.success,\n\t\t\t\t\t\t\t\tsubmissionResults.failed,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tawait Promise.all(Array.from({ length: workerCount }, () => runSubmitWorker()));\n\t\t\t} finally {\n\t\t\t\tsetIsSubmittingDrafts(false);\n\t\t\t}\n\n\t\t\tif (submissionResults.success > 0) {\n\t\t\t\tonSubmittedSuccessfully?.(submissionResults);\n\t\t\t}\n\n\t\t\treturn submissionResults;\n\t\t},\n\t\t[\n\t\t\tallowedColumns,\n\t\t\trelationInfoByKey,\n\t\t\tfieldMetaByKey,\n\t\t\tcreate,\n\t\t\tremoveDraftRow,\n\t\t\tsetDraftRowStatus,\n\t\t\ttableKey,\n\t\t\tfeedback,\n\t\t\tonSubmittedSuccessfully,\n\t\t],\n\t);\n\n\tconst handleSubmitDraftRows = useCallback(async () => {\n\t\tif (!draftRowsTable || !hasDraftSelection) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst total = selectedDraftRowEntries.length;\n\t\tconst operationId = feedback?.onStart?.('submit', total);\n\n\t\tconst submissionResults = await submitDraftEntries(selectedDraftRowEntries, operationId);\n\n\t\tif (operationId) {\n\t\t\tconst { success, failed } = submissionResults;\n\t\t\tif (failed === 0 && success > 0) {\n\t\t\t\tfeedback?.onComplete?.(\n\t\t\t\t\toperationId,\n\t\t\t\t\t'success',\n\t\t\t\t\t`Submitted ${success} ${success === 1 ? 'row' : 'rows'}`,\n\t\t\t\t);\n\t\t\t} else if (success > 0 && failed > 0) {\n\t\t\t\tfeedback?.onComplete?.(\n\t\t\t\t\toperationId,\n\t\t\t\t\t'partial',\n\t\t\t\t\t`Submitted ${success}, ${failed} failed`,\n\t\t\t\t);\n\t\t\t} else if (failed > 0) {\n\t\t\t\tfeedback?.onComplete?.(\n\t\t\t\t\toperationId,\n\t\t\t\t\t'error',\n\t\t\t\t\t`Failed to submit ${failed} ${failed === 1 ? 'row' : 'rows'}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif (submissionResults.success > 0) {\n\t\t\tclearSelection();\n\t\t}\n\t}, [draftRowsTable, hasDraftSelection, selectedDraftRowEntries, submitDraftEntries, clearSelection, feedback]);\n\n\tconst handleSubmitSingleDraftRow = useCallback(\n\t\tasync (draftRowId: string) => {\n\t\t\tif (!draftRowsTable) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst draftRow = draftRowsTable.map[draftRowId];\n\t\t\tif (!draftRow) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Single row submission - no operation feedback, rely on row status indicator\n\t\t\tawait submitDraftEntries([{ draftRowId, draftRow }]);\n\t\t},\n\t\t[draftRowsTable, submitDraftEntries],\n\t);\n\n\tconst submitDraftLabel = useMemo(() => {\n\t\tif (!hasDraftSelection) {\n\t\t\treturn 'Submit draft rows';\n\t\t}\n\t\tconst count = selectedDraftRowEntries.length;\n\t\treturn `Submit ${count} draft ${count === 1 ? 'row' : 'rows'}`;\n\t}, [hasDraftSelection, selectedDraftRowEntries.length]);\n\n\tconst submitDraftButtonDisabled = isSubmittingDrafts || !hasDraftSelection;\n\n\t/**\n\t * Submit a single draft row for editor workflows (e.g., ImageEditor upload).\n\t * Returns the created row with real database ID for subsequent operations.\n\t *\n\t * NOTE: This does NOT call onSingleRowSubmitted - the editor is responsible\n\t * for triggering data refresh after any follow-up operations (like upload)\n\t * are complete. This prevents premature cache invalidation.\n\t */\n\tconst submitDraftRowForEditor = useCallback(\n\t\tasync (draftRowId: string): Promise<DraftSubmitResult> => {\n\t\t\tif (!draftRowsTable) {\n\t\t\t\treturn { createdRow: null };\n\t\t\t}\n\n\t\t\tconst draftRow = draftRowsTable.map[draftRowId];\n\t\t\tif (!draftRow) {\n\t\t\t\treturn { createdRow: null };\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tsetDraftRowStatus({ tableKey, draftRowId, status: 'saving', errors: null });\n\n\t\t\t\tconst payload = prepareDraftSubmissionPayload(draftRow.values, {\n\t\t\t\t\tallowedColumns,\n\t\t\t\t\trelationInfoByKey,\n\t\t\t\t});\n\n\t\t\t\tconst result = await create(payload);\n\t\t\t\tconst createdRow = result?.createdRow ?? null;\n\n\t\t\t\tif (createdRow) {\n\t\t\t\t\tremoveDraftRow(tableKey, draftRowId);\n\t\t\t\t\t// NOTE: Don't call onSingleRowSubmitted here - let the editor\n\t\t\t\t\t// trigger refresh after follow-up operations complete\n\t\t\t\t}\n\n\t\t\t\treturn { createdRow };\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : 'Failed to create row';\n\t\t\t\tsetDraftRowStatus({ tableKey, draftRowId, status: 'error', errors: { submit: message } });\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\t[draftRowsTable, setDraftRowStatus, tableKey, allowedColumns, relationInfoByKey, create, removeDraftRow],\n\t);\n\n\treturn {\n\t\tisSubmittingDrafts,\n\t\tsubmitDraftButtonDisabled,\n\t\tsubmitDraftLabel,\n\t\thandleSubmitDraftRows,\n\t\thandleSubmitSingleDraftRow,\n\t\tsubmitDraftRowForEditor,\n\t};\n}\n","/**\n * Centralized concurrency limits for Sheets async workflows.\n * Keep these values conservative to avoid overloading API endpoints.\n */\nexport const SHEETS_CONCURRENCY = {\n\tdraftSubmit: 3,\n\tbulkDelete: 4,\n} as const;\n","// The DOM content resolver — the native analogue of the canvas `useGridContent`\n// (grid/hooks/use-grid-content.ts). It MIRRORS that hook's routing steps 1:1 but\n// produces a neutral {@link SheetsCell} (+ the resolved view component) instead of\n// a glide `GridCell`, so the DOM grid never touches the canvas render path.\n//\n// It deliberately does NOT own the `ensureRelationInfo` effect: the canvas\n// `useGridContent` already runs that effect for the same table, so this hook takes\n// `relationInfoByField` + `meta` as INPUTS to avoid a duplicate store write/effect.\n// Draft VISUAL styling (faded/error theme overrides) is intentionally deferred to\n// Phase 7 — here we only blank the leaked draft-id text and tag `styleHint.draft`\n// so Phase 7 can style from a neutral flag (no glide theme imports).\n\nimport { useCallback, useMemo } from 'react';\n\nimport type { CellTypeRegistry } from '../cell-types/cell-type-registry';\nimport type { FieldMetadata } from '../cell-types/cell-type-resolver';\nimport type { CellCreationMetadata } from '../grid/grid-cell-types';\nimport type { CellProps } from '../cell-model/cell-props';\nimport type { SheetsCell } from '../cell-model/sheets-cell';\nimport type { SheetsRow } from '../grid/row-model';\nimport type { RelationInfo } from '../store/relation-info-slice';\nimport type { MetaQuery } from '@constructive-io/data';\nimport { buildRelationFieldNameSet, resolveGridCellRoute } from '../grid/cell-routing';\nimport { getDraftMeta } from '../grid/row-model';\nimport { unwrapRelationValue } from '../grid/sheets.utils';\nimport { MEDIA_TYPES } from '../cell-types/cell-type-groups';\nimport type { SheetsRowIdentifier } from '../row-identity';\n\ninterface RelationOptions {\n\trelationChipLimit?: number;\n\trelationLabelMaxLength?: number;\n}\n\n/** Resolved DOM cell payload: the neutral cell plus its (optional) view component. */\nexport interface SheetsCellResolution {\n\tcell: SheetsCell;\n\tcomponent?: React.ComponentType<CellProps>;\n\tcolKey: string;\n\t/**\n\t * The resolved cell-type key (post detection-override) — the SINGLE source of\n\t * truth the host feeds to `resolveEditIntent` to route activation. Always set;\n\t * `'text'` for the loading/empty fallthrough cells that carry no type. (Mirror\n\t * of the `meta.cellType` the cell itself now self-describes.)\n\t */\n\ttypeKey: string;\n\t/** Field metadata for the column — fed to a native overlay editor's EditorProps.fieldMeta. */\n\tfieldMeta?: FieldMetadata;\n\t/** Relation info for the column (when relational) — fed to a native overlay editor's EditorProps.relationInfo. */\n\trelationInfo?: RelationInfo;\n}\n\nexport interface UseSheetsContentArgs {\n\tdata: SheetsRow[];\n\tcolumnKeys: string[];\n\tfieldMetaMap: ReadonlyMap<string, FieldMetadata>;\n\tregistry: CellTypeRegistry;\n\ttableName?: string;\n\toptions?: RelationOptions;\n\t/** Relation info per field — owned by the canvas `useGridContent` ensureRelationInfo effect. */\n\trelationInfoByField: ReadonlyMap<string, RelationInfo>;\n\t/** Schema meta (same value the canvas path reads via useSheetsMeta). */\n\tmeta: MetaQuery | undefined;\n\t/** Disable every persisted-row editor when the table cannot expose update mutations. */\n\tserverRowsReadOnly?: boolean;\n\t/** Primary-key fields are immutable after insertion because they define row identity. */\n\tserverReadOnlyFields?: ReadonlySet<string>;\n\t/** Resolve the GraphQL mutation identity; self-committing editors require a legacy scalar id. */\n\tgetRowIdentifier?: (row: Readonly<Record<string, unknown>>) => SheetsRowIdentifier | null;\n\t/** Relation/upload editors still use scalar record APIs and must fail closed otherwise. */\n\tsupportsScalarSelfCommit?: boolean;\n}\n\nfunction isDraftId(value: unknown): boolean {\n\treturn typeof value === 'string' && value.startsWith('draft:');\n}\n\n/**\n * DISPLAY-LEVEL suppression of an internal draft key leaking as visible cell text —\n * the {@link SheetsCell} mirror of the canvas `suppressDraftIdText`. When the row is\n * a draft AND the value being rendered is the draft key (the `id` column starting\n * with `draft:`, or any value equal to the draft id), blank the cell's display/data\n * text while preserving kind and structural flags. Narrow by design: nothing else.\n */\nexport function suppressDraftIdText(\n\tcell: SheetsCell,\n\targs: { isDraftRow: boolean; colKey: string; rawValue: unknown; draftId: string | undefined },\n): SheetsCell {\n\tconst { isDraftRow, colKey, rawValue, draftId } = args;\n\tif (!isDraftRow) return cell;\n\n\tconst isIdColumnDraftKey = colKey === 'id' && isDraftId(rawValue);\n\tconst valueIsDraftId = typeof draftId === 'string' && rawValue === draftId;\n\tif (!isIdColumnDraftKey && !valueIsDraftId) return cell;\n\n\treturn { ...cell, data: typeof cell.data === 'string' ? '' : cell.data, displayData: '' };\n}\n\n/**\n * Tag the cell as a draft row so the host can apply faded/error styling from a flag —\n * the DOM mirror of the canvas applyDraftDisabledStyle/applyDraftErrorStyle split.\n * `error` is set when draftMeta.errors carries a field-level error for THIS colKey\n * (canvas: applyDraftErrorStyle); `draft` always (canvas: faded/disabled visuals).\n */\nfunction tagDraftStyle(cell: SheetsCell, hasError: boolean): SheetsCell {\n\treturn { ...cell, styleHint: { ...cell.styleHint, draft: true, error: hasError } };\n}\n\n/**\n * Build the DOM content resolver. Returns `getSheetsCell(rowIndex, colKey)` which\n * mirrors the canvas `getCellContent` routing exactly (draftMeta → fieldMeta →\n * relationInfo → route → relation value unwrap → matchInput → resolveTypeKey →\n * metadata → registry.toSheetsCell), then suppresses any leaked draft-id text and\n * tags draft rows. The view component is resolved alongside via `getCellComponent`.\n */\nexport function useSheetsContent(args: UseSheetsContentArgs) {\n\tconst {\n\t\tdata,\n\t\tcolumnKeys,\n\t\tfieldMetaMap,\n\t\tregistry,\n\t\ttableName,\n\t\toptions,\n\t\trelationInfoByField,\n\t\tmeta,\n\t\tserverRowsReadOnly = false,\n\t\tserverReadOnlyFields,\n\t\tgetRowIdentifier,\n\t\tsupportsScalarSelfCommit = true,\n\t} = args;\n\n\tconst relationFieldNamesFromMeta = useMemo(() => buildRelationFieldNameSet(meta, tableName), [meta, tableName]);\n\n\t// PER-RESOLVER RESULT CACHE. The cell host calls `getSheetsCell` for every visible\n\t// cell on every re-render, almost always re-deriving an identical resolution. This\n\t// Map memoizes the last resolution per `rowIndex|colKey`, keyed on the cell's raw\n\t// VALUE: a repeat call whose value is reference-equal to the cached one returns the\n\t// cached resolution and skips the full pipeline (route → relation unwrap →\n\t// resolveTypeKey → toSheetsCell, which allocates ≥3 objects).\n\t//\n\t// SAFETY: the deps below are IDENTICAL to the `getSheetsCell` useCallback's deps, so\n\t// the cache is thrown away exactly when the resolver would change identity. Every\n\t// input that can change a cell's resolution flows through one of these deps — most\n\t// notably `data`: draft status/errors rebuild `combinedRows` (new array + new row\n\t// objects, see useDraftRows), and any server-data / optimistic change recreates the\n\t// rows array too. So `styleHint.draft/error` (derived from the row's DraftMeta) and\n\t// the relation-unwrap fields (read off the same row object) cannot change without a\n\t// new `data` reference resetting this cache — making the per-value compare sound:\n\t// within one resolver identity the row objects are immutable, so a value that is\n\t// reference-equal guarantees an identical resolution.\n\tconst cache = useMemo(\n\t\t() => new Map<string, { value: unknown; resolution: SheetsCellResolution }>(),\n\t\t[data, columnKeys, fieldMetaMap, registry, relationFieldNamesFromMeta, relationInfoByField, options, serverRowsReadOnly, serverReadOnlyFields, getRowIdentifier, supportsScalarSelfCommit],\n\t);\n\n\tconst getSheetsCell = useCallback(\n\t\t(rowIndex: number, colKey: string): SheetsCellResolution => {\n\t\t\t// UNLOADED INFINITE ROW → loading skeleton. In infinite-scroll mode `data` is the\n\t\t\t// null-backed proxy from useSheets: a server index whose page is still in flight reads\n\t\t\t// back as `null` (drafts are real objects, never null). Resolve those slots to a neutral\n\t\t\t// `kind: 'loading'` cell with NO component, so the host's kind→view map paints\n\t\t\t// LoadingCellView (the canvas analogue is glide's loadingCell). Without this the row\n\t\t\t// coerces to `{}` below and every cell renders as blank text instead of a skeleton.\n\t\t\tconst rawRow = (data as any[])[rowIndex];\n\t\t\tconst cacheKey = rowIndex + '|' + colKey;\n\t\t\tif (colKey && rawRow == null) {\n\t\t\t\t// Cache the loading slot keyed on its (null) value: when the page loads, the row\n\t\t\t\t// flips null → object, the value identity changes, and this naturally MISSES and\n\t\t\t\t// recomputes (a new `data` proxy also resets the whole cache, so this is belt-and-braces).\n\t\t\t\tconst hit = cache.get(cacheKey);\n\t\t\t\tif (hit && hit.value === rawRow) return hit.resolution;\n\t\t\t\tconst resolution: SheetsCellResolution = {\n\t\t\t\t\tcell: { kind: 'loading', data: null, displayData: '', readonly: true },\n\t\t\t\t\tcolKey,\n\t\t\t\t\ttypeKey: 'text',\n\t\t\t\t};\n\t\t\t\tcache.set(cacheKey, { value: rawRow, resolution });\n\t\t\t\treturn resolution;\n\t\t\t}\n\t\t\tconst rowData = rawRow ?? {};\n\t\t\tif (!colKey) {\n\t\t\t\treturn { cell: { kind: 'text', data: '', displayData: '', readonly: false }, colKey, typeKey: 'text' };\n\t\t\t}\n\n\t\t\tconst rawValue = rowData?.[colKey];\n\n\t\t\t// RESULT-CACHE FAST PATH: the resolution is fully determined by the row object's\n\t\t\t// fields (see the cache declaration), and the row object is immutable within this\n\t\t\t// resolver identity, so a reference-equal `rawValue` means an identical resolution.\n\t\t\tconst hit = cache.get(cacheKey);\n\t\t\tif (hit && hit.value === rawValue) return hit.resolution;\n\t\t\tconst draftMeta = getDraftMeta(rowData);\n\t\t\tconst isDraftRow = Boolean(draftMeta?.isDraft);\n\t\t\tconst isDraftIdCell = isDraftRow && colKey === 'id';\n\n\t\t\tconst baseFieldMeta = fieldMetaMap.get(colKey);\n\t\t\tconst relationInfo = relationInfoByField.get(colKey);\n\t\t\tconst isRelationFallback = relationFieldNamesFromMeta.has(colKey);\n\t\t\tconst isRelation = Boolean(relationInfo) || isRelationFallback;\n\t\t\tconst foreignKeyField = relationInfo?.foreignKeyField;\n\t\t\tconst canEditRelationInline =\n\t\t\t\trelationInfo?.kind === 'belongsTo' &&\n\t\t\t\ttypeof foreignKeyField === 'string' &&\n\t\t\t\tfieldMetaMap.has(foreignKeyField);\n\n\t\t\tconst fieldMeta: FieldMetadata | undefined = baseFieldMeta;\n\t\t\tconst route = resolveGridCellRoute({\n\t\t\t\tcolKey,\n\t\t\t\tfieldMeta,\n\t\t\t\trelationInfo,\n\t\t\t\tisRelationFallback,\n\t\t\t\tisDraftIdCell,\n\t\t\t\thasForeignKeyField: canEditRelationInline,\n\t\t\t});\n\t\t\tconst tableForcedReadOnly = !isDraftRow && (\n\t\t\t\tserverRowsReadOnly || Boolean(serverReadOnlyFields?.has(colKey))\n\t\t\t);\n\n\t\t\tlet valueForCell = rawValue;\n\n\t\t\tif (relationInfo && relationInfo.relationField && relationInfo.relationField !== colKey) {\n\t\t\t\tconst relatedValue = (rowData as any)?.[relationInfo.relationField];\n\t\t\t\tif (relatedValue !== undefined && relatedValue !== null) {\n\t\t\t\t\tvalueForCell = relatedValue;\n\t\t\t\t} else if (typeof rawValue === 'string' && rawValue && !isDraftId(rawValue)) {\n\t\t\t\t\tvalueForCell = { id: rawValue };\n\t\t\t\t}\n\t\t\t} else if (relationInfo && valueForCell == null) {\n\t\t\t\tconst fkField = relationInfo.foreignKeyField;\n\t\t\t\tconst fkValue = fkField ? (rowData as any)?.[fkField] : undefined;\n\t\t\t\tif (fkValue && !isDraftId(fkValue)) {\n\t\t\t\t\tvalueForCell = { id: fkValue };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isRelation) {\n\t\t\t\tvalueForCell = unwrapRelationValue(valueForCell);\n\t\t\t}\n\n\t\t\t// Consumer detection override: a registered def's match() may override the\n\t\t\t// resolved typeKey. With no consumer cell types this returns route.cellType.\n\t\t\tconst matchInput = {\n\t\t\t\tgqlType: fieldMeta?.type?.gqlType ?? '',\n\t\t\t\tisArray: Boolean(fieldMeta?.type?.isArray),\n\t\t\t\tpgAlias: fieldMeta?.type?.pgAlias ?? null,\n\t\t\t\tpgType: fieldMeta?.type?.pgType ?? null,\n\t\t\t\tsubtype: fieldMeta?.type?.subtype ?? null,\n\t\t\t\tfieldName: colKey,\n\t\t\t};\n\t\t\tconst cellType = registry.resolveTypeKey(matchInput, () => route.cellType);\n\t\t\tconst rowIdentifier = !isDraftRow ? getRowIdentifier?.(rowData) : null;\n\t\t\tconst selfCommittingEditor = isRelation || MEDIA_TYPES.has(cellType);\n\t\t\tconst lacksScalarEditorIdentity =\n\t\t\t\tselfCommittingEditor &&\n\t\t\t\t(!supportsScalarSelfCommit || (\n\t\t\t\t\trowIdentifier != null && typeof rowIdentifier === 'object'\n\t\t\t\t));\n\t\t\tconst forcedReadOnly = tableForcedReadOnly || lacksScalarEditorIdentity;\n\n\t\t\tconst metadata: CellCreationMetadata = {\n\t\t\t\tcellType,\n\t\t\t\tfieldName: colKey,\n\t\t\t\tfieldMeta,\n\t\t\t\trelationInfo,\n\t\t\t\trelationOptions: relationInfo ? options || {} : undefined,\n\t\t\t\tcanEdit: route.canEdit && !forcedReadOnly,\n\t\t\t\tisReadonly: route.isReadonly || forcedReadOnly,\n\t\t\t\tactivationBehavior: route.activationBehavior,\n\t\t\t};\n\n\t\t\tconst resolvedCell = registry.toSheetsCell(cellType, valueForCell, { metadata });\n\t\t\tconst cell = forcedReadOnly && !resolvedCell.readonly\n\t\t\t\t? { ...resolvedCell, readonly: true }\n\t\t\t\t: resolvedCell;\n\n\t\t\t// Blank any internal draft key that would otherwise render as visible text\n\t\t\t// (kind unchanged); narrow to the draft id, nothing else.\n\t\t\tconst displaySafe = suppressDraftIdText(cell, {\n\t\t\t\tisDraftRow,\n\t\t\t\tcolKey,\n\t\t\t\trawValue,\n\t\t\t\tdraftId: draftMeta?.draftRowId,\n\t\t\t});\n\n\t\t\t// Flag draft rows (faded) and per-cell errors (error) so the host can paint\n\t\t\t// the DOM equivalent of applyDraftDisabledStyle / applyDraftErrorStyle.\n\t\t\tconst draftErrors = draftMeta?.errors ?? null;\n\t\t\tconst hasCellError = Boolean(draftErrors && colKey in draftErrors);\n\t\t\tconst styled = isDraftRow ? tagDraftStyle(displaySafe, hasCellError) : displaySafe;\n\n\t\t\tconst component = registry.getCellComponent(cellType);\n\t\t\t// Surface the already-computed field/relation meta so a native overlay editor\n\t\t\t// (relation/image, Phase 5) can read EditorProps.fieldMeta / relationInfo without\n\t\t\t// re-resolving — no extra work, just exposing what this routing already derived.\n\t\t\t// `typeKey` is the resolved cellType — the single source of truth for edit-intent.\n\t\t\tconst resolution: SheetsCellResolution = { cell: styled, component, colKey, typeKey: cellType, fieldMeta, relationInfo };\n\t\t\tcache.set(cacheKey, { value: rawValue, resolution });\n\t\t\treturn resolution;\n\t\t},\n\t\t[data, columnKeys, fieldMetaMap, registry, relationFieldNamesFromMeta, relationInfoByField, options, serverRowsReadOnly, serverReadOnlyFields, getRowIdentifier, supportsScalarSelfCommit],\n\t);\n\n\treturn { getSheetsCell };\n}\n","import type { MetaQuery } from '@constructive-io/data';\n\nimport { resolveCellType, type FieldMetadata } from '../cell-types/cell-type-resolver';\nimport type { RelationInfo } from '../store/relation-info-slice';\n\ntype MetaTable = NonNullable<NonNullable<MetaQuery['_meta']>['tables']>[number];\n\nexport interface GridCellRouteInput {\n\tcolKey: string;\n\tfieldMeta?: FieldMetadata;\n\trelationInfo?: RelationInfo;\n\tisRelationFallback?: boolean;\n\tisCustomGeometryCell?: boolean;\n\tisDraftIdCell?: boolean;\n\thasForeignKeyField?: boolean;\n}\n\nexport interface GridCellRoute {\n\tcellType: string;\n\tbaseCellType: string;\n\tisRelation: boolean;\n\tcanEdit: boolean;\n\tcanActivate: boolean;\n\tisReadonly: boolean;\n\tactivationBehavior: 'single-click' | 'double-click';\n}\n\nexport function buildRelationFieldNameSet(meta: MetaQuery | undefined, tableName?: string): Set<string> {\n\tif (!tableName) return new Set<string>();\n\n\tconst table = meta?._meta?.tables?.find((entry): entry is MetaTable => Boolean(entry && entry.name === tableName));\n\tif (!table?.relations) return new Set<string>();\n\n\tconst out = new Set<string>();\n\tconst push = (fieldName?: string | null) => {\n\t\tif (fieldName) out.add(fieldName);\n\t};\n\n\ttable.relations.belongsTo?.forEach((relation) => {\n\t\tpush(relation?.fieldName);\n\t\trelation?.keys?.forEach((key) => push(key?.name));\n\t});\n\ttable.relations.hasOne?.forEach((relation) => push(relation?.fieldName));\n\ttable.relations.hasMany?.forEach((relation) => push(relation?.fieldName));\n\ttable.relations.manyToMany?.forEach((relation) => push(relation?.fieldName));\n\n\treturn out;\n}\n\nexport function resolveGridCellRoute({\n\tcolKey,\n\tfieldMeta,\n\trelationInfo,\n\tisRelationFallback = false,\n\tisCustomGeometryCell = false,\n\tisDraftIdCell = false,\n\thasForeignKeyField = false,\n}: GridCellRouteInput): GridCellRoute {\n\tconst base = resolveCellType(colKey, fieldMeta);\n\tconst isRelation = Boolean(relationInfo) || isRelationFallback;\n\tconst canEditRelationInline = Boolean(\n\t\trelationInfo && relationInfo.kind === 'belongsTo' && relationInfo.foreignKeyField && hasForeignKeyField,\n\t);\n\n\tconst canEdit = isDraftIdCell ? false : isRelation ? canEditRelationInline : base.canEdit;\n\tconst canActivate = isDraftIdCell ? false : isRelation ? true : base.canActivate;\n\tconst isReadonly = isDraftIdCell ? true : isRelation ? !canEditRelationInline : base.isReadonly;\n\n\tlet cellType = isRelation ? 'relation' : base.cellType;\n\tif (!isRelation && isCustomGeometryCell) {\n\t\tcellType = 'geometry';\n\t}\n\n\treturn {\n\t\tcellType,\n\t\tbaseCellType: base.cellType,\n\t\tisRelation,\n\t\tcanEdit,\n\t\tcanActivate,\n\t\tisReadonly,\n\t\tactivationBehavior: base.activationBehavior,\n\t};\n}\n","import { useCallback } from 'react';\n\nimport type { SheetsSelection } from '../../selection/selection-model';\nimport { SHEETS_CONCURRENCY } from '../../config/sheets-concurrency';\nimport { sheetsLogger } from '../../utils/sheets-logger';\nimport { getDraftMeta } from '../row-model';\nimport type { SheetsRowIdentifier } from '../../row-identity';\n\ninterface OperationFeedbackCallbacks {\n\tonStart?: (type: 'delete', total: number) => string;\n\tonProgress?: (id: string, completed: number, failed: number) => void;\n\tonComplete?: (id: string, status: 'success' | 'partial' | 'error', message: string) => void;\n}\n\ntype DeleteOutcome = { status: 'success' | 'partial' | 'error'; message: string } | null;\n\n/**\n * Build the completion toast for a bulk delete, distinguishing UNSAVED draft rows\n * (discarded client-side, nothing hit the server) from real server-row deletes.\n *\n * `drafts` = draft rows discarded, `deleted` = server rows deleted, `failed` =\n * server deletes that errored. All-success wording reflects reality:\n * - only drafts -> \"Discarded N draft(s)\"\n * - only server -> \"Deleted N row(s)\" (unchanged)\n * - mixed -> \"Deleted N rows, discarded M drafts\"\n * The partial/error (failure) wording is unchanged from prior behavior.\n */\nexport function summarizeDeleteResult(drafts: number, deleted: number, failed: number): DeleteOutcome {\n\tconst successes = drafts + deleted;\n\n\tif (failed === 0 && successes > 0) {\n\t\tlet message: string;\n\t\tif (deleted === 0) {\n\t\t\tmessage = `Discarded ${drafts} draft${drafts === 1 ? '' : 's'}`;\n\t\t} else if (drafts === 0) {\n\t\t\tmessage = `Deleted ${deleted} ${deleted === 1 ? 'row' : 'rows'}`;\n\t\t} else {\n\t\t\tmessage = `Deleted ${deleted} ${deleted === 1 ? 'row' : 'rows'}, discarded ${drafts} draft${drafts === 1 ? '' : 's'}`;\n\t\t}\n\t\treturn { status: 'success', message };\n\t}\n\n\tif (successes > 0 && failed > 0) {\n\t\treturn { status: 'partial', message: `Deleted ${successes}, ${failed} failed` };\n\t}\n\n\tif (failed > 0) {\n\t\treturn { status: 'error', message: `Failed to delete ${failed} ${failed === 1 ? 'row' : 'rows'}` };\n\t}\n\n\treturn null;\n}\n\nexport function useGridOperations(\n\tdata: any[],\n\tdeleteRow: (id: SheetsRowIdentifier) => Promise<any>,\n\tgridSelection: SheetsSelection | undefined,\n\tclearSelection: () => void,\n\toptions?: {\n\t\tonRemoveDraftRow?: (draftRowId: string) => void;\n\t\tonAfterServerDeletes?: () => void;\n\t\tgetRowIdentifier?: (row: Readonly<Record<string, unknown>>) => SheetsRowIdentifier | null;\n\t\tcanDeleteServerRows?: boolean;\n\t\tfeedback?: OperationFeedbackCallbacks;\n\t},\n) {\n\tconst deleteSelected = useCallback(async () => {\n\t\tif (!gridSelection) return;\n\n\t\tconst rows = gridSelection.rows.toArray();\n\t\tif (rows.length === 0) return;\n\n\t\t\t// Start operation feedback\n\t\t\tconst operationId = options?.feedback?.onStart?.('delete', rows.length);\n\n\t\t\tlet successes = 0;\n\t\t\tlet failures = 0;\n\t\t\tlet serverSuccesses = 0;\n\t\t\tlet draftDiscards = 0;\n\t\t\tconst records = rows.map((idx) => data[idx]);\n\t\t\tlet nextRecordIndex = 0;\n\t\t\tconst workerCount = Math.min(SHEETS_CONCURRENCY.bulkDelete, records.length);\n\n\t\t\tconst runDeleteWorker = async () => {\n\t\t\t\twhile (nextRecordIndex < records.length) {\n\t\t\t\t\tconst currentIndex = nextRecordIndex;\n\t\t\t\t\tnextRecordIndex += 1;\n\t\t\t\t\tconst record = records[currentIndex];\n\n\t\t\t\t\tconst draftMeta = getDraftMeta(record);\n\t\t\t\t\tif (draftMeta?.isDraft && options?.onRemoveDraftRow) {\n\t\t\t\t\t\tconst draftRowId = draftMeta.draftRowId;\n\t\t\t\t\t\tif (draftRowId) {\n\t\t\t\t\t\t\toptions.onRemoveDraftRow(draftRowId);\n\t\t\t\t\t\t\tsuccesses += 1;\n\t\t\t\t\t\t\tdraftDiscards += 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfailures += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (options?.canDeleteServerRows !== false) {\n\t\t\t\t\t\tconst identifier = options?.getRowIdentifier\n\t\t\t\t\t\t\t? options.getRowIdentifier(record)\n\t\t\t\t\t\t\t: typeof record?.id === 'string' || typeof record?.id === 'number'\n\t\t\t\t\t\t\t\t? record.id\n\t\t\t\t\t\t\t\t: null;\n\t\t\t\t\t\tif (identifier === null) {\n\t\t\t\t\t\t\tfailures += 1;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait deleteRow(identifier);\n\t\t\t\t\t\t\tsuccesses += 1;\n\t\t\t\t\t\t\tserverSuccesses += 1;\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tsheetsLogger().error('Failed to delete record', { identifier, error });\n\t\t\t\t\t\t\tfailures += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfailures += 1;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (operationId) {\n\t\t\t\t\t\toptions?.feedback?.onProgress?.(operationId, successes, failures);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tawait Promise.all(Array.from({ length: workerCount }, () => runDeleteWorker()));\n\n\t\t\t// Complete operation feedback — distinguish discarded drafts from server deletes.\n\t\t\tif (operationId) {\n\t\t\t\tconst outcome = summarizeDeleteResult(draftDiscards, serverSuccesses, failures);\n\t\t\t\tif (outcome) {\n\t\t\t\t\toptions?.feedback?.onComplete?.(operationId, outcome.status, outcome.message);\n\t\t\t\t}\n\t\t\t}\n\n\t\tif (serverSuccesses > 0) {\n\t\t\toptions?.onAfterServerDeletes?.();\n\t\t}\n\n\t\t// Always clear selection so indices don't point to new rows after deletion\n\t\tclearSelection();\n\t}, [gridSelection, data, deleteRow, clearSelection, options]);\n\n\treturn {\n\t\tdeleteSelected,\n\t};\n}\n","import { useMemo } from 'react';\n\nimport type { SheetsSelection } from '../../selection/selection-model';\nimport type { DraftRow } from '../../store/draft-rows-slice';\nimport { getDraftMeta, type DraftMeta } from '../row-model';\n\ninterface DraftRowsTableState {\n\torder: string[];\n\tmap: Record<string, DraftRow>;\n\ttemplate: Record<string, unknown>;\n\tmetaVersion: string;\n\tcolumnOrder: string[];\n}\n\nexport interface DraftRowEntry {\n\tdraftRowId: string;\n\tdraftRow: DraftRow;\n}\n\ninterface UseGridSelectionStateParams {\n\tgridSelection: SheetsSelection | undefined;\n\tcombinedRows: any[];\n\tdraftRowsTable?: DraftRowsTableState;\n}\n\nexport function useGridSelectionState({ gridSelection, combinedRows, draftRowsTable }: UseGridSelectionStateParams) {\n\tconst selectedRowIndices = useMemo(() => {\n\t\tif (!gridSelection) return [] as number[];\n\t\treturn gridSelection.rows.toArray();\n\t}, [gridSelection]);\n\n\tconst selectedRowCount = selectedRowIndices.length;\n\n\tconst selectedDraftRowEntries = useMemo(() => {\n\t\tif (!draftRowsTable || selectedRowIndices.length === 0) return [] as DraftRowEntry[];\n\n\t\treturn selectedRowIndices\n\t\t\t.map((rowIndex) => getDraftMeta(combinedRows[rowIndex]))\n\t\t\t.filter((meta): meta is DraftMeta => Boolean(meta?.draftRowId))\n\t\t\t.map((meta) => {\n\t\t\t\tconst draftRow = draftRowsTable.map[meta.draftRowId];\n\t\t\t\treturn draftRow ? { draftRowId: meta.draftRowId, draftRow } : null;\n\t\t\t})\n\t\t\t.filter((entry): entry is DraftRowEntry => entry !== null);\n\t}, [draftRowsTable, selectedRowIndices, combinedRows]);\n\n\tconst hasDraftSelection = selectedDraftRowEntries.length > 0;\n\n\treturn {\n\t\tselectedRowIndices,\n\t\tselectedRowCount,\n\t\tselectedDraftRowEntries,\n\t\thasDraftSelection,\n\t};\n}\n","import { useCallback, useMemo, useReducer } from 'react';\n\nimport { emptySheetsSelection, moveActive, selectCell } from '../../selection/selection-model';\nimport type { SheetsSelection } from '../../selection/selection-model';\nimport type { FilterGroup } from '../sheets.controls';\n\n// Centralized grid state interface\nexport interface GridState {\n\t// Sorting state\n\tsorting: {\n\t\tid: string | null;\n\t\tdesc: boolean;\n\t};\n\n\t// Pagination state\n\tpageIndex: number;\n\n\t// Filter states\n\tfilterTree: FilterGroup;\n\tfiltersOpen: boolean;\n\n\t// Column state\n\tcolumnWidths: Map<string, number>;\n\n\t// Selection state (native SheetsSelection — glide is only a derived projection now).\n\t// Field name kept as `gridSelection` to minimize consumer churn during the port.\n\tgridSelection: SheetsSelection | undefined;\n}\n\nconst EMPTY_FILTER_TREE: FilterGroup = { type: 'group', id: 'root', conjunction: 'and', children: [] };\n\n// Action types for state updates\nexport type GridAction =\n\t| { type: 'SET_SORTING'; payload: GridState['sorting'] }\n\t| { type: 'TOGGLE_SORTING'; payload: string }\n\t| { type: 'SET_PAGE_INDEX'; payload: number }\n\t| { type: 'SET_FILTER_TREE'; payload: FilterGroup }\n\t| { type: 'CLEAR_ALL_FILTERS' }\n\t| { type: 'TOGGLE_FILTERS_PANEL' }\n\t| { type: 'SET_FILTERS_OPEN'; payload: boolean }\n\t| { type: 'RESIZE_COLUMN'; payload: { id: string; width: number } }\n\t| { type: 'SET_GRID_SELECTION'; payload: SheetsSelection | undefined }\n\t| { type: 'SET_ACTIVE_CELL'; payload: { col: number; row: number } }\n\t| { type: 'MOVE_ACTIVE'; payload: { dCol: number; dRow: number; colCount: number; rowCount: number } }\n\t| { type: 'RESET_PAGE_IF_NEEDED'; payload: { totalPages: number } };\n\n// Initial state factory\nfunction createInitialGridState(): GridState {\n\treturn {\n\t\tsorting: { id: null, desc: false },\n\t\tpageIndex: 0,\n\t\tfilterTree: { ...EMPTY_FILTER_TREE },\n\t\tfiltersOpen: false,\n\t\tcolumnWidths: new Map(),\n\t\tgridSelection: undefined,\n\t};\n}\n\n// State reducer with type-safe action handling\nfunction gridStateReducer(state: GridState, action: GridAction): GridState {\n\tswitch (action.type) {\n\t\tcase 'SET_SORTING':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tsorting: action.payload,\n\t\t\t};\n\n\t\tcase 'TOGGLE_SORTING': {\n\t\t\tconst colId = action.payload;\n\t\t\tlet newSorting: GridState['sorting'];\n\n\t\t\tif (state.sorting.id !== colId) {\n\t\t\t\t// Different column clicked: start with ASC\n\t\t\t\tnewSorting = { id: colId, desc: false };\n\t\t\t} else if (!state.sorting.desc) {\n\t\t\t\t// Same column, currently ASC: switch to DESC\n\t\t\t\tnewSorting = { id: colId, desc: true };\n\t\t\t} else {\n\t\t\t\t// Same column, currently DESC: reset to neutral (no sorting)\n\t\t\t\tnewSorting = { id: null, desc: false };\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tsorting: newSorting,\n\t\t\t};\n\t\t}\n\n\t\tcase 'SET_PAGE_INDEX':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tpageIndex: action.payload,\n\t\t\t};\n\n\t\tcase 'SET_FILTER_TREE':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tfilterTree: action.payload,\n\t\t\t};\n\n\t\tcase 'CLEAR_ALL_FILTERS':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tfilterTree: { ...EMPTY_FILTER_TREE },\n\t\t\t};\n\n\t\tcase 'TOGGLE_FILTERS_PANEL':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tfiltersOpen: !state.filtersOpen,\n\t\t\t};\n\n\t\tcase 'SET_FILTERS_OPEN':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tfiltersOpen: action.payload,\n\t\t\t};\n\n\t\tcase 'RESIZE_COLUMN': {\n\t\t\tconst newColumnWidths = new Map(state.columnWidths);\n\t\t\tnewColumnWidths.set(action.payload.id, action.payload.width);\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tcolumnWidths: newColumnWidths,\n\t\t\t};\n\t\t}\n\n\t\tcase 'SET_GRID_SELECTION':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tgridSelection: action.payload,\n\t\t\t};\n\n\t\tcase 'SET_ACTIVE_CELL': {\n\t\t\tconst { col, row } = action.payload;\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tgridSelection: selectCell(state.gridSelection ?? emptySheetsSelection, col, row),\n\t\t\t};\n\t\t}\n\n\t\tcase 'MOVE_ACTIVE': {\n\t\t\tconst { dCol, dRow, colCount, rowCount } = action.payload;\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tgridSelection: moveActive(state.gridSelection ?? emptySheetsSelection, dCol, dRow, colCount, rowCount),\n\t\t\t};\n\t\t}\n\n\t\tcase 'RESET_PAGE_IF_NEEDED': {\n\t\t\tconst { totalPages } = action.payload;\n\t\t\tif (state.pageIndex >= totalPages) {\n\t\t\t\treturn {\n\t\t\t\t\t...state,\n\t\t\t\t\tpageIndex: Math.max(0, totalPages - 1),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn state;\n\t\t}\n\n\t\tdefault:\n\t\t\treturn state;\n\t}\n}\n\n// Custom hook for grid state management\nexport function useGridState() {\n\tconst [state, dispatch] = useReducer(gridStateReducer, undefined, createInitialGridState);\n\n\tconst setSorting = useCallback((sorting: GridState['sorting']) => {\n\t\tdispatch({ type: 'SET_SORTING', payload: sorting });\n\t}, []);\n\n\tconst toggleSorting = useCallback((colId: string) => {\n\t\tdispatch({ type: 'TOGGLE_SORTING', payload: colId });\n\t}, []);\n\n\tconst setPageIndex = useCallback((pageIndex: number) => {\n\t\tdispatch({ type: 'SET_PAGE_INDEX', payload: pageIndex });\n\t}, []);\n\n\tconst setFilterTree = useCallback((tree: FilterGroup) => {\n\t\tdispatch({ type: 'SET_FILTER_TREE', payload: tree });\n\t}, []);\n\n\tconst clearAllFilters = useCallback(() => {\n\t\tdispatch({ type: 'CLEAR_ALL_FILTERS' });\n\t}, []);\n\n\tconst toggleFiltersPanel = useCallback(() => {\n\t\tdispatch({ type: 'TOGGLE_FILTERS_PANEL' });\n\t}, []);\n\n\tconst setFiltersOpen = useCallback((open: boolean) => {\n\t\tdispatch({ type: 'SET_FILTERS_OPEN', payload: open });\n\t}, []);\n\n\tconst resizeColumn = useCallback((id: string, width: number) => {\n\t\tdispatch({ type: 'RESIZE_COLUMN', payload: { id, width } });\n\t}, []);\n\n\tconst setGridSelection = useCallback((selection: SheetsSelection | undefined) => {\n\t\tdispatch({ type: 'SET_GRID_SELECTION', payload: selection });\n\t}, []);\n\n\tconst setActiveCell = useCallback((col: number, row: number) => {\n\t\tdispatch({ type: 'SET_ACTIVE_CELL', payload: { col, row } });\n\t}, []);\n\n\tconst moveActiveCell = useCallback((dCol: number, dRow: number, colCount: number, rowCount: number) => {\n\t\tdispatch({ type: 'MOVE_ACTIVE', payload: { dCol, dRow, colCount, rowCount } });\n\t}, []);\n\n\tconst resetPageIfNeeded = useCallback((totalPages: number) => {\n\t\tdispatch({ type: 'RESET_PAGE_IF_NEEDED', payload: { totalPages } });\n\t}, []);\n\n\t// Stable object identity (avoid prop/effect churn in consumers)\n\tconst actions = useMemo(\n\t\t() => ({\n\t\t\tsetSorting,\n\t\t\ttoggleSorting,\n\t\t\tsetPageIndex,\n\t\t\tsetFilterTree,\n\t\t\tclearAllFilters,\n\t\t\ttoggleFiltersPanel,\n\t\t\tsetFiltersOpen,\n\t\t\tresizeColumn,\n\t\t\tsetGridSelection,\n\t\t\tsetActiveCell,\n\t\t\tmoveActiveCell,\n\t\t\tresetPageIfNeeded,\n\t\t}),\n\t\t[\n\t\t\tsetSorting,\n\t\t\ttoggleSorting,\n\t\t\tsetPageIndex,\n\t\t\tsetFilterTree,\n\t\t\tclearAllFilters,\n\t\t\ttoggleFiltersPanel,\n\t\t\tsetFiltersOpen,\n\t\t\tresizeColumn,\n\t\t\tsetGridSelection,\n\t\t\tsetActiveCell,\n\t\t\tmoveActiveCell,\n\t\t\tresetPageIfNeeded,\n\t\t],\n\t);\n\n\treturn {\n\t\tstate,\n\t\tactions,\n\t};\n}\n","/**\n * RangeSet — the immutable selection primitive for the native (TanStack DOM)\n * grid. It replaces glide's `CompactSelection` for row selection state.\n *\n * Internal representation: a sorted, non-overlapping, NON-ADJACENT array of\n * `[start, end)` half-open ranges. Adjacency MERGES on touch (so `add([0,3))`\n * then `add([3,5))` collapses to a single `[0,5)`), keeping a 10k-row selection\n * O(#ranges) instead of O(#rows). Every mutator returns a NEW RangeSet; the\n * receiver is never mutated.\n *\n * Focused tests protect merging, splitting, offsets, and immutability without\n * freezing the obsolete grid implementation this class replaced.\n */\n\ntype Range = readonly [start: number, end: number];\n\n/** Normalize the `number | [number, number]` arg to a half-open `[start, end)`. */\nfunction toRange(i: number | [number, number]): Range {\n\treturn typeof i === 'number' ? [i, i + 1] : [i[0], i[1]];\n}\n\n/** True when the range is empty/inverted (start >= end) and contributes nothing. */\nfunction isEmptyRange([start, end]: Range): boolean {\n\treturn start >= end;\n}\n\n/**\n * Insert `[s, e)` into a sorted, disjoint, non-adjacent range list, merging any\n * ranges it overlaps OR merely TOUCHES (touch = adjacency merge). Returns a new\n * sorted, disjoint, non-adjacent list.\n */\nfunction insertRange(ranges: readonly Range[], [s, e]: Range): Range[] {\n\tconst out: Range[] = [];\n\tlet start = s;\n\tlet end = e;\n\tlet inserted = false;\n\tfor (const [rs, re] of ranges) {\n\t\tif (re < start) {\n\t\t\t// Entirely before the new range (and not touching) — keep as-is.\n\t\t\tout.push([rs, re]);\n\t\t} else if (rs > end) {\n\t\t\t// Entirely after the new range (and not touching) — emit the merged\n\t\t\t// range once, then keep the rest.\n\t\t\tif (!inserted) {\n\t\t\t\tout.push([start, end]);\n\t\t\t\tinserted = true;\n\t\t\t}\n\t\t\tout.push([rs, re]);\n\t\t} else {\n\t\t\t// Overlaps or touches — widen the in-flight merged range.\n\t\t\tstart = Math.min(start, rs);\n\t\t\tend = Math.max(end, re);\n\t\t}\n\t}\n\tif (!inserted) out.push([start, end]);\n\treturn out;\n}\n\n/**\n * Subtract `[selMin, selMax)` from a sorted, disjoint range list, SPLITTING any\n * covering range (removing the middle of one yields two).\n *\n * This is a faithful port of glide `CompactSelection.remove`, including its two\n * documented quirks rather than a clean set difference:\n *\n * 1. Overlap test is `start <= selMax && selMin <= end` — both bounds `<=`, so\n * a range touching the cut is \"intersected\" (usually a harmless in-place\n * replace with an identical range).\n * 2. It SPLICES `items` in place while iterating with `items.entries()`, whose\n * cursor just counts iterations (0,1,2,…) regardless of mutation. So when a\n * range is fully consumed (`toAdd` empty), `splice(i, 1)` shrinks the array\n * and the element that slides into slot `i` is SKIPPED — the next read is\n * slot `i + 1`. A plain index loop over the MUTATED array reproduces this\n * exactly: never re-align `i`. (\"remove-spanning-three-ranges\" depends on\n * it — the range after a fully dropped middle range survives untouched.)\n */\nfunction subtractRange(ranges: readonly Range[], [selMin, selMax]: Range): Range[] {\n\tconst items: Range[] = ranges.map(([start, end]) => [start, end]);\n\tfor (let i = 0; i < items.length; i++) {\n\t\tconst [start, end] = items[i];\n\t\tif (start <= selMax && selMin <= end) {\n\t\t\tconst toAdd: Range[] = [];\n\t\t\tif (start < selMin) toAdd.push([start, selMin]);\n\t\t\tif (selMax < end) toAdd.push([selMax, end]);\n\t\t\titems.splice(i, 1, ...toAdd);\n\t\t}\n\t}\n\treturn items;\n}\n\nexport class RangeSet {\n\tprivate readonly ranges: readonly Range[];\n\n\tprivate constructor(ranges: readonly Range[]) {\n\t\tthis.ranges = ranges;\n\t}\n\n\tstatic empty(): RangeSet {\n\t\treturn new RangeSet([]);\n\t}\n\n\t/** RESET to a single index `[i, i+1)` or a single `[start, end)` range. */\n\tstatic fromSingleSelection(i: number | [number, number]): RangeSet {\n\t\tconst range = toRange(i);\n\t\treturn isEmptyRange(range) ? new RangeSet([]) : new RangeSet([range]);\n\t}\n\n\t/** Add an index/range; merges adjacent + overlapping ranges; contained = no-op. */\n\tadd(i: number | [number, number]): RangeSet {\n\t\tconst range = toRange(i);\n\t\tif (isEmptyRange(range)) return this;\n\t\treturn new RangeSet(insertRange(this.ranges, range));\n\t}\n\n\t/** Remove an index/range; SPLITS a covering range. */\n\tremove(i: number | [number, number]): RangeSet {\n\t\tconst range = toRange(i);\n\t\tif (isEmptyRange(range)) return this;\n\t\treturn new RangeSet(subtractRange(this.ranges, range));\n\t}\n\n\t/** Shift every range by `amount`. */\n\toffset(amount: number): RangeSet {\n\t\tif (amount === 0) return this;\n\t\treturn new RangeSet(this.ranges.map(([start, end]) => [start + amount, end + amount]));\n\t}\n\n\thasIndex(i: number): boolean {\n\t\tfor (const [start, end] of this.ranges) {\n\t\t\tif (i >= start && i < end) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Ascending expansion of every selected index. */\n\ttoArray(): number[] {\n\t\tconst out: number[] = [];\n\t\tfor (const [start, end] of this.ranges) {\n\t\t\tfor (let i = start; i < end; i++) out.push(i);\n\t\t}\n\t\treturn out;\n\t}\n\n\t/** Total selected count — sum of `(end - start)` across ranges. */\n\tget length(): number {\n\t\tlet total = 0;\n\t\tfor (const [start, end] of this.ranges) total += end - start;\n\t\treturn total;\n\t}\n\n\t/** Lowest selected index, or `undefined` when empty. */\n\tfirst(): number | undefined {\n\t\treturn this.ranges.length === 0 ? undefined : this.ranges[0][0];\n\t}\n\n\t/** Highest selected index, or `undefined` when empty. */\n\tlast(): number | undefined {\n\t\tif (this.ranges.length === 0) return undefined;\n\t\treturn this.ranges[this.ranges.length - 1][1] - 1;\n\t}\n}\n","/**\n * SheetsSelection — the native (TanStack DOM) selection value that replaces\n * glide's `GridSelection`. It is the canonical selection state for the new grid;\n * glide's `GridSelection` is only a derived projection (see `glide-projection.ts`)\n * kept alive for the still-drawing canvas during the phased port.\n *\n * Shape mirrors the slice of glide the grid actually reads/round-trips:\n * - `rows` — selected ROW indices (a {@link RangeSet}; the only thing\n * production consumes via `.toArray()` / `.length`).\n * - `columns` — selected COLUMN indices. Nothing consumes it today; it exists\n * solely so the glide projection has a faithful slot. Stays empty.\n * - `current` — the active cell + optional active range (glide's `current.cell`\n * + `current.range`). The canvas keyboard-nav cursor depends on it,\n * so the projection must preserve it round-trip.\n *\n * The interaction helpers below are PURE and own the click logic glide used to\n * own internally (plain/ctrl/shift row clicks). They operate on ROW indices.\n *\n * NOTE — anchor tracking for shift-click is NOT stored here: `selectRange` takes\n * the anchor as an argument, so the caller (the reducer / interaction layer) owns\n * \"where the last plain click landed\". This keeps the model a pure value with no\n * hidden interaction state.\n */\n\nimport { RangeSet } from './range-set';\n\n/** A half-open active range in cell coordinates (mirrors glide's `Rectangle`). */\nexport interface SelectionRect {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n}\n\n/** The active cell (and optional active range) — glide's `current`, trimmed. */\nexport interface SelectionCurrent {\n\t/** `[col, row]` — mirrors glide's `Item` ordering. */\n\tcell: [number, number];\n\t/** Active range; absent for a bare single-cell cursor. */\n\trange?: SelectionRect;\n}\n\nexport interface SheetsSelection {\n\tcurrent?: SelectionCurrent;\n\trows: RangeSet;\n\tcolumns: RangeSet;\n}\n\n/** The zero value — no rows, no columns, no active cell. */\nexport const emptySheetsSelection: SheetsSelection = {\n\trows: RangeSet.empty(),\n\tcolumns: RangeSet.empty()\n};\n\n/**\n * Plain row click: REPLACE the row selection with just `index` and park the\n * active cell on that row (column 0). Columns are left empty.\n */\nexport function selectRow(sel: SheetsSelection, index: number): SheetsSelection {\n\treturn {\n\t\tcurrent: { cell: [0, index] },\n\t\trows: RangeSet.fromSingleSelection(index),\n\t\tcolumns: sel.columns\n\t};\n}\n\n/**\n * Ctrl/cmd row click: TOGGLE `index` in the existing row selection (add when\n * absent, remove when present). The active cell follows the touched row.\n */\nexport function toggleRow(sel: SheetsSelection, index: number): SheetsSelection {\n\tconst rows = sel.rows.hasIndex(index) ? sel.rows.remove(index) : sel.rows.add(index);\n\treturn {\n\t\tcurrent: { cell: [0, index] },\n\t\trows,\n\t\tcolumns: sel.columns\n\t};\n}\n\n/**\n * Shift row click: REPLACE the row selection with the contiguous block spanning\n * `anchor`..`index` (inclusive, either order). The active cell follows `index`.\n */\nexport function selectRange(sel: SheetsSelection, anchor: number, index: number): SheetsSelection {\n\tconst min = Math.min(anchor, index);\n\tconst max = Math.max(anchor, index);\n\treturn {\n\t\tcurrent: { cell: [0, index] },\n\t\trows: RangeSet.fromSingleSelection([min, max + 1]),\n\t\tcolumns: sel.columns\n\t};\n}\n\n/** Clear everything back to the empty selection. */\nexport function clear(_sel: SheetsSelection): SheetsSelection {\n\treturn emptySheetsSelection;\n}\n\n/** Clamp `n` into the inclusive `[min, max]` range. */\nfunction clamp(n: number, min: number, max: number): number {\n\treturn Math.max(min, Math.min(max, n));\n}\n\n/**\n * Park the active cell on `[col, row]`, dropping any prior active range. PRESERVES\n * `rows` and `columns` — cell navigation must NOT touch the row-checkbox selection\n * that drives delete/export.\n */\nexport function selectCell(sel: SheetsSelection, col: number, row: number): SheetsSelection {\n\treturn { ...sel, current: { cell: [col, row] } };\n}\n\n/**\n * Extend the active range from an anchor cell to `[col, row]`. The active cell\n * becomes `[col, row]`; `current.range` is a normalized HALF-OPEN {@link SelectionRect}\n * spanning anchor..target in either order. PRESERVES `rows` and `columns`.\n */\nexport function extendRangeToCell(\n\tsel: SheetsSelection,\n\tcol: number,\n\trow: number,\n\tanchorCol: number,\n\tanchorRow: number,\n): SheetsSelection {\n\treturn {\n\t\t...sel,\n\t\tcurrent: {\n\t\t\tcell: [col, row],\n\t\t\trange: {\n\t\t\t\tx: Math.min(col, anchorCol),\n\t\t\t\ty: Math.min(row, anchorRow),\n\t\t\t\twidth: Math.abs(col - anchorCol) + 1,\n\t\t\t\theight: Math.abs(row - anchorRow) + 1,\n\t\t\t},\n\t\t},\n\t};\n}\n\n/**\n * Select the WHOLE grid as a single cell range (Ctrl/Cmd+A). `current.range` is ONE\n * rect spanning every column/row and `current.cell` parks at `[0, 0]`; `rows`/`columns`\n * are untouched. Coordinate-only — NEVER enumerates rows (the infinite row-model is\n * O(totalCount)), so a million-row grid stays a single interval.\n */\nexport function selectAllCells(sel: SheetsSelection, colCount: number, rowCount: number): SheetsSelection {\n\treturn {\n\t\t...sel,\n\t\tcurrent: { cell: [0, 0], range: { x: 0, y: 0, width: colCount, height: rowCount } },\n\t};\n}\n\n/**\n * Move the active cell by `[dCol, dRow]`, clamped to the grid bounds. Starts from\n * `[0, 0]` when no active cell exists. Drops any prior range; PRESERVES rows/columns.\n */\nexport function moveActive(\n\tsel: SheetsSelection,\n\tdCol: number,\n\tdRow: number,\n\tcolCount: number,\n\trowCount: number,\n): SheetsSelection {\n\tconst base = sel.current?.cell ?? [0, 0];\n\tconst col = clamp(base[0] + dCol, 0, colCount - 1);\n\tconst row = clamp(base[1] + dRow, 0, rowCount - 1);\n\treturn selectCell(sel, col, row);\n}\n\n/**\n * Pure nav-key resolver for the extended spreadsheet keys (Tab/Home/End + their\n * Ctrl/Cmd variants + PageUp/PageDown). Returns the NEW `[col, row]` target clamped\n * to grid bounds, or `null` when the key is not one of these moves (Arrow keys and\n * Enter/F2 are handled separately). `base` is the current active cell, `pageRows` is\n * the row span of one visible page (PageUp/Dn). Coordinate-only — never enumerates rows.\n */\nexport function computeKeyNavTarget(\n\tkey: string,\n\tmods: { ctrlOrMeta: boolean; shift: boolean },\n\tbase: [number, number],\n\tcolCount: number,\n\trowCount: number,\n\tpageRows: number,\n): [number, number] | null {\n\tconst [col, row] = base;\n\tconst lastCol = colCount - 1;\n\tconst lastRow = rowCount - 1;\n\n\tswitch (key) {\n\t\tcase 'Tab': {\n\t\t\tif (mods.shift) {\n\t\t\t\t// col-1; before col 0 wrap to the last col of the previous row. Clamp at grid start.\n\t\t\t\tif (col > 0) return [col - 1, row];\n\t\t\t\tif (row > 0) return [lastCol, row - 1];\n\t\t\t\treturn [0, 0];\n\t\t\t}\n\t\t\t// col+1; past the last col wrap to col 0 of the next row. Clamp at grid end.\n\t\t\tif (col < lastCol) return [col + 1, row];\n\t\t\tif (row < lastRow) return [0, row + 1];\n\t\t\treturn [lastCol, lastRow];\n\t\t}\n\t\tcase 'Home':\n\t\t\treturn mods.ctrlOrMeta ? [0, 0] : [0, row];\n\t\tcase 'End':\n\t\t\treturn mods.ctrlOrMeta ? [lastCol, lastRow] : [lastCol, row];\n\t\tcase 'PageUp':\n\t\t\treturn [col, clamp(row - pageRows, 0, lastRow)];\n\t\tcase 'PageDown':\n\t\t\treturn [col, clamp(row + pageRows, 0, lastRow)];\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n","/**\n * Hook for integrating infinite scroll with the data grid\n * Wraps useSheetsInfiniteTable and provides grid-specific utilities\n */\nimport { useCallback, useMemo } from 'react';\n\nimport type { MetaField, MetaQuery } from '@constructive-io/data';\n\nimport { useSheetsContext } from '../../context/sheets-context';\nimport { useSheetsMeta } from '../../hooks/use-sheets-meta';\nimport { useSheetsInfiniteTable, type UseInfiniteTableOptions } from '../../hooks/use-sheets-infinite-table';\n\nimport { getAllRelationFields } from '../../utils/relation-utils';\nimport { normalizeServerRow } from '../sheets.utils';\n\ntype RowRecord = Record<string, unknown>;\n\n/** Native inclusive row window — the DOM grid's visible-range shape (no glide Rectangle). */\nexport interface VisibleRowRange {\n\tstartIndex: number;\n\tendIndex: number;\n}\n\ntype MetaTable = NonNullable<NonNullable<NonNullable<MetaQuery['_meta']>['tables']>[number]>;\n\n/**\n * Apply field type overrides from SheetsConfig to field metadata.\n * Mirrors the logic in use-load-grid.ts for consistent behavior.\n */\nfunction buildFieldMetaMap(\n\tfields: MetaField[],\n\ttableName: string,\n\tfieldTypeOverrides?: Record<string, string>,\n): Map<string, MetaField> {\n\tconst map = new Map<string, MetaField>();\n\n\tif (!fields || fields.length === 0) return map;\n\n\tfor (const field of fields) {\n\t\tif (!field?.name) continue;\n\n\t\tconst overrideKey = `${tableName}.${field.name}`;\n\t\tconst overridePgAlias = fieldTypeOverrides?.[overrideKey];\n\n\t\tif (overridePgAlias && field.type?.pgAlias !== overridePgAlias) {\n\t\t\tmap.set(field.name, {\n\t\t\t\t...field,\n\t\t\t\ttype: {\n\t\t\t\t\t...field.type,\n\t\t\t\t\tpgAlias: overridePgAlias,\n\t\t\t\t},\n\t\t\t} as MetaField);\n\t\t} else {\n\t\t\tmap.set(field.name, field);\n\t\t}\n\t}\n\n\treturn map;\n}\n\nexport interface UseInfiniteGridDataOptions extends Omit<UseInfiniteTableOptions, 'select'> {\n\ttableName: string;\n}\n\nexport interface UseInfiniteGridDataResult {\n\t/** Get row at index, returns null if not loaded */\n\tgetRowAtIndex: (index: number) => RowRecord | null;\n\t/** Total count of rows */\n\ttotalCount: number;\n\t/** Check if row is loaded */\n\tisRowLoaded: (rowIndex: number) => boolean;\n\t/** Prefetch the rows in an inclusive visible window (native range, not a glide Rectangle). */\n\tonVisibleRegionChanged: (range: VisibleRowRange) => void;\n\t/** Whether data is loading */\n\tisLoading: boolean;\n\t/** Whether initial data has been fetched */\n\thasInitialData: boolean;\n\t/** Error if any */\n\terror: Error | null;\n\t/** Invalidate and refetch all data */\n\tinvalidate: () => void;\n\t/**\n\t * Optimistically update a single row in the cache without refetching.\n\t * Used after successful cell edits to avoid full grid refresh.\n\t * @param rowIndex The index of the row to update\n\t * @param patch Partial row data to merge with existing row\n\t * @returns true if the row was found and updated, false on a cache miss\n\t */\n\tupdateRowAtIndex: (rowIndex: number, patch: Partial<RowRecord>) => boolean;\n\t/** Table metadata */\n\ttableMeta: MetaTable | null;\n\t/** Field metadata map */\n\tfieldMetaMap: Map<string, MetaField>;\n\t/** All relation field names */\n\tallRelationFields: string[];\n\t/** Page size */\n\tpageSize: number;\n}\n\n/**\n * Hook that provides infinite scroll data loading for the grid\n */\nexport function useInfiniteGridData({\n\ttableName,\n\tpageSize = 100,\n\torderBy,\n\twhere,\n\tenabled = true,\n}: UseInfiniteGridDataOptions): UseInfiniteGridDataResult {\n\t// Get metadata\n\tconst { data: meta, error: metaError } = useSheetsMeta({ enabled });\n\tconst { config } = useSheetsContext();\n\n\tconst tableMeta = useMemo<MetaTable | null>(() => {\n\t\tconst candidate = meta?._meta?.tables?.find((t) => t?.name === tableName) as MetaTable | undefined;\n\t\treturn candidate ?? null;\n\t}, [meta, tableName]);\n\n\t// Field metadata map for quick lookup, enhanced with field type overrides\n\tconst fieldMetaMap = useMemo(() => {\n\t\tconst candidate = meta?._meta?.tables?.find((t) => t?.name === tableName) as MetaTable | undefined;\n\t\tconst fields = (candidate?.fields as MetaField[]) || [];\n\t\treturn buildFieldMetaMap(fields, tableName, config.fieldTypeOverrides);\n\t}, [meta, tableName, config.fieldTypeOverrides]);\n\n\tconst metaTables = meta?._meta?.tables;\n\tconst allRelationFields = useMemo<string[]>(\n\t\t() => {\n\t\t\tconst rawTables = metaTables?.filter((t): t is NonNullable<typeof t> => t != null);\n\t\t\treturn getAllRelationFields(tableMeta?.relations, rawTables);\n\t\t},\n\t\t[tableMeta, metaTables],\n\t);\n\n\tconst relationFieldNames = useMemo(() => new Set(allRelationFields), [allRelationFields]);\n\n\tconst fieldSelection = useMemo(() => {\n\t\tif (allRelationFields.length === 0) return 'all' as const;\n\t\treturn { includeRelations: allRelationFields };\n\t}, [allRelationFields]);\n\n\t// Use the infinite table hook\n\tconst infiniteTable = useSheetsInfiniteTable<RowRecord>(tableName, {\n\t\tpageSize,\n\t\torderBy,\n\t\twhere,\n\t\tselect: fieldSelection,\n\t\tenabled,\n\t});\n\n\t// Get row at index with normalization\n\t// Note: We don't cache normalized rows because optimistic updates change the underlying\n\t// data without changing the row id. Caching by id causes stale data to be returned.\n\t// Normalization is cheap enough to do on every access.\n\tconst getRowAtIndex = useCallback(\n\t\t(rowIndex: number): RowRecord | null => {\n\t\t\tconst rawRow = infiniteTable.getRowAtIndex(rowIndex);\n\t\t\tif (rawRow === null) return null;\n\n\t\t\t// Always normalize - caching caused stale data issues with optimistic updates\n\t\t\t// because the cache key (id) doesn't change when other fields are updated\n\t\t\treturn normalizeServerRow(rawRow, relationFieldNames);\n\t\t},\n\t\t[infiniteTable, relationFieldNames],\n\t);\n\n\t// Prefetch rows for an inclusive visible window (native range).\n\tconst onVisibleRegionChanged = useCallback(\n\t\t(range: VisibleRowRange) => {\n\t\t\tconst startRow = range.startIndex;\n\t\t\tconst endRow = range.endIndex;\n\n\t\t\t// Add buffer for smoother scrolling\n\t\t\tconst buffer = Math.ceil(pageSize / 2);\n\t\t\tinfiniteTable.ensureRowsLoaded(Math.max(0, startRow - buffer), endRow + buffer);\n\t\t},\n\t\t[infiniteTable, pageSize],\n\t);\n\n\t// Invalidate and refetch\n\tconst invalidate = useCallback(() => {\n\t\tinfiniteTable.invalidate();\n\t}, [infiniteTable]);\n\n\t// Optimistically update a single row without refetching\n\tconst updateRowAtIndex = useCallback(\n\t\t(rowIndex: number, patch: Partial<RowRecord>): boolean => {\n\t\t\t// Update the underlying React Query page cache\n\t\t\t// getRowAtIndex will return the updated data on next access.\n\t\t\t// Propagate the inner boolean so callers can self-heal (refetch) on a cache miss.\n\t\t\treturn infiniteTable.updateRowAtIndex(rowIndex, patch);\n\t\t},\n\t\t[infiniteTable],\n\t);\n\n\treturn {\n\t\tgetRowAtIndex,\n\t\ttotalCount: infiniteTable.totalCount,\n\t\tisRowLoaded: infiniteTable.isRowLoaded,\n\t\tonVisibleRegionChanged,\n\t\tisLoading: infiniteTable.isLoading,\n\t\thasInitialData: infiniteTable.hasInitialData,\n\t\terror: metaError ?? infiniteTable.error,\n\t\tinvalidate,\n\t\tupdateRowAtIndex,\n\t\ttableMeta,\n\t\tfieldMetaMap,\n\t\tallRelationFields,\n\t\tpageSize,\n\t};\n}\n","/**\n * Infinite scroll table hook with hybrid cursor-based pagination\n *\n * Uses a hybrid pagination strategy:\n * - Page 0: Offset-based (`first: N`) to get initial data + endCursor\n * - Page N+1: Cursor-based (`first: N, after: endCursor`) for efficient deep pagination\n *\n * This leverages PostGraphile's Relay Connection spec for optimal performance on large datasets.\n *\n * Data Persistence:\n * - Uses React Query cache as the source of truth for page data\n * - Data survives component unmount/remount and route changes\n * - Only clears when table name or query options actually change (deep comparison)\n *\n * Ported from apps/admin use-infinite-table.ts with context injection.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useQueries, useQueryClient } from '@tanstack/react-query';\n\nimport { useSheetsContext } from '../context/sheets-context';\nimport type { SheetsScopeKey } from '../context/sheets-context';\n\nimport {\n\tcleanTable,\n\ttype CleanTable,\n\ttype MetaTable,\n\ttype MutationOptions,\n\ttype PageInfo,\n\ttype QueryOptions,\n} from '@constructive-io/data';\nimport { createError } from '@constructive-io/data';\nimport type { FieldSelection } from '@constructive-io/data';\nimport { reuseSheetsPlaceholderData } from './query-keys';\nimport { toOrderByEnumValue } from '@constructive-io/data';\nimport { useSheetsAdapter } from '../adapter/use-sheets-adapter';\nimport { useSheetsMeta } from './use-sheets-meta';\nimport { sheetsQueryKeys } from './query-keys';\nimport { resolveRelationFieldMap } from './relation-field-resolution';\nimport { validateOrderByVariables } from './orderby-enum-resolution';\nimport { transformToPostGraphileVariables } from './use-sheets-table';\n\ntype RowRecord = Record<string, unknown>;\n\n/** Data for a single loaded page */\nexport interface PageData<T = RowRecord> {\n\trows: T[];\n\tpageInfo: PageInfo;\n\tpageIndex: number;\n\ttotalCount?: number;\n}\n\n/** Options for the infinite table hook */\nexport interface UseInfiniteTableOptions {\n\t/** Page size for fetching */\n\tpageSize?: number;\n\t/** Order by clauses */\n\torderBy?: Array<{ field: string; direction: 'asc' | 'desc' }>;\n\t/** Filter conditions */\n\twhere?: Record<string, unknown>;\n\t/** Field selection preset or custom selection */\n\tselect?: FieldSelection;\n\t/** Enable/disable the hook */\n\tenabled?: boolean;\n\t/** Mutation options for CRUD operations */\n\tmutationOptions?: MutationOptions;\n}\n\n/** Result from the infinite table hook */\nexport interface UseInfiniteTableResult<T = RowRecord> {\n\t/** Get row at a specific index, returns null if not loaded */\n\tgetRowAtIndex: (index: number) => T | null;\n\t/** Total count of rows in the table */\n\ttotalCount: number;\n\t/** Check if a specific row index is loaded */\n\tisRowLoaded: (rowIndex: number) => boolean;\n\t/** Check if a specific page is currently loading */\n\tisPageLoading: (pageIndex: number) => boolean;\n\t/** Ensure rows in a range are loaded (call from onVisibleRegionChanged) */\n\tensureRowsLoaded: (startRow: number, endRow: number) => void;\n\t/** All loaded pages */\n\tloadedPages: Map<number, PageData<T>>;\n\t/** Page size */\n\tpageSize: number;\n\t/** Overall loading state (true if any page is loading) */\n\tisLoading: boolean;\n\t/** Whether initial data has been loaded */\n\thasInitialData: boolean;\n\t/** Error from the most recent failed fetch */\n\terror: Error | null;\n\t/** Invalidate all pages and refetch */\n\tinvalidate: () => void;\n\t/** Reset to initial state (clears all pages, refetches page 0) */\n\treset: () => void;\n\t/**\n\t * Optimistically update a single row in the page cache without refetching.\n\t * @param rowIndex The absolute row index\n\t * @param patch Partial row data to merge with existing row\n\t * @returns true if the row was found and updated, false otherwise\n\t */\n\tupdateRowAtIndex: (rowIndex: number, patch: Partial<T>) => boolean;\n}\n\n/** Query key factory for infinite table pages */\nconst sheetsInfiniteTableKeys = {\n\tall: (scope: SheetsScopeKey, tableName: string) => sheetsQueryKeys.infiniteTable(scope, tableName),\n\tpage: (scope: SheetsScopeKey, tableName: string, pageIndex: number, optionsKey: string) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableName), 'page', pageIndex, optionsKey] as const,\n\ttotalCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown>) =>\n\t\tsheetsQueryKeys.infiniteTableTotalCount(scope, tableName, where),\n};\n\n/**\n * Create a stable JSON key from options for deep comparison.\n * This ensures the key only changes when the actual values change, not object references.\n */\nfunction createStableOptionsKey(options: {\n\tpageSize: number;\n\torderBy?: Array<{ field: string; direction: 'asc' | 'desc' }>;\n\twhere?: Record<string, unknown>;\n\tfieldSelection?: FieldSelection;\n}): string {\n\treturn JSON.stringify({\n\t\tpageSize: options.pageSize,\n\t\torderBy: options.orderBy ?? null,\n\t\twhere: options.where ?? null,\n\t\tfieldSelection: options.fieldSelection ?? null,\n\t});\n}\n\n/**\n * Hook for infinite scroll table with hybrid cursor-based pagination.\n * Uses React Query cache as the source of truth for data persistence.\n */\nexport function useSheetsInfiniteTable<T extends RowRecord = RowRecord>(\n\ttableName: string,\n\toptions: UseInfiniteTableOptions = {},\n): UseInfiniteTableResult<T> {\n\tconst { pageSize = 100, orderBy, where, select: fieldSelection, enabled = true } = options;\n\n\tconst queryClient = useQueryClient();\n\tconst { execute, scopeKey } = useSheetsContext();\n\tconst { data: meta } = useSheetsMeta({ enabled });\n\tconst adapter = useSheetsAdapter();\n\n\t// Create stable options key using JSON serialization for deep comparison\n\tconst stableOptionsKey = useMemo(\n\t\t() => createStableOptionsKey({ pageSize, orderBy, where, fieldSelection }),\n\t\t[pageSize, orderBy, where, fieldSelection],\n\t);\n\n\t// Track which pages we want to load\n\tconst [requestedPages, setRequestedPages] = useState<Set<number>>(() => new Set([0]));\n\n\t// Cursor chain for cursor-based pagination (stored in ref for performance)\n\tconst cursorChainRef = useRef<Map<number, string>>(new Map());\n\tconst [cursorChainVersion, setCursorChainVersion] = useState(0);\n\n\t// Track latest total count from any page response\n\tconst totalCountRef = useRef<number>(0);\n\n\t// Flag to defer cache invalidation to useEffect after synchronous reset\n\tconst needsInvalidationRef = useRef(false);\n\n\t// Generation counter: incremented on every table/options reset. queryFn closures capture\n\t// the current generation and skip cursor writes if stale. This prevents in-flight queries\n\t// from a previous table/options context from poisoning cursorChainRef after a reset.\n\t// (PostGraphile v5 cursors include a digest hash scoped to table + ORDER BY, so a cursor\n\t// from one query context will be rejected by a different query context.)\n\tconst generationRef = useRef(0);\n\n\t// Track previous stable key to detect actual changes\n\tconst prevStableKeyRef = useRef<string>(stableOptionsKey);\n\tconst prevTableNameRef = useRef<string>(tableName);\n\n\t// Get table metadata\n\tconst tables = useMemo<CleanTable[]>(() => {\n\t\tif (!meta?._meta?.tables) return [];\n\t\treturn meta._meta.tables\n\t\t\t.filter((candidate): candidate is MetaTable => candidate != null)\n\t\t\t.map((metaTable) => cleanTable(metaTable));\n\t}, [meta]);\n\n\tconst table = useMemo<CleanTable | null>(\n\t\t() => tables.find((candidate) => candidate.name === tableName) ?? null,\n\t\t[tables, tableName],\n\t);\n\n\t// Synchronous render-time reset: clear cursors and state BEFORE pageQueries useMemo reads them.\n\t// This follows the React 18+ \"storing information from previous renders\" pattern where setState\n\t// during render causes React to discard the current render and retry with updated state.\n\t// On retry, the condition is false (refs already updated) so no infinite loop occurs.\n\tconst tableChanged = prevTableNameRef.current !== tableName;\n\tconst optionsChanged = prevStableKeyRef.current !== stableOptionsKey;\n\n\tif (tableChanged || optionsChanged) {\n\t\t// Clear cursors synchronously — must happen before pageQueries useMemo\n\t\tcursorChainRef.current.clear();\n\t\ttotalCountRef.current = 0;\n\n\t\t// Bump generation so in-flight queryFn closures from the old context\n\t\t// will skip writing their stale cursors into cursorChainRef\n\t\tgenerationRef.current += 1;\n\n\t\t// Update tracking refs so condition is false on retry render\n\t\tprevTableNameRef.current = tableName;\n\t\tprevStableKeyRef.current = stableOptionsKey;\n\n\t\t// Flag cache invalidation for the subsequent useEffect\n\t\tneedsInvalidationRef.current = true;\n\n\t\t// Trigger state update — React discards current render and retries\n\t\tsetCursorChainVersion(0);\n\t\tsetRequestedPages(new Set([0]));\n\t}\n\n\t// Cache invalidation is a side effect and must stay in useEffect\n\tuseEffect(() => {\n\t\tif (needsInvalidationRef.current) {\n\t\t\tneedsInvalidationRef.current = false;\n\t\t\tqueryClient.invalidateQueries({\n\t\t\t\tqueryKey: sheetsInfiniteTableKeys.all(scopeKey, tableName),\n\t\t\t});\n\t\t}\n\t}, [tableName, stableOptionsKey, queryClient, scopeKey]);\n\n\t// Helper to get page data from React Query cache\n\tconst getPageDataFromCache = useCallback(\n\t\t(pageIndex: number): PageData<T> | undefined => {\n\t\t\treturn queryClient.getQueryData<PageData<T>>(\n\t\t\t\tsheetsInfiniteTableKeys.page(scopeKey, tableName, pageIndex, stableOptionsKey),\n\t\t\t);\n\t\t},\n\t\t[queryClient, scopeKey, tableName, stableOptionsKey],\n\t);\n\n\t// Create query options for each requested page\n\tconst pageQueries = useMemo(() => {\n\t\tif (!table || !enabled) return [];\n\t\t// Force recompute when cursor chain advances\n\t\tvoid cursorChainVersion;\n\n\t\t// Capture generation at useMemo time — queryFn closures use this to detect\n\t\t// if the query context has changed (table/options reset) before they write cursors\n\t\tconst queryGeneration = generationRef.current;\n\n\t\treturn Array.from(requestedPages).map((pageIndex) => {\n\t\t\t// Determine pagination strategy\n\t\t\tconst isFirstPage = pageIndex === 0;\n\t\t\tconst previousCursor = pageIndex > 0 ? cursorChainRef.current.get(pageIndex - 1) : undefined;\n\t\t\t// Pages:\n\t\t\t// - 0: always fetch\n\t\t\t// - 1: wait for cursor from page 0 (prefer cursor-based)\n\t\t\t// - 2+: allow offset fallback (supports scrollbar jumps without loading all intermediate pages)\n\t\t\tconst canUseOffsetFallback = pageIndex >= 2;\n\t\t\tconst canFetch = isFirstPage || previousCursor !== undefined || canUseOffsetFallback;\n\n\t\t\treturn {\n\t\t\t\tqueryKey: sheetsInfiniteTableKeys.page(scopeKey, tableName, pageIndex, stableOptionsKey),\n\t\t\t\tqueryFn: async (): Promise<PageData<T>> => {\n\t\t\t\t\tif (!table) {\n\t\t\t\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Build query options. `includePageInfo` is always set so the cursor\n\t\t\t\t\t// chain works on every page (page 0 has no `after` to imply pageInfo).\n\t\t\t\t\tconst queryOptions: QueryOptions = {\n\t\t\t\t\t\tfirst: pageSize,\n\t\t\t\t\t\torderBy,\n\t\t\t\t\t\twhere: where as QueryOptions['where'],\n\t\t\t\t\t\tfieldSelection,\n\t\t\t\t\t\tincludePageInfo: true, // Always include for cursor chain\n\t\t\t\t\t};\n\n\t\t\t\t\t// Prefer cursor-based pagination when possible; allow offset fallback for deep jumps.\n\t\t\t\t\tif (!isFirstPage) {\n\t\t\t\t\t\tif (previousCursor) {\n\t\t\t\t\t\t\tqueryOptions.after = previousCursor;\n\t\t\t\t\t\t} else if (canUseOffsetFallback) {\n\t\t\t\t\t\t\tqueryOptions.offset = pageIndex * pageSize;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Cache-bound resolution stays in the hook. The orderBy validation mutates\n\t\t\t\t\t// `variables.orderBy` (PostGraphile enum strings) in place; we fold that\n\t\t\t\t\t// result back into the `{ field, direction }[]` orderBy we hand the adapter,\n\t\t\t\t\t// so the adapter rebuilds an identical (validated) variables payload.\n\t\t\t\t\tconst variables = transformToPostGraphileVariables(table, queryOptions);\n\n\t\t\t\t\tconst [relationFieldMap] = await Promise.all([\n\t\t\t\t\t\tresolveRelationFieldMap({\n\t\t\t\t\t\t\ttable,\n\t\t\t\t\t\t\tfieldSelection: queryOptions.fieldSelection,\n\t\t\t\t\t\t\tscopeKey,\n\t\t\t\t\t\t\tqueryClient,\n\t\t\t\t\t\t\texecute,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tvalidateOrderByVariables(variables, table, scopeKey, queryClient, execute),\n\t\t\t\t\t]);\n\n\t\t\t\t\tconst validatedOrderByEnum = new Set((variables.orderBy as string[] | undefined) ?? []);\n\t\t\t\t\tconst availableOrderByFields = new Set(table.fields.map((field) => field.name));\n\t\t\t\t\tconst validatedOrderBy = orderBy?.filter(\n\t\t\t\t\t\t({ field, direction }) =>\n\t\t\t\t\t\t\tavailableOrderByFields.has(field) && validatedOrderByEnum.has(toOrderByEnumValue(field, direction)),\n\t\t\t\t\t);\n\n\t\t\t\t\tconst res = await adapter.listRows<T>(\n\t\t\t\t\t\t{ table, allTables: tables, tableName },\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...queryOptions,\n\t\t\t\t\t\t\torderBy: validatedOrderBy,\n\t\t\t\t\t\t\t// resolveRelationFieldMap yields `string | null` (null = omit field). The\n\t\t\t\t\t\t\t// contract narrows to `string`, but the null values are passed through to\n\t\t\t\t\t\t\t// buildSelect unchanged at runtime — behavior is identical to before.\n\t\t\t\t\t\t\trelationFieldMap: relationFieldMap as Record<string, string>,\n\t\t\t\t\t\t},\n\t\t\t\t\t\texecute,\n\t\t\t\t\t);\n\n\t\t\t\t\tconst rows = res.rows;\n\t\t\t\t\t// The adapter's AdapterPageInfo marks booleans optional; the underlying\n\t\t\t\t\t// PostGraphile connection always populates them (the doc selects all four),\n\t\t\t\t\t// so this narrows to PageInfo exactly as the inline connection cast did.\n\t\t\t\t\tconst pageInfo: PageInfo = (res.pageInfo as PageInfo | undefined) || {\n\t\t\t\t\t\thasNextPage: false,\n\t\t\t\t\t\thasPreviousPage: false,\n\t\t\t\t\t\tendCursor: null,\n\t\t\t\t\t\tstartCursor: null,\n\t\t\t\t\t};\n\n\t\t\t\t\t// Guard: only write refs if this queryFn's generation matches the current one.\n\t\t\t\t\t// In-flight queries from a previous table/options context will have a stale\n\t\t\t\t\t// generation and their writes are silently discarded.\n\t\t\t\t\tconst isCurrentGeneration = queryGeneration === generationRef.current;\n\n\t\t\t\t\t// Update total count ref\n\t\t\t\t\tif (res.totalCount !== undefined && isCurrentGeneration) {\n\t\t\t\t\t\ttotalCountRef.current = res.totalCount;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Store cursor for next page (and bump version so dependent pages can enable)\n\t\t\t\t\tif (pageInfo.endCursor && isCurrentGeneration) {\n\t\t\t\t\t\tconst prev = cursorChainRef.current.get(pageIndex);\n\t\t\t\t\t\tif (prev !== pageInfo.endCursor) {\n\t\t\t\t\t\t\tcursorChainRef.current.set(pageIndex, pageInfo.endCursor);\n\t\t\t\t\t\t\tsetCursorChainVersion((v) => v + 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst pageData: PageData<T> = {\n\t\t\t\t\t\trows,\n\t\t\t\t\t\tpageInfo,\n\t\t\t\t\t\tpageIndex,\n\t\t\t\t\t\ttotalCount: res.totalCount,\n\t\t\t\t\t};\n\n\t\t\t\t\treturn pageData;\n\t\t\t\t},\n\t\t\t\tenabled: enabled && !!table && canFetch,\n\t\t\t\t// Reuse a page across sort/filter/page-size key changes only while the\n\t\t\t\t// endpoint, database, and authenticated identity remain unchanged.\n\t\t\t\tplaceholderData: (\n\t\t\t\t\tpreviousData: PageData<T> | undefined,\n\t\t\t\t\tpreviousQuery: { queryKey: readonly unknown[] } | undefined,\n\t\t\t\t) =>\n\t\t\t\t\treuseSheetsPlaceholderData(previousData, previousQuery?.queryKey, scopeKey),\n\t\t\t\tstaleTime: 5 * 60 * 1000, // 5 minutes\n\t\t\t\tgcTime: 10 * 60 * 1000, // 10 minutes\n\t\t\t};\n\t\t});\n\t\t}, [\n\t\t\ttable,\n\t\t\ttables,\n\t\t\ttableName,\n\t\t\tenabled,\n\t\t\tscopeKey,\n\t\t\tqueryClient,\n\t\t\texecute,\n\t\t\tadapter,\n\t\t\trequestedPages,\n\t\t\tstableOptionsKey,\n\t\t\tpageSize,\n\t\torderBy,\n\t\twhere,\n\t\tfieldSelection,\n\t\tcursorChainVersion,\n\t]);\n\n\t// Execute all page queries\n\tconst queryResults = useQueries({ queries: pageQueries });\n\n\t// Sync cursor chain from React Query cache on mount/rehydration\n\t// This restores cursors for pages that were cached but cursor chain was lost.\n\t// Guarded by generation to avoid restoring stale cursors during a reset transition.\n\tuseEffect(() => {\n\t\tif (!enabled || !table) return;\n\n\t\tconst gen = generationRef.current;\n\n\t\t// Check React Query cache for existing page data and restore cursors\n\t\tfor (let i = 0; i < 100; i++) {\n\t\t\t// Bail if generation changed (a reset happened while this effect was running)\n\t\t\tif (gen !== generationRef.current) break;\n\n\t\t\t// Check up to 100 pages\n\t\t\tconst cachedData = getPageDataFromCache(i);\n\t\t\tif (cachedData?.pageInfo?.endCursor && !cursorChainRef.current.has(i)) {\n\t\t\t\tcursorChainRef.current.set(i, cachedData.pageInfo.endCursor);\n\t\t\t}\n\t\t\tif (cachedData?.totalCount !== undefined) {\n\t\t\t\ttotalCountRef.current = cachedData.totalCount;\n\t\t\t}\n\t\t\tif (!cachedData) break; // Stop at first missing page\n\t\t}\n\t}, [enabled, table, getPageDataFromCache]);\n\n\t// Compute loading states\n\tconst isLoading = queryResults.some((result) => result.isLoading);\n\n\t// Check if we have initial data - either from current query or from cache\n\tconst hasInitialData = useMemo(() => {\n\t\t// Check query results first\n\t\tconst page0Query = queryResults.find((_, idx) => Array.from(requestedPages)[idx] === 0);\n\t\tif (page0Query?.data) return true;\n\n\t\t// Fall back to cache check\n\t\tconst cachedPage0 = getPageDataFromCache(0);\n\t\treturn cachedPage0 !== undefined;\n\t}, [queryResults, requestedPages, getPageDataFromCache]);\n\n\tconst error = queryResults.find((result) => result.error)?.error ?? null;\n\n\t// Get row at index - reads from React Query cache\n\t// IMPORTANT: Always read from cache first since optimistic updates use setQueryData\n\t// which updates cache but doesn't immediately update queryResults references\n\tconst getRowAtIndex = useCallback(\n\t\t(rowIndex: number): T | null => {\n\t\t\tconst pageIndex = Math.floor(rowIndex / pageSize);\n\t\t\tconst rowIndexInPage = rowIndex % pageSize;\n\n\t\t\t// Always read from React Query cache first - this ensures we get optimistically\n\t\t\t// updated data from setQueryData calls (used in updateRowAtIndex)\n\t\t\tconst cachedData = getPageDataFromCache(pageIndex);\n\t\t\tif (cachedData) {\n\t\t\t\treturn cachedData.rows[rowIndexInPage] ?? null;\n\t\t\t}\n\n\t\t\t// Fall back to query results if cache miss (shouldn't happen normally)\n\t\t\tconst queryIndex = Array.from(requestedPages).indexOf(pageIndex);\n\t\t\tif (queryIndex !== -1 && queryResults[queryIndex]?.data) {\n\t\t\t\tconst pageData = queryResults[queryIndex].data;\n\t\t\t\treturn pageData.rows[rowIndexInPage] ?? null;\n\t\t\t}\n\n\t\t\treturn null;\n\t\t},\n\t\t[pageSize, getPageDataFromCache, requestedPages, queryResults],\n\t);\n\n\t// Check if row is loaded - reads from cache first for consistency with getRowAtIndex\n\tconst isRowLoaded = useCallback(\n\t\t(rowIndex: number): boolean => {\n\t\t\tconst pageIndex = Math.floor(rowIndex / pageSize);\n\t\t\tconst rowIndexInPage = rowIndex % pageSize;\n\n\t\t\t// Check cache first (consistent with getRowAtIndex)\n\t\t\tconst cachedData = getPageDataFromCache(pageIndex);\n\t\t\tif (cachedData) {\n\t\t\t\treturn rowIndexInPage < cachedData.rows.length;\n\t\t\t}\n\n\t\t\t// Fallback to query results\n\t\t\tconst queryIndex = Array.from(requestedPages).indexOf(pageIndex);\n\t\t\tif (queryIndex !== -1 && queryResults[queryIndex]?.data) {\n\t\t\t\treturn rowIndexInPage < queryResults[queryIndex].data.rows.length;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t},\n\t\t[pageSize, getPageDataFromCache, requestedPages, queryResults],\n\t);\n\n\t// Check if page is loading\n\tconst isPageLoading = useCallback(\n\t\t(pageIndex: number): boolean => {\n\t\t\tconst queryIndex = Array.from(requestedPages).indexOf(pageIndex);\n\t\t\tif (queryIndex === -1) return false;\n\t\t\treturn queryResults[queryIndex]?.isLoading ?? false;\n\t\t},\n\t\t[requestedPages, queryResults],\n\t);\n\n\t// Ensure rows in range are loaded\n\tconst ensureRowsLoaded = useCallback(\n\t\t(startRow: number, endRow: number) => {\n\t\t\tconst startPage = Math.floor(Math.max(0, startRow) / pageSize);\n\t\t\tconst endPage = Math.floor(Math.max(0, endRow - 1) / pageSize);\n\n\t\t\tconst minPage = Math.max(0, startPage);\n\t\t\tconst maxPage = endPage;\n\n\t\t\tsetRequestedPages((prev) => {\n\t\t\t\tconst next = new Set(prev);\n\t\t\t\tlet changed = false;\n\n\t\t\t\tconst maxPossiblePage =\n\t\t\t\t\ttotalCountRef.current > 0 ? Math.max(0, Math.ceil(totalCountRef.current / pageSize) - 1) : null;\n\t\t\t\tconst cappedMaxPage = maxPossiblePage === null ? maxPage : Math.min(maxPage, maxPossiblePage);\n\n\t\t\t\tfor (let page = minPage; page <= cappedMaxPage; page++) {\n\t\t\t\t\tif (!next.has(page)) {\n\t\t\t\t\t\tnext.add(page);\n\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn changed ? next : prev;\n\t\t\t});\n\t\t},\n\t\t[pageSize],\n\t);\n\n\t// Build loadedPages map from React Query cache for backward compatibility\n\tconst loadedPages = useMemo(() => {\n\t\tconst map = new Map<number, PageData<T>>();\n\n\t\t// Add data from current query results\n\t\tArray.from(requestedPages).forEach((pageIndex, idx) => {\n\t\t\tconst result = queryResults[idx];\n\t\t\tif (result?.data) {\n\t\t\t\tmap.set(pageIndex, result.data);\n\t\t\t}\n\t\t});\n\n\t\treturn map;\n\t}, [requestedPages, queryResults]);\n\n\t// Compute total count from query results or ref\n\tconst totalCount = useMemo(() => {\n\t\t// Try to get from latest query result\n\t\tfor (const result of queryResults) {\n\t\t\tif (result.data?.totalCount !== undefined) {\n\t\t\t\treturn result.data.totalCount;\n\t\t\t}\n\t\t}\n\t\treturn totalCountRef.current;\n\t}, [queryResults]);\n\n\t// Invalidate all pages\n\tconst invalidate = useCallback(() => {\n\t\t// Clear cursor chain and bump generation to discard in-flight stale cursors\n\t\tcursorChainRef.current.clear();\n\t\ttotalCountRef.current = 0;\n\t\tgenerationRef.current += 1;\n\t\tsetCursorChainVersion(0);\n\n\t\t// Reset to page 0\n\t\tsetRequestedPages(new Set([0]));\n\n\t\t// Invalidate React Query cache\n\t\tqueryClient.invalidateQueries({ queryKey: sheetsInfiniteTableKeys.all(scopeKey, tableName) });\n\t}, [queryClient, scopeKey, tableName]);\n\n\t// Reset to initial state\n\tconst reset = useCallback(() => {\n\t\tinvalidate();\n\t}, [invalidate]);\n\n\t// Optimistically update a single row in the React Query cache\n\tconst updateRowAtIndex = useCallback(\n\t\t(rowIndex: number, patch: Partial<T>): boolean => {\n\t\t\tconst pageIndex = Math.floor(rowIndex / pageSize);\n\t\t\tconst rowIndexInPage = rowIndex % pageSize;\n\n\t\t\tconst queryKey = sheetsInfiniteTableKeys.page(scopeKey, tableName, pageIndex, stableOptionsKey);\n\t\t\tconst cachedData = queryClient.getQueryData<PageData<T>>(queryKey);\n\n\t\t\tif (!cachedData || !cachedData.rows[rowIndexInPage]) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Update the cache optimistically\n\t\t\tqueryClient.setQueryData<PageData<T>>(queryKey, (old) => {\n\t\t\t\tif (!old) return old;\n\n\t\t\t\tconst newRows = [...old.rows];\n\t\t\t\tnewRows[rowIndexInPage] = { ...newRows[rowIndexInPage], ...patch } as T;\n\n\t\t\t\treturn {\n\t\t\t\t\t...old,\n\t\t\t\t\trows: newRows,\n\t\t\t\t};\n\t\t\t});\n\n\t\t\treturn true;\n\t\t},\n\t\t[pageSize, queryClient, scopeKey, tableName, stableOptionsKey],\n\t);\n\n\treturn {\n\t\tgetRowAtIndex,\n\t\ttotalCount,\n\t\tisRowLoaded,\n\t\tisPageLoading,\n\t\tensureRowsLoaded,\n\t\tloadedPages,\n\t\tpageSize,\n\t\tisLoading,\n\t\thasInitialData,\n\t\terror: error as Error | null,\n\t\tinvalidate,\n\t\treset,\n\t\tupdateRowAtIndex,\n\t};\n}\n\n/**\n * Export query keys for external cache management\n */\nexport { sheetsInfiniteTableKeys };\n","import { useMemo } from 'react';\nimport type { ReactNode } from 'react';\n\nimport { assessTableWriteCapability, getRowIdentityDefinition } from '@constructive-io/data';\nimport type { FieldSelection, MetaField, MetaQuery, QueryOptions, TableWriteCapability } from '@constructive-io/data';\n\nimport { useSheetsContext } from '../../context/sheets-context';\nimport { useSheetsMeta } from '../../hooks/use-sheets-meta';\nimport { useSheetsTable, type UseTableResult } from '../../hooks/use-sheets-table';\nimport { getAllRelationFields } from '../../utils/relation-utils';\nimport { createColumnSchemaFromMeta } from '../../cell-types/type-mapping';\nimport type { TableSchema, ColumnSchema } from '../../cell-types/types';\nimport { resolveSheetsRowIdentity } from '../../row-identity';\n\ntype MetaTable = NonNullable<NonNullable<NonNullable<MetaQuery['_meta']>['tables']>[number]>;\ntype RowRecord = Record<string, unknown>;\ntype TableOperations = Pick<UseTableResult<RowRecord>, 'update' | 'delete'>;\ntype CreatedRow = Record<string, unknown>;\n\n// Data loading context type\nexport interface DataLoadingContextValue {\n\t// Table data\n\tdata: RowRecord[];\n\ttotalCount: number;\n\t// Loading states\n\tisLoading: boolean;\n\tisError: boolean;\n\terror: Error | null;\n\t// CRUD operations\n\tupdate: TableOperations['update'];\n\tcreate: (data: Record<string, unknown>) => Promise<{ createdRow?: CreatedRow | null }>;\n\tdelete: TableOperations['delete'];\n\t// Refetch the table query (used by the error-state retry)\n\trefetch: () => Promise<unknown>;\n\t// Meta information\n\tmeta: MetaQuery | undefined;\n\ttableMeta: MetaTable | null;\n\twriteCapability: TableWriteCapability | null;\n\ttableSchema: TableSchema | null;\n\tfieldMetaMap: Map<string, MetaField>;\n\tallRelationFields: string[];\n}\n\n// Data loading hook configuration\nexport interface UseDataLoadingConfig {\n\ttableName: string;\n\tenabled?: boolean;\n\tqueryOptions: {\n\t\tlimit?: number;\n\t\toffset?: number;\n\t\torderBy?: Array<{ field: string; direction: 'asc' | 'desc' }>;\n\t\twhere?: QueryOptions['where'];\n\t};\n}\n\n/**\n * Apply field type overrides from SheetsConfig to field metadata.\n *\n * In the admin app, this was handled by `buildEnhancedFieldMetaMap` which\n * merged smartTags.pgAlias from schema-builder. In sheets, the consumer\n * passes `config.fieldTypeOverrides` as a Record<string, string> where\n * key is \"tableName.fieldName\" and value is the cell type override (pgAlias).\n */\nfunction buildFieldMetaMap(\n\tfields: MetaField[],\n\ttableName: string,\n\tfieldTypeOverrides?: Record<string, string>,\n): Map<string, MetaField> {\n\tconst map = new Map<string, MetaField>();\n\n\tif (!fields || fields.length === 0) return map;\n\n\tfor (const field of fields) {\n\t\tif (!field?.name) continue;\n\n\t\t// Check for field type override\n\t\tconst overrideKey = `${tableName}.${field.name}`;\n\t\tconst overridePgAlias = fieldTypeOverrides?.[overrideKey];\n\n\t\tif (overridePgAlias && field.type?.pgAlias !== overridePgAlias) {\n\t\t\t// Apply override\n\t\t\tmap.set(field.name, {\n\t\t\t\t...field,\n\t\t\t\ttype: {\n\t\t\t\t\t...field.type,\n\t\t\t\t\tpgAlias: overridePgAlias,\n\t\t\t\t},\n\t\t\t} as MetaField);\n\t\t} else {\n\t\t\tmap.set(field.name, field);\n\t\t}\n\t}\n\n\treturn map;\n}\n\n// Main data loading hook\nexport function useDataLoading({\n\ttableName,\n\tenabled = true,\n\tqueryOptions,\n}: UseDataLoadingConfig) {\n\t// Meta data for table information\n\tconst { data: meta, isLoading: isMetaLoading, error: metaError } = useSheetsMeta({ enabled });\n\tconst { config } = useSheetsContext();\n\n\tconst tableMeta = useMemo<MetaTable | null>(() => {\n\t\tconst candidate = meta?._meta?.tables?.find((t) => t?.name === tableName) as MetaTable | undefined;\n\t\treturn candidate ?? null;\n\t}, [meta, tableName]);\n\n\t// Table schema for form integration\n\tconst tableSchema = useMemo<TableSchema | null>(() => buildTableSchema(tableMeta), [tableMeta]);\n\tconst writeCapability = useMemo<TableWriteCapability | null>(\n\t\t() => tableMeta ? assessTableWriteCapability(tableMeta) : null,\n\t\t[tableMeta],\n\t);\n\n\t// Field metadata map for quick lookup, enhanced with field type overrides\n\tconst fieldMetaMap = useMemo(() => {\n\t\tconst candidate = meta?._meta?.tables?.find((t) => t?.name === tableName) as MetaTable | undefined;\n\t\tconst fields = (candidate?.fields as MetaField[]) || [];\n\t\treturn buildFieldMetaMap(fields, tableName, config.fieldTypeOverrides);\n\t}, [meta, tableName, config.fieldTypeOverrides]);\n\n\tconst metaTables = meta?._meta?.tables;\n\tconst allRelationFields = useMemo(\n\t\t() => {\n\t\t\tconst rawTables = metaTables?.filter((t): t is NonNullable<typeof t> => t != null);\n\t\t\treturn getAllRelationFields(tableMeta?.relations, rawTables);\n\t\t},\n\t\t[tableMeta, metaTables],\n\t);\n\n\tconst relationSelection = useMemo<FieldSelection>(() => {\n\t\treturn allRelationFields.length > 0 ? { includeRelations: allRelationFields } : 'all';\n\t}, [allRelationFields]);\n\n\tconst tableData = useSheetsTable<RowRecord>(tableName, {\n\t\t...queryOptions,\n\t\t// Leverage field selection to include relation fields when requested\n\t\tselect: relationSelection,\n\t\tenabled,\n\t});\n\tconst {\n\t\tdata = [],\n\t\ttotalCount,\n\t\tupdate: updateRow,\n\t\tcreate: createRow,\n\t\tdelete: deleteRow,\n\t\tisLoading: isTableLoading,\n\t\terror: tableError,\n\t\trefetch,\n\t} = tableData;\n\n\tconst create: DataLoadingContextValue['create'] = async (payload) => {\n\t\tconst result = await createRow(payload);\n\t\tconst createdRow = result?.createdRow;\n\t\tif (!createdRow || typeof createdRow !== 'object' || !tableMeta) {\n\t\t\tthrow new Error(`Create mutation for '${tableName}' did not return a row identity.`);\n\t\t}\n\t\tconst identity = resolveSheetsRowIdentity(tableMeta, createdRow);\n\t\tif (identity.status !== 'identified') {\n\t\t\tthrow new Error(`Create mutation for '${tableName}' returned an incomplete primary-key identity.`);\n\t\t}\n\n\t\treturn { createdRow: createdRow as CreatedRow };\n\t};\n\n\t// Combined loading and error states\n\tconst isLoading = isMetaLoading || isTableLoading;\n\tconst isError = !!metaError || !!tableError;\n\tconst error = (metaError as Error | null) || (tableError as Error | null) || null;\n\n\tconst contextValue: DataLoadingContextValue = useMemo(\n\t\t() => ({\n\t\t\tdata,\n\t\t\ttotalCount,\n\t\t\tisLoading,\n\t\t\tisError,\n\t\t\terror,\n\t\t\tupdate: updateRow,\n\t\t\tcreate,\n\t\t\tdelete: deleteRow,\n\t\t\trefetch,\n\t\t\tmeta,\n\t\t\ttableMeta,\n\t\t\twriteCapability,\n\t\t\ttableSchema,\n\t\t\tfieldMetaMap,\n\t\t\tallRelationFields,\n\t\t}),\n\t\t[\n\t\t\tdata,\n\t\t\ttotalCount,\n\t\t\tisLoading,\n\t\t\tisError,\n\t\t\terror,\n\t\t\tupdateRow,\n\t\t\tcreate,\n\t\t\tdeleteRow,\n\t\t\trefetch,\n\t\t\tmeta,\n\t\t\ttableMeta,\n\t\t\twriteCapability,\n\t\t\ttableSchema,\n\t\t\tfieldMetaMap,\n\t\t\tallRelationFields,\n\t\t],\n\t);\n\n\treturn {\n\t\tcontextValue,\n\t\tProvider: ({ children }: { children: ReactNode }) => children,\n\t};\n}\n\nfunction buildTableSchema(metaTable: MetaTable | null): TableSchema | null {\n\tif (!metaTable) return null;\n\n\tconst columns: ColumnSchema[] = [];\n\tfor (const field of metaTable.fields ?? []) {\n\t\tif (!field) continue;\n\t\tcolumns.push(createColumnSchemaFromMeta(field));\n\t}\n\n\tconst identity = getRowIdentityDefinition(metaTable);\n\tconst primaryKeyFields = identity.status === 'keyed'\n\t\t? identity.fields.map((field) => field.fieldName)\n\t\t: [];\n\n\tconst inflection = metaTable.inflection;\n\n\tconst metadata: TableSchema['metadata'] = {\n\t\tlabel: metaTable.name ?? undefined,\n\t\tdescription: inflection?.tableType ?? inflection?.allRows ?? undefined,\n\t\tprimaryKey: primaryKeyFields.length > 0 ? primaryKeyFields : undefined,\n\t};\n\n\treturn {\n\t\tid: metaTable.name ?? 'unknown-table',\n\t\tname: metaTable.name ?? 'unknown-table',\n\t\tcolumns,\n\t\tmetadata,\n\t};\n}\n\n// Convenience hooks for accessing specific parts of the context\nexport function useTableData(): null {\n\treturn null;\n}\nexport function useTableOperations(): null {\n\treturn null;\n}\nexport function useTableMeta(): null {\n\treturn null;\n}\n","// The TanStack Table v9 instance for the DOM port.\n//\n// This is a STATE-MIRROR over already-server-processed rows — NOT a layout\n// layer (TanStack Virtual does layout in S4) and NOT a data layer (useSheets\n// does data). The hook takes EXPLICIT params (it never calls useSheets) so it\n// is unit-testable with hand-fed data.\n//\n// Controlled state (S1): v8-style `state` partial + per-feature `on*Change`\n// callbacks. The CALLER owns the slices (useGridState / the store) — the table\n// is never a second writer, so there is no echo loop.\n//\n// manualSorting / manualFiltering / manualPagination / rowCount are OMITTED:\n// they live only on the sorting/filtering/pagination feature option types,\n// which we do not register, so those keys are not in our TableOptions and\n// passing them is a TS error (S1 verdict).\nimport { useMemo } from 'react';\nimport { createColumnHelper, useTable } from '@tanstack/react-table';\nimport type {\n\tColumnDef,\n\tColumnPinningState,\n\tColumnResizeMode,\n\tColumnSizingState,\n\tOnChangeFn,\n\tRowSelectionState\n} from '@tanstack/react-table';\n\nimport type { SheetsRow } from '../grid/row-model';\nimport { sheetsTableFeatures, type SheetsTableFeatures } from './features';\n\n/** Smallest column descriptor the instance needs — key + header label (+ optional width). */\nexport interface SheetsColumnDescriptor {\n\tkey: string;\n\tname: string;\n\tsize?: number;\n}\n\nexport type SheetsColumnDef = ColumnDef<SheetsTableFeatures, SheetsRow>;\n\nexport interface UseSheetsTableInstanceParams {\n\t/** Render-column descriptors (header label + key), in display order. */\n\tcolumns: SheetsColumnDescriptor[];\n\t/** Rows fed AS-IS — already server sorted/filtered/paginated by useSheets. */\n\tdata: SheetsRow[];\n\t/** Committed column widths (caller-owned). */\n\tcolumnSizing: ColumnSizingState;\n\t/** Logical start/end column pins (caller-owned). */\n\tcolumnPinning: ColumnPinningState;\n\t/** Row selection map (caller-owned). */\n\trowSelection: RowSelectionState;\n\tonColumnSizingChange: OnChangeFn<ColumnSizingState>;\n\tonColumnPinningChange: OnChangeFn<ColumnPinningState>;\n\tonRowSelectionChange: OnChangeFn<RowSelectionState>;\n\t/** Stable row id from the server primary key / draft meta. Defaults to `row.id`. */\n\tgetRowId?: (row: SheetsRow, index: number) => string;\n}\n\nfunction defaultGetRowId(row: SheetsRow, index: number): string {\n\t// In infinite-scroll mode `data` is the null-backed proxy from useSheets: indices not yet\n\t// fetched read back as `null`. TanStack Table v9 builds its row model over EVERY index\n\t// (getRowId is called per row, eagerly), so guard the null placeholder and key it on the\n\t// index — the stable id an unloaded slot should carry until its page resolves.\n\treturn row?.id != null ? String(row.id) : String(index);\n}\n\n/**\n * Build a v9 table instance wired with {@link sheetsTableFeatures} and the\n * caller-owned controlled state. The column defs carry only a minimal value\n * accessor (`row[key]`); the actual cell RENDER is the S5 host's job, so no\n * `cell` renderer is duplicated here.\n */\nexport function useSheetsTableInstance(params: UseSheetsTableInstanceParams) {\n\tconst {\n\t\tcolumns,\n\t\tdata,\n\t\tcolumnSizing,\n\t\tcolumnPinning,\n\t\trowSelection,\n\t\tonColumnSizingChange,\n\t\tonColumnPinningChange,\n\t\tonRowSelectionChange,\n\t\tgetRowId = defaultGetRowId\n\t} = params;\n\n\tconst columnDefs = useMemo<SheetsColumnDef[]>(() => {\n\t\tconst helper = createColumnHelper<SheetsTableFeatures, SheetsRow>();\n\t\t// accessor-FUNCTION branch (value by key) → requires an explicit `id`. Null-guard the row:\n\t\t// v9 evaluates accessors eagerly while building the row model, and in infinite-scroll mode\n\t\t// `data` is the null-backed proxy (unloaded indices read as `null`). The DOM cell host paints\n\t\t// those slots from `getSheetsCellContent` (→ loading skeleton), so this accessor value is only\n\t\t// a placeholder; returning `undefined` for a null row keeps the eager build from throwing.\n\t\treturn columns.map((col) => helper.accessor((row) => row?.[col.key], { id: col.key, header: col.name, size: col.size }));\n\t}, [columns]);\n\n\t// The v9 pinning feature reads `state.columnPinning.{start,end}` directly (no defaulting\n\t// when a partial object is supplied), so `column.getIsPinned()` throws on a bare `{}`.\n\t// Normalize to a complete shape so callers may pass `{}` for \"nothing pinned\".\n\tconst normalizedPinning = useMemo<ColumnPinningState>(\n\t\t() => ({ start: columnPinning.start ?? [], end: columnPinning.end ?? [] }),\n\t\t[columnPinning]\n\t);\n\n\treturn useTable({\n\t\tfeatures: sheetsTableFeatures,\n\t\tcolumns: columnDefs,\n\t\tdata,\n\t\tgetRowId,\n\t\tenableColumnPinning: true,\n\t\tenableColumnResizing: true,\n\t\tenableRowSelection: true,\n\t\tcolumnResizeMode: 'onChange' as ColumnResizeMode,\n\t\t// Controlled: our reducer/store is the source of truth for these slices.\n\t\tstate: { columnSizing, columnPinning: normalizedPinning, rowSelection },\n\t\tonColumnSizingChange,\n\t\tonColumnPinningChange,\n\t\tonRowSelectionChange\n\t\t// Subscribe to NOTHING (`() => null`). v9 `useTable` runs `table.setOptions(...)` DURING render\n\t\t// to sync the controlled `state` above into its @tanstack/store atoms; a broad selector would make\n\t\t// THIS component a store subscriber, so that render-phase write notifies it synchronously →\n\t\t// `forceStoreRerender` → React's \"Cannot update a component while rendering\" warning. The slices\n\t\t// are caller-owned (the shell is the single source of truth) and the DOM grid reads layout via direct\n\t\t// table methods (getRowModel/getSize/getIsPinned), not `table.state`, so no subscription is needed —\n\t\t// the grid already re-renders from the shell's own state. (TanStack production-readiness: prefer\n\t\t// `() => null` + `table.Subscribe` over a broad `() => state` selector.)\n\t}, (): null => null);\n}\n","// The TanStack Table v9 feature set for the DOM port — EXACTLY the four\n// client-state features (S1). No sort/filter/pagination features and no\n// row-model factories: rows arrive already server-sorted/filtered/paginated\n// from useSheets, so this instance is a pure column + selection state-mirror.\n//\n// Built at module scope so the feature object has a stable identity across\n// renders (a fresh tableFeatures({...}) per render would churn the table).\nimport {\n\tcolumnSizingFeature, // committed column widths -> state.columnSizing\n\tcolumnResizingFeature, // transient drag-resize -> state.columnResizing\n\tcolumnPinningFeature, // logical start/end pin -> state.columnPinning\n\trowSelectionFeature, // row selection -> state.rowSelection\n\ttableFeatures\n} from '@tanstack/react-table';\n\nexport const sheetsTableFeatures = tableFeatures({\n\tcolumnSizingFeature,\n\tcolumnResizingFeature,\n\tcolumnPinningFeature,\n\trowSelectionFeature\n});\n\nexport type SheetsTableFeatures = typeof sheetsTableFeatures;\n","// The DOM viewport for the TanStack port — where LAYOUT happens (the v9 table\n// instance from S3 is a pure state-mirror; this is the dual-axis TanStack\n// Virtual shell that paints it).\n//\n// VERTICAL virtualizer over rows (dynamic height via measureElement), HORIZONTAL\n// virtualizer over columns. The STICKY column (start-pinned via columnPinning, or\n// the first column when nothing is pinned) is painted OUTSIDE the horizontal\n// virtual window — a separate `left: 0` element per row — so it stays put under\n// horizontal scroll. The horizontal virtualizer still counts it (so column start\n// offsets stay correct), but the item loop SKIPS the sticky index; it is never\n// double-painted.\n//\n// A sticky HEADER band (S1) sits at the top of the scroll content, reusing the\n// SAME column layout as the body (sticky-col header + the virtualized non-sticky\n// headers at the identical translateX offsets). Each header carries a sort caret\n// (clickable -> onHeaderClick) and a drag-resize handle on its right edge.\n//\n// `renderCell` is injected so S4 stays host-decoupled and testable: S5 supplies\n// the real cell host. The root carries `data-impl=\"dom\"` so tests / Chrome can\n// assert the DOM path is live.\nimport { useImperativeHandle, useMemo, useRef } from 'react';\nimport type { Ref } from 'react';\nimport { useVirtualizer } from '@tanstack/react-virtual';\nimport type { Cell, Column, Row, Table } from '@tanstack/react-table';\n\nimport { Checkbox } from '@constructive-io/ui/checkbox';\n\nimport { cn } from '../utils/cn';\nimport type { SheetsRow } from '../grid/row-model';\nimport type { SelectionRect } from '../selection/selection-model';\nimport type { SheetsTableFeatures } from './features';\n\n/** Comfortable density default (DESIGN_SPEC §5). Drives the v-virtualizer estimate,\n * range-band / fill-nub geometry, and hit-testing — change here propagates everywhere. */\nconst ESTIMATED_ROW_HEIGHT = 44;\n/** Extra rows rendered above/below the visible window — fewer blank rows on fast vertical scroll. */\nconst ROW_OVERSCAN = 12;\n/** Extra columns rendered left/right of the visible window — fewer blank cells on fast horizontal scroll. */\nconst COLUMN_OVERSCAN = 6;\n/** Header band height (DESIGN_SPEC §5 comfortable) — slightly shorter than the body row. */\nconst HEADER_HEIGHT = 40;\n/** Width of the optional leading row-marker (checkbox) column — glide's rowMarker analogue. */\nconst MARKER_WIDTH = 40;\n\n// Row-hover tint for the PINNED (sticky) cells. The pinned column/marker sit OVER the\n// horizontally-scrolled body, so their hover background must be fully OPAQUE — a translucent\n// `bg-muted/50` (as used on the row itself) would let the scrolled-away cells bleed through the\n// pinned column on hover. `color-mix` precomputes the SAME tint as opaque: 50% muted over the\n// surface, so the pinned column matches the row exactly while staying solid. Theme-safe (the raw\n// `--muted`/`--background` vars flip in dark mode). Uses raw vars, not `--color-*`, because the UI\n// theme is `@theme inline` (the `--color-*` aliases aren't emitted at runtime).\nconst PINNED_HOVER_BG = 'group-hover:bg-[color-mix(in_oklab,var(--muted)_50%,var(--background))]';\n\ntype SheetsTable = Table<SheetsTableFeatures, SheetsRow>;\ntype SheetsTableCell = Cell<SheetsTableFeatures, SheetsRow, unknown>;\ntype SheetsTableColumn = Column<SheetsTableFeatures, SheetsRow, unknown>;\n\n/** Sorting state mirror (the shell owns it via useGridState — `id:null` = unsorted). */\nexport interface GridViewportSorting {\n\tid: string | null;\n\tdesc: boolean;\n}\n\n/** Per-cell layout context handed to the host alongside the v9 cell. */\nexport interface RenderCellContext {\n\trowIndex: number;\n\tcolumnIndex: number;\n\t/** True for the sticky column, painted outside the h-virtual window. */\n\tisStickyColumn: boolean;\n\t/** True when this cell is the active (keyboard cursor) cell. Drives the focus ring. */\n\tisActive: boolean;\n}\n\nexport type RenderCell = (cell: SheetsTableCell, ctx: RenderCellContext) => React.ReactNode;\n\n/** Imperative handle for the later SheetsHandle scrollToRow path. */\nexport interface GridViewportHandle {\n\tscrollToIndex: (rowIndex: number) => void;\n\t/** Scroll the given cell into view (row + column virtualizers). Used by keyboard nav. */\n\tscrollToCell: (columnIndex: number, rowIndex: number) => void;\n}\n\n/** Visible row window (overscan-inclusive) reported to the shell for infinite-scroll prefetch. */\nexport interface VisibleRange {\n\tstartIndex: number;\n\tendIndex: number;\n}\n\nexport interface GridViewportProps {\n\ttable: SheetsTable;\n\trenderCell: RenderCell;\n\thandleRef?: Ref<GridViewportHandle>;\n\t/**\n\t * Fired on the scroll root's `scroll`. The DOM grid uses this to close (commit-or-\n\t * dismiss) any open overlay editor: a virtualized cell anchor can unmount under\n\t * scroll, so Phase-4 closes rather than re-positions against a stale rect.\n\t */\n\tonScroll?: (e: React.UIEvent<HTMLDivElement>) => void;\n\t/** Sort caret state for the header. Defaults to unsorted (`{ id: null, desc: false }`). */\n\tsorting?: GridViewportSorting;\n\t/** Toggle sort for a column. The shell wires this to onHeaderClicked / toggleSorting. */\n\tonHeaderClick?: (colKey: string) => void;\n\t/**\n\t * Commit a column width from the header drag-resize handle. When provided, the handle\n\t * drives a manual pointer-drag against this (shell sizing lives in useGridState). When\n\t * omitted, the handle falls back to the v9 `header.getResizeHandler()` (columnResizeMode\n\t * 'onChange' feeds the table's own columnSizing state).\n\t */\n\tonResize?: (colKey: string, width: number) => void;\n\t/**\n\t * Total row count for the VERTICAL virtualizer. Defaults to the table's row-model length.\n\t * Infinite scroll passes the server total here so the scrollbar spans every (lazily loaded)\n\t * row — the table's `data` is the same-length proxy, so this matches `rows.length` in practice\n\t * but is threaded explicitly so the shell stays the single source of truth for row count.\n\t */\n\tcount?: number;\n\t/**\n\t * Fired (effect-free, via the row virtualizer's `onChange`) with the current overscan-inclusive\n\t * visible window. The shell maps this to the canvas `onVisibleRegionChanged({ y, height })` so\n\t * infinite-scroll prefetch runs identically. Omitted in paginated mode.\n\t */\n\tonVisibleRangeChange?: (range: VisibleRange) => void;\n\t/**\n\t * Optional leading checkbox / select-all column (glide's `rowMarkers` analogue). When supplied,\n\t * a sticky MARKER column (fixed {@link MARKER_WIDTH}px) is painted to the LEFT of the sticky col0,\n\t * driving the canonical {@link SheetsSelection} RangeSet. When OMITTED, the grid renders exactly as\n\t * before (no marker column) so existing tests/stories that pass no rowMarker are unaffected.\n\t */\n\trowMarker?: RowMarker;\n\t/** Active (keyboard cursor) cell `[col, row]`. Drives the per-cell focus ring + aria-activedescendant. */\n\tactiveCell?: [number, number];\n\t/** Active range (cell coords) — rendered as an inert pointer-events-none band overlay. P2 populates it. */\n\tactiveRange?: SelectionRect;\n\t/** Keydown handler for the grid root — the shell owns spreadsheet nav (arrows / Enter / F2). */\n\tonGridKeyDown?: (e: React.KeyboardEvent) => void;\n\t/**\n\t * Native clipboard handlers for the grid root. They fire only when the root (tabIndex=0) holds\n\t * focus and an overlay editor is NOT open (the editor owns its own clipboard while editing). The\n\t * shell routes each to the `clipboard.copy`/`cut`/`paste` command through the ONE dispatch pipeline.\n\t */\n\tonCopy?: (e: React.ClipboardEvent) => void;\n\tonCut?: (e: React.ClipboardEvent) => void;\n\tonPaste?: (e: React.ClipboardEvent) => void;\n\t/** DOM id of the active cell node, mirrored to `aria-activedescendant` on the grid root. */\n\tactiveDescendantId?: string;\n\t/**\n\t * Fired on a fill-handle (nub) drag RELEASE when the dropped cell extends the source range.\n\t * `sourceRange` is the active range (or a 1×1 rect at the active cell) the drag started from;\n\t * `target` is the `[col,row]` under the pointer at release (clamped to grid bounds). The shell\n\t * routes this to the `fill.drag` command. Omitted = no nub rendered.\n\t */\n\tonFillDrag?: (sourceRange: SelectionRect, target: [number, number]) => void;\n\tclassName?: string;\n}\n\n/** Selection wiring for the leading checkbox column. The shell derives this from SheetsSelection. */\nexport interface RowMarker {\n\t/** True when row `rowIndex` is in the canonical selection. */\n\tisSelected: (rowIndex: number) => boolean;\n\t/** Toggle row `rowIndex`; `shiftKey` requests a contiguous range-select from the last anchor. */\n\tonToggleRow: (rowIndex: number, shiftKey: boolean) => void;\n\t/** Every row selected — the header checkbox shows checked. */\n\tallSelected: boolean;\n\t/** Some (but not all) rows selected — the header checkbox shows indeterminate. */\n\tsomeSelected: boolean;\n\t/** Select-all / clear-all from the header checkbox. */\n\tonToggleAll: () => void;\n}\n\nfunction cellForColumnIndex(row: Row<SheetsTableFeatures, SheetsRow>, columnIndex: number): SheetsTableCell {\n\treturn row.getAllCells()[columnIndex];\n}\n\n/**\n * Project a half-open active {@link SelectionRect} (cell coords) into px box geometry for\n * the inert range-band overlay. X/width sum `columns[i].getSize()` across the spanned cols\n * (honoring the leading `markerWidth` offset); Y/height use the uniform ESTIMATED_ROW_HEIGHT.\n * INERT in P1 (nothing sets `activeRange`); wired so P2 just populates `current.range`.\n */\nfunction rangeBandStyle(range: SelectionRect, columns: SheetsTableColumn[], markerWidth: number): React.CSSProperties {\n\tlet left = markerWidth;\n\tfor (let i = 0; i < range.x && i < columns.length; i++) left += columns[i].getSize();\n\tlet width = 0;\n\tfor (let i = range.x; i < range.x + range.width && i < columns.length; i++) width += columns[i].getSize();\n\treturn {\n\t\ttransform: `translate(${left}px, ${range.y * ESTIMATED_ROW_HEIGHT}px)`,\n\t\twidth,\n\t\theight: range.height * ESTIMATED_ROW_HEIGHT\n\t};\n}\n\n/** Side of the square fill-handle nub (px). Centered on the source rect's bottom-right corner. */\nconst FILL_NUB_SIZE = 8;\n\n/**\n * Position the fill-handle nub centered on the BOTTOM-RIGHT corner of the source {@link SelectionRect}.\n * Reuses {@link rangeBandStyle}'s left/width math (column-width sum + markerWidth) so the nub tracks\n * scroll in the SAME body coordinate space as the range band; the corner is `(left+width, top+height)`.\n */\nfunction fillNubStyle(source: SelectionRect, columns: SheetsTableColumn[], markerWidth: number): React.CSSProperties {\n\tlet left = markerWidth;\n\tfor (let i = 0; i < source.x && i < columns.length; i++) left += columns[i].getSize();\n\tlet width = 0;\n\tfor (let i = source.x; i < source.x + source.width && i < columns.length; i++) width += columns[i].getSize();\n\tconst right = left + width;\n\tconst bottom = (source.y + source.height) * ESTIMATED_ROW_HEIGHT;\n\treturn {\n\t\ttransform: `translate(${right - FILL_NUB_SIZE / 2}px, ${bottom - FILL_NUB_SIZE / 2}px)`,\n\t\twidth: FILL_NUB_SIZE,\n\t\theight: FILL_NUB_SIZE\n\t};\n}\n\n/**\n * Hit-test a client pointer position to a `[col, row]` cell index over the virtualized body.\n *\n * Converts to CONTENT space (add the scroll element's scroll offset, subtract its bounding-rect\n * origin), then: X walks the per-column widths from the leading `markerWidth` to find the column\n * whose band the pointer is over; Y subtracts the sticky `headerHeight` and floors by the uniform\n * `rowHeight`. Both axes CLAMP to `[0, count-1]` so a drag past the grid edge lands on the last\n * cell. PURE (takes the geometry, returns indices) — testable without a DOM.\n */\nexport function hitTestCell(\n\tclientX: number,\n\tclientY: number,\n\tgeom: {\n\t\trect: { left: number; top: number };\n\t\tscrollLeft: number;\n\t\tscrollTop: number;\n\t\tmarkerWidth: number;\n\t\theaderHeight: number;\n\t\trowHeight: number;\n\t\tcolWidths: readonly number[];\n\t\trowCount: number;\n\t},\n): [number, number] {\n\tconst { rect, scrollLeft, scrollTop, markerWidth, headerHeight, rowHeight, colWidths, rowCount } = geom;\n\t// Column: walk widths in content space from the marker offset.\n\tconst localX = clientX - rect.left + scrollLeft - markerWidth;\n\tlet col = 0;\n\tlet acc = 0;\n\tfor (let i = 0; i < colWidths.length; i++) {\n\t\tacc += colWidths[i];\n\t\tif (localX < acc) {\n\t\t\tcol = i;\n\t\t\tbreak;\n\t\t}\n\t\tcol = i;\n\t}\n\tcol = Math.max(0, Math.min(col, colWidths.length - 1));\n\t// Row: subtract the sticky header, floor by the uniform row height.\n\tconst localY = clientY - rect.top + scrollTop - headerHeight;\n\tlet row = Math.floor(localY / rowHeight);\n\trow = Math.max(0, Math.min(row, rowCount - 1));\n\treturn [col, row];\n}\n\n/** Index of the start-pinned column, else the first column (sticky-by-default). */\nfunction findStickyColumnIndex(columns: SheetsTableColumn[]): number {\n\tconst pinned = columns.findIndex((col) => col.getIsPinned() === 'start');\n\treturn pinned >= 0 ? pinned : columns.length > 0 ? 0 : -1;\n}\n\n/** Header label: shell meta title -> string header -> column id. `meta` is the empty v9 type, so read it loosely. */\nfunction columnTitle(column: SheetsTableColumn): string {\n\tconst meta = column.columnDef.meta as { title?: string } | undefined;\n\tif (meta?.title) return meta.title;\n\tconst header = column.columnDef.header;\n\tif (typeof header === 'string') return header;\n\treturn column.id;\n}\n\ninterface HeaderCellProps {\n\tcolumn: SheetsTableColumn;\n\theader: import('@tanstack/react-table').Header<SheetsTableFeatures, SheetsRow, unknown>;\n\tsorting: GridViewportSorting;\n\tonHeaderClick?: (colKey: string) => void;\n\tonResize?: (colKey: string, width: number) => void;\n}\n\n/** A single header cell: title + sort caret (click toggles) + right-edge resize handle. */\nfunction HeaderCell({ column, header, sorting, onHeaderClick, onResize }: HeaderCellProps) {\n\tconst isSorted = sorting.id === column.id;\n\tconst direction: 'asc' | 'desc' | 'none' = isSorted ? (sorting.desc ? 'desc' : 'asc') : 'none';\n\n\tfunction onResizePointerDown(e: React.PointerEvent<HTMLDivElement>) {\n\t\t// Don't toggle sort while grabbing the handle, and don't select header text.\n\t\te.preventDefault();\n\t\te.stopPropagation();\n\t\tif (onResize) {\n\t\t\tconst startX = e.clientX;\n\t\t\tconst startWidth = column.getSize();\n\t\t\tconst onMove = (move: PointerEvent) => onResize(column.id, Math.max(40, startWidth + (move.clientX - startX)));\n\t\t\tconst onUp = () => {\n\t\t\t\twindow.removeEventListener('pointermove', onMove);\n\t\t\t\twindow.removeEventListener('pointerup', onUp);\n\t\t\t};\n\t\t\twindow.addEventListener('pointermove', onMove);\n\t\t\twindow.addEventListener('pointerup', onUp);\n\t\t\treturn;\n\t\t}\n\t\t// Fall back to the v9 feature handler (columnResizeMode 'onChange').\n\t\theader.getResizeHandler()(e.nativeEvent);\n\t}\n\n\treturn (\n\t\t<div\n\t\t\trole='columnheader'\n\t\t\tdata-part-id='sheets-header-cell'\n\t\t\tdata-col-key={column.id}\n\t\t\taria-sort={direction === 'asc' ? 'ascending' : direction === 'desc' ? 'descending' : 'none'}\n\t\t\tonClick={() => onHeaderClick?.(column.id)}\n\t\t\tclassName={cn(\n\t\t\t\t'group relative flex h-full w-full select-none items-center gap-1 border-b border-border bg-background px-3 text-xs font-medium text-muted-foreground',\n\t\t\t\tonHeaderClick && 'cursor-pointer hover:bg-muted/50 hover:text-foreground'\n\t\t\t)}\n\t\t>\n\t\t\t<span className='truncate'>{columnTitle(column)}</span>\n\t\t\t<SortCaret direction={direction} />\n\t\t\t<div\n\t\t\t\trole='separator'\n\t\t\t\taria-orientation='vertical'\n\t\t\t\tdata-part-id='sheets-resize-handle'\n\t\t\t\tonClick={(e) => e.stopPropagation()}\n\t\t\t\tonPointerDown={onResizePointerDown}\n\t\t\t\tclassName='absolute right-0 top-0 h-full w-1 cursor-col-resize touch-none select-none bg-transparent hover:bg-primary/50'\n\t\t\t/>\n\t\t</div>\n\t);\n}\n\n/** Up/down/neutral sort caret (inline SVG, no icon-lib dep — matches the package's glyph style). */\nfunction SortCaret({ direction }: { direction: 'asc' | 'desc' | 'none' }) {\n\treturn (\n\t\t<svg\n\t\t\tdata-part-id='sheets-sort-caret'\n\t\t\tdata-direction={direction}\n\t\t\twidth='8'\n\t\t\theight='8'\n\t\t\tviewBox='0 0 8 8'\n\t\t\taria-hidden='true'\n\t\t\tclassName={cn('ml-auto shrink-0', direction === 'none' && 'opacity-30')}\n\t\t>\n\t\t\t{direction === 'desc' ? <path d='M0 2 L4 6 L8 2 Z' fill='currentColor' /> : <path d='M0 6 L4 2 L8 6 Z' fill='currentColor' />}\n\t\t</svg>\n\t);\n}\n\n/** Header marker cell: the select-all checkbox (checked = all, indeterminate = some). */\nfunction RowMarkerHeaderCell({ rowMarker }: { rowMarker: RowMarker }) {\n\treturn (\n\t\t<div\n\t\t\trole='columnheader'\n\t\t\tdata-part-id='sheets-row-marker-header'\n\t\t\tdata-slot='row-marker-header'\n\t\t\tclassName='flex h-full w-full select-none items-center justify-center border-b border-border bg-background'\n\t\t>\n\t\t\t<Checkbox\n\t\t\t\tchecked={rowMarker.allSelected}\n\t\t\t\tindeterminate={rowMarker.someSelected}\n\t\t\t\tonClick={() => rowMarker.onToggleAll()}\n\t\t\t\taria-label={rowMarker.allSelected ? 'Deselect all rows' : 'Select all rows'}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n\n/** Body marker cell per row: a checkbox reflecting selection; click (with shiftKey) drives the toggle. */\nfunction RowMarkerCell({ rowIndex, rowMarker }: { rowIndex: number; rowMarker: RowMarker }) {\n\tconst selected = rowMarker.isSelected(rowIndex);\n\t// Reveal-on-hover (DESIGN_SPEC §9): checkbox is hidden until the row is hovered, but stays\n\t// visible once this row is checked OR any selection is active (so multi-select stays legible).\n\tconst reveal = selected || rowMarker.someSelected || rowMarker.allSelected;\n\treturn (\n\t\t<div\n\t\t\tdata-part-id='sheets-row-marker-cell'\n\t\t\tdata-slot='row-marker-cell'\n\t\t\t// Stop the click from bubbling into the row (which would also start a cell edit).\n\t\t\tonClick={(e) => e.stopPropagation()}\n\t\t\tonDoubleClick={(e) => e.stopPropagation()}\n\t\t\tclassName={`flex h-full w-full select-none items-center justify-center bg-background ${PINNED_HOVER_BG}`}\n\t\t>\n\t\t\t<Checkbox\n\t\t\t\tchecked={selected}\n\t\t\t\t// base-ui Checkbox renders a <button>; onClick carries the native shiftKey for range-select.\n\t\t\t\tonClick={(e) => rowMarker.onToggleRow(rowIndex, e.shiftKey)}\n\t\t\t\taria-label={`Select row ${rowIndex}`}\n\t\t\t\tclassName={cn(!reveal && 'opacity-0 transition-opacity group-hover:opacity-100 motion-reduce:transition-none')}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n\nexport function GridViewport({\n\ttable,\n\trenderCell,\n\thandleRef,\n\tonScroll,\n\tsorting = { id: null, desc: false },\n\tonHeaderClick,\n\tonResize,\n\tcount,\n\tonVisibleRangeChange,\n\trowMarker,\n\tactiveCell,\n\tactiveRange,\n\tonGridKeyDown,\n\tonCopy,\n\tonCut,\n\tonPaste,\n\tactiveDescendantId,\n\tonFillDrag,\n\tclassName\n}: GridViewportProps) {\n\tconst scrollRef = useRef<HTMLDivElement>(null);\n\n\tconst rows = table.getRowModel().rows;\n\tconst columns = table.getAllLeafColumns();\n\n\t// Report the visible window WITHOUT an effect: the virtualizer's `onChange` fires on every\n\t// recompute (scroll/resize/measure) with the live instance, whose `.range` is the overscan-\n\t// inclusive {startIndex,endIndex}. Keep the ref current each render so the latch never goes stale.\n\tconst onVisibleRangeChangeRef = useRef(onVisibleRangeChange);\n\tonVisibleRangeChangeRef.current = onVisibleRangeChange;\n\n\tconst rowVirtualizer = useVirtualizer({\n\t\tcount: count ?? rows.length,\n\t\tgetScrollElement: () => scrollRef.current,\n\t\testimateSize: () => ESTIMATED_ROW_HEIGHT,\n\t\toverscan: ROW_OVERSCAN,\n\t\tonChange: (instance) => {\n\t\t\tconst range = instance.range;\n\t\t\tif (range) onVisibleRangeChangeRef.current?.({ startIndex: range.startIndex, endIndex: range.endIndex });\n\t\t}\n\t});\n\n\tconst columnVirtualizer = useVirtualizer({\n\t\thorizontal: true,\n\t\tcount: columns.length,\n\t\tgetScrollElement: () => scrollRef.current,\n\t\testimateSize: (index) => columns[index].getSize(),\n\t\tgetItemKey: (index) => columns[index]?.id ?? index,\n\t\toverscan: COLUMN_OVERSCAN\n\t});\n\n\tuseImperativeHandle(\n\t\thandleRef,\n\t\t() => ({\n\t\t\tscrollToIndex: (rowIndex: number) => rowVirtualizer.scrollToIndex(rowIndex),\n\t\t\tscrollToCell: (columnIndex: number, rowIndex: number) => {\n\t\t\t\trowVirtualizer.scrollToIndex(rowIndex);\n\t\t\t\tcolumnVirtualizer.scrollToIndex(columnIndex);\n\t\t\t}\n\t\t}),\n\t\t[rowVirtualizer, columnVirtualizer]\n\t);\n\n\tconst stickyIndex = findStickyColumnIndex(columns);\n\tconst hasStickyColumn = stickyIndex >= 0;\n\tconst stickyColumn = hasStickyColumn ? columns[stickyIndex] : undefined;\n\tconst stickyWidth = stickyColumn ? stickyColumn.getSize() : 0;\n\tconst stickyHeader = stickyColumn ? table.getLeafHeaders().find((h) => h.column.id === stickyColumn.id) : undefined;\n\tconst headersByColumnId = useMemo(() => new Map(table.getLeafHeaders().map((h) => [h.column.id, h])), [table, columns]);\n\n\tconst totalWidth = columnVirtualizer.getTotalSize();\n\tconst virtualColumns = columnVirtualizer.getVirtualItems();\n\n\t// The optional leading marker column shifts EVERYTHING right by MARKER_WIDTH: the sticky col0\n\t// pins at `left: markerWidth` (the marker owns `left: 0`), virtualized columns translate by an\n\t// extra markerWidth, and the header/body content width grows by markerWidth. When no rowMarker\n\t// is supplied, markerWidth is 0 and the layout is byte-identical to before.\n\tconst markerWidth = rowMarker ? MARKER_WIDTH : 0;\n\tconst contentWidth = totalWidth + markerWidth;\n\n\t// Fill-handle SOURCE rect: the active range, else a 1×1 rect at the active cell. Drives the nub\n\t// position (its bottom-right corner) and is the `from` handed to onFillDrag. Absent when neither.\n\tconst fillSource: SelectionRect | undefined = onFillDrag\n\t\t? activeRange ?? (activeCell ? { x: activeCell[0], y: activeCell[1], width: 1, height: 1 } : undefined)\n\t\t: undefined;\n\n\tfunction onFillNubPointerDown(e: React.PointerEvent<HTMLDivElement>) {\n\t\t// Don't start a cell selection / text-select while grabbing the nub.\n\t\te.preventDefault();\n\t\te.stopPropagation();\n\t\tif (!onFillDrag || !fillSource) return;\n\t\tconst source = fillSource;\n\t\tconst scrollEl = scrollRef.current;\n\t\tif (!scrollEl) return;\n\t\tconst colWidths = columns.map((c) => c.getSize());\n\t\tlet target: [number, number] = [source.x + source.width - 1, source.y + source.height - 1];\n\t\tconst onMove = (move: PointerEvent) => {\n\t\t\tconst rect = scrollEl.getBoundingClientRect();\n\t\t\ttarget = hitTestCell(move.clientX, move.clientY, {\n\t\t\t\trect: { left: rect.left, top: rect.top },\n\t\t\t\tscrollLeft: scrollEl.scrollLeft,\n\t\t\t\tscrollTop: scrollEl.scrollTop,\n\t\t\t\tmarkerWidth,\n\t\t\t\theaderHeight: HEADER_HEIGHT,\n\t\t\t\trowHeight: ESTIMATED_ROW_HEIGHT,\n\t\t\t\tcolWidths,\n\t\t\t\trowCount: count ?? rows.length\n\t\t\t});\n\t\t};\n\t\tconst onUp = () => {\n\t\t\twindow.removeEventListener('pointermove', onMove);\n\t\t\twindow.removeEventListener('pointerup', onUp);\n\t\t\tonFillDrag(source, target);\n\t\t};\n\t\twindow.addEventListener('pointermove', onMove);\n\t\twindow.addEventListener('pointerup', onUp);\n\t}\n\n\treturn (\n\t\t<div\n\t\t\tref={scrollRef}\n\t\t\tdata-impl='dom'\n\t\t\tdata-part-id='sheets-viewport'\n\t\t\trole='grid'\n\t\t\ttabIndex={0}\n\t\t\tonScroll={onScroll}\n\t\t\tonKeyDown={(e) => onGridKeyDown?.(e)}\n\t\t\tonCopy={onCopy}\n\t\t\tonCut={onCut}\n\t\t\tonPaste={onPaste}\n\t\t\taria-activedescendant={activeDescendantId}\n\t\t\taria-rowcount={count ?? rows.length}\n\t\t\taria-colcount={columns.length}\n\t\t\tclassName={cn('relative h-full w-full overflow-auto outline-none', className)}\n\t\t>\n\t\t\t{/* Sticky HEADER band — same column layout as the body. */}\n\t\t\t<div\n\t\t\t\trole='row'\n\t\t\t\tdata-part-id='sheets-header-row'\n\t\t\t\tclassName='sticky top-0 z-30 flex bg-background'\n\t\t\t\tstyle={{ height: HEADER_HEIGHT, width: contentWidth }}\n\t\t\t>\n\t\t\t\t{rowMarker && (\n\t\t\t\t\t<div className='sticky left-0 z-40 flex shrink-0' style={{ width: markerWidth, height: '100%' }}>\n\t\t\t\t\t\t<RowMarkerHeaderCell rowMarker={rowMarker} />\n\t\t\t\t\t</div>\n\t\t\t\t)}\n\t\t\t\t{stickyColumn && stickyHeader && (\n\t\t\t\t\t<div className='sticky z-40 flex shrink-0 border-r border-border' style={{ left: markerWidth, width: stickyWidth, height: '100%' }}>\n\t\t\t\t\t\t<HeaderCell\n\t\t\t\t\t\t\tcolumn={stickyColumn}\n\t\t\t\t\t\t\theader={stickyHeader}\n\t\t\t\t\t\t\tsorting={sorting}\n\t\t\t\t\t\t\tonHeaderClick={onHeaderClick}\n\t\t\t\t\t\t\tonResize={onResize}\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>\n\t\t\t\t)}\n\t\t\t\t{virtualColumns.map((virtualCol) => {\n\t\t\t\t\tif (virtualCol.index === stickyIndex) return null; // sticky header painted above\n\t\t\t\t\tconst column = columns[virtualCol.index];\n\t\t\t\t\tconst header = headersByColumnId.get(column.id);\n\t\t\t\t\tif (!header) return null;\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tkey={virtualCol.key}\n\t\t\t\t\t\t\tclassName='absolute top-0 flex'\n\t\t\t\t\t\t\tstyle={{ transform: `translateX(${virtualCol.start + markerWidth}px)`, width: virtualCol.size, height: '100%' }}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<HeaderCell\n\t\t\t\t\t\t\t\tcolumn={column}\n\t\t\t\t\t\t\t\theader={header}\n\t\t\t\t\t\t\t\tsorting={sorting}\n\t\t\t\t\t\t\t\tonHeaderClick={onHeaderClick}\n\t\t\t\t\t\t\t\tonResize={onResize}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t);\n\t\t\t\t})}\n\t\t\t</div>\n\n\t\t\t{/* BODY — virtualized rows × columns. */}\n\t\t\t<div style={{ height: rowVirtualizer.getTotalSize(), width: contentWidth, position: 'relative' }}>\n\t\t\t\t{rowVirtualizer.getVirtualItems().map((virtualRow) => {\n\t\t\t\t\tconst row = rows[virtualRow.index];\n\t\t\t\t\t// Defensive: when `count` (server total) leads the loaded `rows` window, the proxy\n\t\t\t\t\t// should still back every index — but guard the off-by-one race rather than crash.\n\t\t\t\t\tif (!row) return null;\n\t\t\t\t\tconst rowSelected = rowMarker?.isSelected(virtualRow.index) ?? false;\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tkey={virtualRow.key}\n\t\t\t\t\t\t\trole='row'\n\t\t\t\t\t\t\tdata-index={virtualRow.index}\n\t\t\t\t\t\t\tdata-row={virtualRow.index}\n\t\t\t\t\t\t\tdata-selected={rowSelected || undefined}\n\t\t\t\t\t\t\taria-rowindex={virtualRow.index + 1}\n\t\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t'group absolute left-0 top-0 flex border-b border-border',\n\t\t\t\t\t\t\trowSelected ? 'bg-primary/5' : 'hover:bg-muted/50'\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t\tstyle={{ transform: `translateY(${virtualRow.start}px)`, height: ESTIMATED_ROW_HEIGHT, width: '100%' }}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{rowMarker && (\n\t\t\t\t\t\t\t\t<div className='sticky left-0 z-20 flex shrink-0' style={{ width: markerWidth }}>\n\t\t\t\t\t\t\t\t\t<RowMarkerCell rowIndex={virtualRow.index} rowMarker={rowMarker} />\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t{hasStickyColumn && (\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclassName={`sticky z-10 flex shrink-0 border-r border-border bg-background ${PINNED_HOVER_BG}`}\n\t\t\t\t\t\t\t\t\tdata-col={stickyIndex}\n\t\t\t\t\t\t\t\t\taria-colindex={stickyIndex + 1}\n\t\t\t\t\t\t\t\t\tstyle={{ left: markerWidth, width: stickyWidth }}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{renderCell(cellForColumnIndex(row, stickyIndex), {\n\t\t\t\t\t\t\t\t\t\trowIndex: virtualRow.index,\n\t\t\t\t\t\t\t\t\t\tcolumnIndex: stickyIndex,\n\t\t\t\t\t\t\t\t\t\tisStickyColumn: true,\n\t\t\t\t\t\t\t\t\t\tisActive: activeCell?.[0] === stickyIndex && activeCell?.[1] === virtualRow.index\n\t\t\t\t\t\t\t\t\t})}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t{virtualColumns.map((virtualCol) => {\n\t\t\t\t\t\t\t\tif (virtualCol.index === stickyIndex) return null; // sticky col painted by the element above\n\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\tkey={virtualCol.key}\n\t\t\t\t\t\t\t\t\t\tclassName='absolute top-0 flex'\n\t\t\t\t\t\t\t\t\t\tdata-col={virtualCol.index}\n\t\t\t\t\t\t\t\t\t\taria-colindex={virtualCol.index + 1}\n\t\t\t\t\t\t\t\t\t\tstyle={{ transform: `translateX(${virtualCol.start + markerWidth}px)`, width: virtualCol.size, height: '100%' }}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{renderCell(cellForColumnIndex(row, virtualCol.index), {\n\t\t\t\t\t\t\t\t\t\t\trowIndex: virtualRow.index,\n\t\t\t\t\t\t\t\t\t\t\tcolumnIndex: virtualCol.index,\n\t\t\t\t\t\t\t\t\t\t\tisStickyColumn: false,\n\t\t\t\t\t\t\t\t\t\t\tisActive: activeCell?.[0] === virtualCol.index && activeCell?.[1] === virtualRow.index\n\t\t\t\t\t\t\t\t\t\t})}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t})}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t);\n\t\t\t\t})}\n\t\t\t\t{activeRange && (\n\t\t\t\t\t<div\n\t\t\t\t\t\tdata-part-id='sheets-range-band'\n\t\t\t\t\t\taria-hidden='true'\n\t\t\t\t\t\tclassName='pointer-events-none absolute z-[5] border border-primary/50 bg-primary/10'\n\t\t\t\t\t\tstyle={rangeBandStyle(activeRange, columns, markerWidth)}\n\t\t\t\t\t/>\n\t\t\t\t)}\n\t\t\t\t{fillSource && (\n\t\t\t\t\t<div\n\t\t\t\t\t\tdata-part-id='sheets-fill-handle'\n\t\t\t\t\t\trole='button'\n\t\t\t\t\t\taria-label='Fill handle'\n\t\t\t\t\t\tonPointerDown={onFillNubPointerDown}\n\t\t\t\t\t\tclassName='absolute z-10 cursor-crosshair touch-none select-none rounded-[1px] border border-background bg-primary'\n\t\t\t\t\t\tstyle={fillNubStyle(fillSource, columns, markerWidth)}\n\t\t\t\t\t/>\n\t\t\t\t)}\n\t\t\t</div>\n\t\t</div>\n\t);\n}\n","// The DOM cell host — the `getCellContent` → React port. Given a v9 cell it asks\n// the injected resolver for the {@link SheetsCellResolution} ({ cell, component? })\n// and renders the consumer component when present, else dispatches on the neutral\n// `kind` to the matching built-in view (cell-model/views/*).\n//\n// Phase 3 replaces the Phase-1 value→kind STOPGAP (`deriveSheetsCell`) with\n// registry-driven resolution: the host no longer guesses a kind from the JS value\n// — `getSheetsCellContent(rowIndex, colKey)` runs the full `createCellContent` →\n// `toSheetsCell` routing and (when the consumer registered a `cellComponent` for\n// the resolved typeKey) hands back the component to render instead of a built-in\n// view. SheetsDomInner injects the resolver via the `renderCell` closure.\n//\n// The kind→view map covers every native SheetsCellKind. datetime/interval cells\n// carry kind 'text' (formatted text in v1), so they route through TextCellView\n// alongside the grid-internal kinds (loading/draft-action/custom); their dedicated\n// DateTimeCellView/IntervalCellView stay exported for per-typeKey use later.\n// Dependency-light: local `cn` only, with no shared primitive dependency.\nimport { memo, useCallback, useRef } from 'react';\nimport type React from 'react';\nimport type { Cell } from '@tanstack/react-table';\n\nimport { cn } from '../utils/cn';\nimport { getDraftMeta, type SheetsRow } from '../grid/row-model';\nimport { DRAFT_ACTION_COLUMN_KEY } from '../grid/sheets.constants';\nimport type { SheetsTableFeatures } from '../table/features';\nimport type { RenderCellContext } from '../table/grid-viewport';\nimport type { CellProps } from '../cell-model/cell-props';\nimport { BadgesCellView } from '../cell-model/views/badges-view';\nimport { BooleanCellView } from '../cell-model/views/boolean-view';\nimport { DraftActionCellView, type DraftActionStatus } from '../cell-model/views/draft-action-view';\nimport { GeometryCellView } from '../cell-model/views/geometry-view';\nimport { ImageCellView } from '../cell-model/views/image-view';\nimport { LoadingCellView } from '../cell-model/views/loading-view';\nimport { NumberCellView } from '../cell-model/views/number-view';\nimport { RelationCellView } from '../cell-model/views/relation-view';\nimport { TextCellView } from '../cell-model/views/text-view';\nimport { UriCellView } from '../cell-model/views/uri-view';\nimport { InlineCellEditor } from './inline-cell-editor';\nimport type { SheetsCellResolution } from './use-sheets-content';\n\ntype SheetsTableCell = Cell<SheetsTableFeatures, SheetsRow, unknown>;\n\n/** Native DOM content resolver injected by the shell — mirrors `getCellContent`. */\nexport type GetSheetsCellContent = (rowIndex: number, colKey: string) => SheetsCellResolution;\n\n/**\n * Open the native overlay editor for a cell. Threaded from `SheetsDomInner` through\n * `renderCell` so only the host knows the cell's DOM node (it measures the anchor\n * rect off `getBoundingClientRect`). Phase-4 additive — the canvas path is untouched.\n */\nexport type OpenEditor = (rowIndex: number, colKey: string, anchorRect: DOMRect, initialText?: string) => void;\n\n/**\n * Submit a client-side draft row by its draft id. Threaded from `SheetsDomInner` (the\n * shell's `submitDraftRow`) so the draft-action cell's REAL `<Button>` can wire its\n * onClick. Phase-7 Stage-4 consumes it; Stage-2 only plumbs it through.\n */\nexport type SubmitDraftRow = (draftRowId: string) => Promise<unknown>;\n\n// COMPLETE kind→view map. `loading` routes to its skeleton view; `draft-action` is\n// special-cased UPSTREAM (rendered as DraftActionCellView with explicit props, never\n// reaching here), so it — like `custom`/`text` — falls back to TextCellView if it ever does.\nfunction renderKindView(props: CellProps) {\n\tswitch (props.cell.kind) {\n\t\tcase 'number':\n\t\t\treturn <NumberCellView {...props} />;\n\t\tcase 'boolean':\n\t\t\treturn <BooleanCellView {...props} />;\n\t\tcase 'badges':\n\t\t\treturn <BadgesCellView {...props} />;\n\t\tcase 'uri':\n\t\t\treturn <UriCellView {...props} />;\n\t\tcase 'image':\n\t\t\treturn <ImageCellView {...props} />;\n\t\tcase 'geometry':\n\t\t\treturn <GeometryCellView {...props} />;\n\t\tcase 'relation':\n\t\t\treturn <RelationCellView {...props} />;\n\t\tcase 'loading':\n\t\t\treturn <LoadingCellView {...props} />;\n\t\tcase 'text':\n\t\tcase 'draft-action':\n\t\tcase 'custom':\n\t\tdefault:\n\t\t\treturn <TextCellView {...props} />;\n\t}\n}\n\n/** Explicit draft-action descriptor for a draft row, derived from its DraftMeta. */\ninterface DraftActionInfo {\n\tdraftRowId: string;\n\tstatus: DraftActionStatus;\n\terrored: boolean;\n\tdisabled: boolean;\n}\n\n/**\n * Derive the draft-action cell's props from a row's draft metadata — the DOM analogue\n * of the canvas draft-action-cell reading the draft slice. `errored`/`disabled` mirror\n * the canvas: an error status surfaces the red dot but keeps the button live (the canvas\n * painter never disabled on error); `saving` disables (DraftActionCellView also self-locks).\n */\nfunction deriveDraftActionInfo(row: SheetsRow | undefined): DraftActionInfo | null {\n\tconst meta = getDraftMeta(row);\n\tif (!meta) return null;\n\tconst status: DraftActionStatus = meta.status;\n\treturn { draftRowId: meta.draftRowId, status, errored: status === 'error', disabled: status === 'saving' };\n}\n\ninterface SheetsCellHostInnerProps {\n\tresolution: SheetsCellResolution;\n\trowId: string;\n\tcolKey: string;\n\trowIndex: number;\n\tcolumnIndex: number;\n\tvalue: unknown;\n\tisEditing: boolean;\n\t/** True when this is the active (keyboard cursor) cell — drives the focus ring + aria-selected + id. */\n\tisActive: boolean;\n\t/** Open the overlay editor for this cell; undefined on render paths without editing (e.g. tests). */\n\topenEditor?: OpenEditor;\n\t/** Type-to-edit seed for the inline editor (only meaningful when `isEditing`). */\n\tinlineInitialText?: string;\n\t/** Commit an inline (in-cell) edit. Set on the inline-edit render path; reuses the host's\n\t * value-commit pipeline (bulk-or-single). */\n\tonInlineCommit?: (rowIndex: number, colKey: string, value: unknown) => void;\n\t/** Cancel an inline (in-cell) edit — discards and closes. */\n\tonInlineCancel?: () => void;\n\t/** Park the active cell on this cell (click-to-activate). `shiftKey` extends the range from the\n\t * anchor instead of resetting it. Undefined on render paths without nav. */\n\tonActivateCell?: (col: number, row: number, shiftKey?: boolean) => void;\n\t/** Right-click this cell — opens the grid context menu anchored at the pointer. The grid first\n\t * activates the cell when it is outside the current selection, so the menu acts on it. */\n\tonContextMenu?: (col: number, row: number, clientX: number, clientY: number) => void;\n\t/** Submit a draft row by id — wired to the draft-action cell's Button (Stage 4). */\n\tonSubmitDraftRow?: SubmitDraftRow;\n\t/** Draft-action descriptor when this is the draft-action column of a draft row; null otherwise. */\n\tdraftAction?: DraftActionInfo | null;\n\tclassName?: string;\n}\n\n/** Build the full {@link CellProps} for a resolved cell. `onStartEdit` is supplied by the host. */\nfunction toCellProps(props: SheetsCellHostInnerProps, onStartEdit: () => void): CellProps {\n\tconst { cell } = props.resolution;\n\treturn {\n\t\tcell,\n\t\tvalue: props.value,\n\t\tcolKey: props.colKey,\n\t\trowId: props.rowId,\n\t\trowIndex: props.rowIndex,\n\t\tcolumn: { key: props.colKey, name: props.colKey, cellType: cell.meta?.cellType ?? 'unknown' },\n\t\tisEditing: props.isEditing,\n\t\tonStartEdit,\n\t\tdisabled: false,\n\t};\n}\n\n// Memoized on (rowId, colKey, value, isEditing, openEditor) — the DOM analogue of\n// glide's `updateCells`: only the changed cell re-renders, never the whole window.\n// The resolution is derived from the first four inputs, so they fully gate the\n// output; openEditor is added so the wrapper's handlers stay current.\nconst SheetsCellHostInner = memo(\n\tfunction SheetsCellHostInner(props: SheetsCellHostInnerProps) {\n\t\tconst wrapperRef = useRef<HTMLDivElement | null>(null);\n\n\t\t// Start editing anchored to THIS cell's DOM node — the host is the only place\n\t\t// that knows the cell's rect (read off getBoundingClientRect, viewport coords,\n\t\t// matching the OverlayManager's window.innerHeight assumption). No-op when the\n\t\t// cell is readonly or no openEditor was threaded in.\n\t\tconst startEdit = useCallback(() => {\n\t\t\tconst open = props.openEditor;\n\t\t\tconst el = wrapperRef.current;\n\t\t\tif (!open || !el || props.resolution.cell.readonly) return;\n\t\t\topen(props.rowIndex, props.colKey, el.getBoundingClientRect());\n\t\t}, [props.openEditor, props.rowIndex, props.colKey, props.resolution.cell.readonly]);\n\n\t\t// Click parks the active cell here (the grid root owns keys via aria-activedescendant).\n\t\t// A shift-click EXTENDS the cell range from the latched anchor instead of resetting it.\n\t\tconst onActivateCell = props.onActivateCell;\n\t\tconst columnIndex = props.columnIndex;\n\t\tconst cellRowIndex = props.rowIndex;\n\t\tconst activate = useCallback((e: React.MouseEvent) => {\n\t\t\tonActivateCell?.(columnIndex, cellRowIndex, e.shiftKey);\n\t\t}, [onActivateCell, columnIndex, cellRowIndex]);\n\n\t\t// Right-click: open the grid context menu at the pointer. preventDefault suppresses the\n\t\t// browser menu; the grid handler activates this cell first when it is outside the selection.\n\t\tconst onContextMenu = props.onContextMenu;\n\t\tconst contextMenu = useCallback((e: React.MouseEvent) => {\n\t\t\tif (!onContextMenu) return;\n\t\t\te.preventDefault();\n\t\t\tonContextMenu(columnIndex, cellRowIndex, e.clientX, e.clientY);\n\t\t}, [onContextMenu, columnIndex, cellRowIndex]);\n\n\t\tconst onSubmitDraftRow = props.onSubmitDraftRow;\n\t\tconst draftAction = props.draftAction;\n\t\tconst submitDraft = useCallback(() => {\n\t\t\tif (draftAction && onSubmitDraftRow) void onSubmitDraftRow(draftAction.draftRowId);\n\t\t}, [draftAction, onSubmitDraftRow]);\n\n\t\tconst cellProps = toCellProps(props, startEdit);\n\t\tconst Component = props.resolution.component;\n\t\tconst styleHint = props.resolution.cell.styleHint;\n\t\t// DOM equivalent of applyDraftDisabledStyle / applyDraftErrorStyle: a draft cell\n\t\t// fades (muted text + tinted bg); a per-cell error overrides with a red bg/text.\n\t\tconst draftClasses = cn(\n\t\t\tstyleHint?.draft && 'bg-muted/40 text-muted-foreground',\n\t\t\tstyleHint?.error && 'bg-destructive/10 text-destructive',\n\t\t);\n\t\t// The draft-action column renders the REAL <Button> (DraftActionCellView), which\n\t\t// takes its own prop shape — bypass the kind→view map and the value/editor wiring.\n\t\tconst isDraftActionCell = props.colKey === DRAFT_ACTION_COLUMN_KEY || props.resolution.cell.kind === 'draft-action';\n\t\t// Border wrapper carries the mouse activation handlers (click parks the active cell,\n\t\t// double-click opens the editor). Keys are owned by the grid root (aria-activedescendant\n\t\t// pattern), so the wrapper is NOT individually focusable. The gridcell role lives on the\n\t\t// built-in view (or the consumer component) inside, so the host adds no second role=\"gridcell\".\n\t\treturn (\n\t\t\t<div\n\t\t\t\tref={wrapperRef}\n\t\t\t\tid={`sheets-cell-${props.rowIndex}-${props.columnIndex}`}\n\t\t\t\taria-selected={props.isActive || undefined}\n\t\t\t\tonClick={activate}\n\t\t\t\tonDoubleClick={startEdit}\n\t\t\t\tonContextMenu={contextMenu}\n\t\t\t\tclassName={cn(\n\t\t\t\t\t'relative h-full w-full overflow-hidden outline-none',\n\t\t\t\t\tprops.isActive && 'z-20 ring-2 ring-inset ring-primary',\n\t\t\t\t\tdraftClasses,\n\t\t\t\t\tprops.className,\n\t\t\t\t)}\n\t\t\t>\n\t\t\t\t{isDraftActionCell ? (\n\t\t\t\t\tdraftAction ? (\n\t\t\t\t\t\t<DraftActionCellView\n\t\t\t\t\t\t\tstatus={draftAction.status}\n\t\t\t\t\t\t\terrored={draftAction.errored}\n\t\t\t\t\t\t\tdisabled={draftAction.disabled}\n\t\t\t\t\t\t\tonSubmit={submitDraft}\n\t\t\t\t\t\t/>\n\t\t\t\t\t) : null\n\t\t\t\t) : props.isEditing ? (\n\t\t\t\t\t// Inline (in-cell) edit for the simple text-representable types — a bare <input>\n\t\t\t\t\t// overlaying the view. `isEditing` is set true ONLY for inline-edit intents (the\n\t\t\t\t\t// shell short-circuits inline-toggle/overlay/none before here), so the cell kind is\n\t\t\t\t\t// always text or number → derive the numeric variant from it.\n\t\t\t\t\t<InlineCellEditor\n\t\t\t\t\t\tariaLabel={`Edit ${props.resolution.fieldMeta?.name ?? props.colKey}`}\n\t\t\t\t\t\tvalue={props.value}\n\t\t\t\t\t\tinitialText={props.inlineInitialText}\n\t\t\t\t\t\tnumeric={props.resolution.cell.kind === 'number'}\n\t\t\t\t\t\tonCommit={(next) => props.onInlineCommit?.(props.rowIndex, props.colKey, next)}\n\t\t\t\t\t\tonCancel={() => props.onInlineCancel?.()}\n\t\t\t\t\t/>\n\t\t\t\t) : Component ? (\n\t\t\t\t\t<Component {...cellProps} />\n\t\t\t\t) : (\n\t\t\t\t\trenderKindView(cellProps)\n\t\t\t\t)}\n\t\t\t</div>\n\t\t);\n\t},\n\t(prev, next) =>\n\t\tprev.rowId === next.rowId &&\n\t\tprev.colKey === next.colKey &&\n\t\tprev.value === next.value &&\n\t\tprev.isEditing === next.isEditing &&\n\t\t// initialText seeds the inline editor on open; it only differs for the editing cell.\n\t\tprev.inlineInitialText === next.inlineInitialText &&\n\t\tprev.onInlineCommit === next.onInlineCommit &&\n\t\tprev.onInlineCancel === next.onInlineCancel &&\n\t\t// isActive must gate the memo or the focus ring will not move between cells.\n\t\tprev.isActive === next.isActive &&\n\t\tprev.openEditor === next.openEditor &&\n\t\tprev.onActivateCell === next.onActivateCell &&\n\t\tprev.onContextMenu === next.onContextMenu &&\n\t\tprev.onSubmitDraftRow === next.onSubmitDraftRow &&\n\t\t// styleHint.draft/error and the draft-action status can flip while `value` is\n\t\t// unchanged (validation result arrives, save in flight), so gate on them too.\n\t\tprev.resolution.cell.styleHint?.draft === next.resolution.cell.styleHint?.draft &&\n\t\tprev.resolution.cell.styleHint?.error === next.resolution.cell.styleHint?.error &&\n\t\tsameDraftAction(prev.draftAction, next.draftAction)\n);\n\n/** Draft-action equality for the memo gate — status/errored/disabled drive the Button. */\nfunction sameDraftAction(a: DraftActionInfo | null | undefined, b: DraftActionInfo | null | undefined): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\treturn a.draftRowId === b.draftRowId && a.status === b.status && a.errored === b.errored && a.disabled === b.disabled;\n}\n\nexport interface SheetsCellHostProps {\n\tcell: SheetsTableCell;\n\tctx: RenderCellContext;\n\tgetSheetsCellContent: GetSheetsCellContent;\n\t/** Open the overlay editor for the activated cell (double-click; grid root owns Enter / F2). */\n\topenEditor?: OpenEditor;\n\t/** True when this cell is being edited IN PLACE (inline-edit intent); renders the bare <input>. */\n\tisEditing?: boolean;\n\t/** Type-to-edit seed for the inline editor (only meaningful when `isEditing`). */\n\tinlineInitialText?: string;\n\t/** Commit an inline (in-cell) edit — reuses the host value-commit pipeline. */\n\tonInlineCommit?: (rowIndex: number, colKey: string, value: unknown) => void;\n\t/** Cancel an inline (in-cell) edit. */\n\tonInlineCancel?: () => void;\n\t/** Park the active cell on click; `shiftKey` extends the cell range from the anchor. */\n\tonActivateCell?: (col: number, row: number, shiftKey?: boolean) => void;\n\t/** Right-click → open the grid context menu anchored at the pointer. */\n\tonContextMenu?: (col: number, row: number, clientX: number, clientY: number) => void;\n\t/** Submit a draft row by id — wired to the draft-action cell's Button (Stage 4). */\n\tonSubmitDraftRow?: SubmitDraftRow;\n\tclassName?: string;\n}\n\n/**\n * Render a v9 cell as DOM. Wire via the {@link GridViewport} `renderCell` closure,\n * which injects the shell's resolver: `(c, ctx) => <SheetsCellHost cell={c} ctx={ctx}\n * getSheetsCellContent={getSheetsCellContent} openEditor={openEditor} />`.\n */\nexport function SheetsCellHost({ cell, ctx, getSheetsCellContent, openEditor, isEditing, inlineInitialText, onInlineCommit, onInlineCancel, onActivateCell, onContextMenu, onSubmitDraftRow, className }: SheetsCellHostProps) {\n\tconst rowIndex = cell.row.index;\n\tconst colKey = cell.column.id;\n\tconst value = cell.getValue();\n\tconst resolution = getSheetsCellContent(rowIndex, colKey);\n\t// Only the draft-action column needs the row's draft status; for every other column\n\t// this is null and the inner skips the Button branch. `cell.row.original` carries the\n\t// Symbol-keyed DraftMeta (it's the live row ref, never spread away by the table).\n\tconst draftAction = colKey === DRAFT_ACTION_COLUMN_KEY ? deriveDraftActionInfo(cell.row.original) : null;\n\treturn (\n\t\t<SheetsCellHostInner\n\t\t\tresolution={resolution}\n\t\t\trowId={cell.row.id}\n\t\t\tcolKey={colKey}\n\t\t\trowIndex={rowIndex}\n\t\t\tcolumnIndex={ctx.columnIndex}\n\t\t\tvalue={value}\n\t\t\tisEditing={!!isEditing}\n\t\t\tinlineInitialText={inlineInitialText}\n\t\t\tonInlineCommit={onInlineCommit}\n\t\t\tonInlineCancel={onInlineCancel}\n\t\t\tisActive={ctx.isActive}\n\t\t\topenEditor={openEditor}\n\t\t\tonActivateCell={onActivateCell}\n\t\t\tonContextMenu={onContextMenu}\n\t\t\tonSubmitDraftRow={onSubmitDraftRow}\n\t\t\tdraftAction={draftAction}\n\t\t\tclassName={className}\n\t\t/>\n\t);\n}\n","// The badge / category color system (DESIGN_SPEC §7) — the signature element.\n//\n// Category pills render as a tinted chip: a soft same-hue background paired with\n// saturated same-hue text. The DEFAULT tone is `neutral`; color is OPT-IN. The\n// consumer assigns a tone per value via a `Record<string, BadgeTone>` overrides\n// map (exact value -> tone) or a `(value) => BadgeTone | undefined` resolver\n// (e.g. CRM grids letting users color their own categories). There is NO\n// automatic hashing — an unconfigured grid stays calm and on-brand, resolving\n// every value to `neutral`.\n//\n// `neutral` is the only tone built from semantic tokens (so it themes for free);\n// the 8-hue categorical palette below is intentional data-viz color and ships\n// explicit `dark:` pairs — the one sanctioned exception to the tokens-not-palette\n// law (§6).\n\nexport type BadgeTone = 'neutral' | 'blue' | 'green' | 'amber' | 'red' | 'purple' | 'pink' | 'teal';\n\nexport const BADGE_TONES: Record<BadgeTone, string> = {\n\tneutral: 'bg-muted text-muted-foreground',\n\tblue: 'bg-blue-50 text-blue-700 dark:bg-blue-500/15 dark:text-blue-300',\n\tgreen: 'bg-emerald-50 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300',\n\tamber: 'bg-amber-50 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300',\n\tred: 'bg-rose-50 text-rose-700 dark:bg-rose-500/15 dark:text-rose-300',\n\tpurple: 'bg-violet-50 text-violet-700 dark:bg-violet-500/15 dark:text-violet-300',\n\tpink: 'bg-pink-50 text-pink-700 dark:bg-pink-500/15 dark:text-pink-300',\n\tteal: 'bg-teal-50 text-teal-700 dark:bg-teal-500/15 dark:text-teal-300',\n};\n\n/**\n * Resolve a badge value to its tone. Resolution order (first hit wins):\n * 1. `overrides[value]` — exact value -> tone map.\n * 2. `resolver?.(value)` — programmatic resolver.\n * 3. `'neutral'` — the default; color is neutral-until-configured.\n *\n * No automatic hashing: an unmapped value is always `neutral`.\n */\nexport function resolveBadgeTone(\n\tvalue: string,\n\toverrides?: Record<string, BadgeTone>,\n\tresolver?: (v: string) => BadgeTone | undefined,\n): BadgeTone {\n\treturn overrides?.[value] ?? resolver?.(value) ?? 'neutral';\n}\n","// Default DOM view for the `badges` SheetsCell family — the native analogue of\n// v1's glide BubbleCell render. Dependency-light: plain JSX + Tailwind v4 + a\n// local `cn`, with no shared primitive dependency. Reads the string[] off\n// `props.cell.data` (the badges payload) and renders one tonal chip per item per\n// DESIGN_SPEC §7; an empty array renders an empty cell.\n//\n// Chips default to the `neutral` tone — the palette is wired for opt-in color\n// later (consumer-supplied tone map / resolver); an unconfigured grid stays calm.\n\nimport { BADGE_TONES, resolveBadgeTone } from '../badge-tones';\nimport { cn } from '../../utils/cn';\nimport type { CellProps } from '../cell-props';\n\nexport function BadgesCellView(props: CellProps) {\n\tconst items = Array.isArray(props.cell.data) ? (props.cell.data as string[]) : [];\n\n\treturn (\n\t\t<div\n\t\t\trole=\"gridcell\"\n\t\t\tdata-slot=\"badges-cell\"\n\t\t\tclassName={cn(\n\t\t\t\t'flex h-full w-full items-center gap-1 overflow-hidden px-3',\n\t\t\t\t// Single row in the fixed-height cell (no vertical cramming): pills that run\n\t\t\t\t// past the right edge fade out, signalling more items beyond the cut (DESIGN_SPEC §7).\n\t\t\t\t// The mask only bites when content actually reaches the right edge, so a short list\n\t\t\t\t// (nothing near the edge) shows no fade.\n\t\t\t\t'[mask-image:linear-gradient(to_right,black,black_calc(100%_-_1.5rem),transparent)]',\n\t\t\t)}\n\t\t>\n\t\t\t{items.map((item, index) => (\n\t\t\t\t<span\n\t\t\t\t\tkey={`${index}-${item}`}\n\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t'inline-flex shrink-0 items-center rounded-md px-2 py-0.5 text-xs font-medium',\n\t\t\t\t\t\tBADGE_TONES[resolveBadgeTone(item)],\n\t\t\t\t\t)}\n\t\t\t\t>\n\t\t\t\t\t{item}\n\t\t\t\t</span>\n\t\t\t))}\n\t\t</div>\n\t);\n}\n","// Default DOM view for the boolean family. A boolean column IS a checkbox column,\n// so it renders the design-system Checkbox as a\n// READ-ONLY status indicator: checked for true, unchecked for false, empty cell for\n// null/undefined. `pointer-events-none` keeps the existing double-click-to-toggle model\n// intact — clicks pass through to the host cell wrapper; the checkbox is display only.\n// Keyed off the boolean payload in `cell.data` (NOT displayData — the factory leaves\n// displayData '' for parity).\n\nimport { Checkbox } from '@constructive-io/ui/checkbox';\n\nimport type { CellProps } from '../cell-props';\n\nexport function BooleanCellView(props: CellProps) {\n\tconst value = props.cell.data;\n\tconst hasValue = value === true || value === false;\n\n\treturn (\n\t\t<div role=\"gridcell\" data-slot=\"boolean-cell\" className=\"flex h-full w-full items-center px-3\">\n\t\t\t{hasValue ? (\n\t\t\t\t<Checkbox checked={value === true} readOnly tabIndex={-1} className=\"pointer-events-none\" />\n\t\t\t) : null}\n\t\t</div>\n\t);\n}\n","// Native DOM view for the `draft-action` column — the REAL <Button> that replaces\n// the canvas fake-button painter (grid/custom-cells/draft-action-cell.tsx, which\n// snapshot-captured design-system button styles into a canvas paint via\n// captureButtonStyle/BUTTON_STYLE_CACHE). Mirrors that painter's states 1:1:\n// - idle -> outline button labelled \"Save\"\n// - saving -> disabled, spinner + \"Saving...\" (canvas drew an animated arc)\n// - errored -> red dot indicator top-right; the button stays interactive\n// (the canvas painter never disabled on `errored`)\n// The host special-cases this column and passes these explicit props instead of the\n// generic CellProps, so the view stays a dumb presenter and onClick -> onSubmit().\n\nimport { LoaderIcon } from 'lucide-react';\n\nimport { Button } from '@constructive-io/ui/button';\nimport { cn } from '../../utils/cn';\n\nexport type DraftActionStatus = 'idle' | 'saving' | 'error';\n\nexport interface DraftActionCellViewProps {\n\tstatus?: DraftActionStatus;\n\tdisabled?: boolean;\n\terrored?: boolean;\n\tonSubmit?: () => void;\n}\n\nconst SAVE_LABEL = 'Save';\nconst SAVING_LABEL = 'Saving...';\n\nexport function DraftActionCellView(props: DraftActionCellViewProps) {\n\tconst status = props.status ?? 'idle';\n\tconst isSaving = status === 'saving';\n\t// Saving locks the button so a real DOM click can't double-submit mid-flight;\n\t// the canvas relied on the shell to guard, the DOM disables outright.\n\tconst isDisabled = Boolean(props.disabled) || isSaving;\n\n\treturn (\n\t\t<div className=\"flex h-full w-full items-center justify-center px-2\">\n\t\t\t<Button\n\t\t\t\ttype=\"button\"\n\t\t\t\tvariant=\"outline\"\n\t\t\t\tsize=\"sm\"\n\t\t\t\tdisabled={isDisabled}\n\t\t\t\tonClick={props.onSubmit}\n\t\t\t\tdata-slot=\"draft-action-cell\"\n\t\t\t\tclassName=\"relative\"\n\t\t\t>\n\t\t\t\t{isSaving && <LoaderIcon className=\"animate-spin\" aria-hidden=\"true\" />}\n\t\t\t\t{isSaving ? SAVING_LABEL : SAVE_LABEL}\n\t\t\t\t{props.errored && (\n\t\t\t\t\t<span\n\t\t\t\t\t\tdata-slot=\"draft-action-error\"\n\t\t\t\t\t\trole=\"status\"\n\t\t\t\t\t\taria-label=\"Save failed\"\n\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t'absolute -top-1 -right-1 size-2 rounded-full bg-destructive',\n\t\t\t\t\t\t\t'ring-2 ring-background',\n\t\t\t\t\t\t)}\n\t\t\t\t\t/>\n\t\t\t\t)}\n\t\t\t</Button>\n\t\t</div>\n\t);\n}\n","// DOM view for geometry cells — the native analogue of the canvas geometry\n// painter (grid/custom-cells/geometry-cell.tsx). Instead of a plain monospace\n// preview it paints a geo ICON tinted by geometry category (point/line/polygon/\n// collection), plus an ABBREVIATED type label, mirroring the canvas `draw`.\n//\n// The geometry TYPE is derived without a leaflet/geojson dependency: prefer an\n// explicit hint (`cell.meta.geometryType`, or a `{ geometryType }` object set by a\n// `deriveGeometry` builder — v1 `createGeometryCell`), else sniff the GeoJSON\n// `\"type\":\"…\"` token out of the compact preview string the factory put in\n// `cell.data` / `cell.displayData`. Dependency-light: plain JSX + inline SVG +\n// Tailwind v4 + local `cn`, with no shared primitive dependency.\n\nimport type { CellProps } from '../cell-props';\nimport { cn } from '../../utils/cn';\n\ntype GeometryCategory = 'point' | 'line' | 'polygon' | 'collection' | 'invalid';\n\n// Canvical-cell category buckets keyed by GeoJSON type — mirrors geometry-cell.tsx\n// ICON_COLORS grouping (point/line/polygon families share a colour).\nconst TYPE_CATEGORY: Record<string, GeometryCategory> = {\n\tPoint: 'point',\n\tMultiPoint: 'point',\n\tLineString: 'line',\n\tMultiLineString: 'line',\n\tPolygon: 'polygon',\n\tMultiPolygon: 'polygon',\n\tGeometryCollection: 'collection',\n};\n\n// Tints mirror geometry-cell.tsx ICON_COLORS (blue/purple/green/amber, red for invalid).\nconst CATEGORY_COLOR: Record<GeometryCategory, string> = {\n\tpoint: '#3b82f6',\n\tline: '#8b5cf6',\n\tpolygon: '#10b981',\n\tcollection: '#f59e0b',\n\tinvalid: '#ef4444',\n};\n\n// Abbreviated labels — the narrowest candidate from geometry-cell.tsx TYPE_LABELS\n// (the DOM cell has no canvas measure loop, so pick the compact form up front).\nconst TYPE_LABEL: Record<string, string> = {\n\tPoint: 'Point',\n\tMultiPoint: 'MPt',\n\tLineString: 'Line',\n\tMultiLineString: 'MLine',\n\tPolygon: 'Poly',\n\tMultiPolygon: 'MPoly',\n\tGeometryCollection: 'GColl',\n};\n\nconst GEOJSON_TYPE_RE = /\"type\"\\s*:\\s*\"([A-Za-z]+)\"/;\n\n/** Read an explicit geometry type from the cell hint (meta or a derived data object). */\nfunction readHintedType(cell: CellProps['cell']): string | undefined {\n\tconst fromMeta = cell.meta?.geometryType;\n\tif (typeof fromMeta === 'string' && fromMeta) return fromMeta;\n\tconst data = cell.data;\n\tif (data && typeof data === 'object') {\n\t\tconst gt = (data as { geometryType?: unknown }).geometryType;\n\t\tif (typeof gt === 'string' && gt) return gt;\n\t}\n\treturn undefined;\n}\n\n/** Sniff the GeoJSON `type` token out of the compact preview string. */\nfunction sniffTypeFromText(cell: CellProps['cell']): string | undefined {\n\tconst source =\n\t\ttypeof cell.data === 'string' ? cell.data : typeof cell.displayData === 'string' ? cell.displayData : '';\n\treturn GEOJSON_TYPE_RE.exec(source)?.[1];\n}\n\n/** The single-line preview text the factory emitted (copy/display parity). */\nfunction readDisplayText(cell: CellProps['cell']): string {\n\tif (typeof cell.displayData === 'string' && cell.displayData) return cell.displayData;\n\tif (typeof cell.data === 'string') return cell.data;\n\treturn '';\n}\n\nfunction categorize(geometryType: string | undefined): GeometryCategory {\n\tif (!geometryType) return 'invalid';\n\treturn TYPE_CATEGORY[geometryType] ?? 'invalid';\n}\n\nfunction labelFor(geometryType: string | undefined, category: GeometryCategory): string {\n\tif (!geometryType) return 'Invalid';\n\treturn TYPE_LABEL[geometryType] ?? (category === 'invalid' ? 'Invalid' : geometryType);\n}\n\n// Inline SVG geo icons — one per category, tinted via `color`. A point is a map\n// pin; line/polygon/collection use a map glyph; invalid is a warning triangle.\nfunction GeometryIcon({ category, color }: { category: GeometryCategory; color: string }) {\n\tconst common = {\n\t\twidth: 14,\n\t\theight: 14,\n\t\tviewBox: '0 0 24 24',\n\t\tfill: 'none',\n\t\tstroke: color,\n\t\tstrokeWidth: 2,\n\t\tstrokeLinecap: 'round' as const,\n\t\tstrokeLinejoin: 'round' as const,\n\t\t'aria-hidden': true,\n\t\tclassName: 'shrink-0',\n\t};\n\tif (category === 'point') {\n\t\treturn (\n\t\t\t<svg {...common} data-geometry-icon=\"point\">\n\t\t\t\t<path d=\"M12 21s-6-5.686-6-10a6 6 0 1 1 12 0c0 4.314-6 10-6 10z\" />\n\t\t\t\t<circle cx=\"12\" cy=\"11\" r=\"2\" />\n\t\t\t</svg>\n\t\t);\n\t}\n\tif (category === 'invalid') {\n\t\treturn (\n\t\t\t<svg {...common} data-geometry-icon=\"invalid\">\n\t\t\t\t<path d=\"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z\" />\n\t\t\t\t<line x1=\"12\" y1=\"9\" x2=\"12\" y2=\"13\" />\n\t\t\t\t<line x1=\"12\" y1=\"17\" x2=\"12.01\" y2=\"17\" />\n\t\t\t</svg>\n\t\t);\n\t}\n\t// line / polygon / collection — a folded map glyph.\n\treturn (\n\t\t<svg {...common} data-geometry-icon={category}>\n\t\t\t<polygon points=\"1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6\" />\n\t\t\t<line x1=\"8\" y1=\"2\" x2=\"8\" y2=\"18\" />\n\t\t\t<line x1=\"16\" y1=\"6\" x2=\"16\" y2=\"22\" />\n\t\t</svg>\n\t);\n}\n\nexport function GeometryCellView(props: CellProps) {\n\tconst { cell } = props;\n\tconst text = readDisplayText(cell);\n\n\t// Empty cell — nothing to paint, matching the canvas `isEmpty` early-return.\n\tif (!text && !readHintedType(cell)) {\n\t\treturn <div data-slot=\"geometry-cell\" role=\"gridcell\" className=\"h-full w-full\" />;\n\t}\n\n\tconst geometryType = readHintedType(cell) ?? sniffTypeFromText(cell);\n\tconst category = categorize(geometryType);\n\tconst color = CATEGORY_COLOR[category];\n\tconst label = labelFor(geometryType, category);\n\n\treturn (\n\t\t<div\n\t\t\tdata-slot=\"geometry-cell\"\n\t\t\tdata-geometry-category={category}\n\t\t\trole=\"gridcell\"\n\t\t\ttitle={text}\n\t\t\tclassName={cn('flex h-full w-full items-center gap-1.5 overflow-hidden px-3')}\n\t\t>\n\t\t\t<GeometryIcon category={category} color={color} />\n\t\t\t<span className={cn('truncate text-xs font-medium', category === 'invalid' && 'text-foreground/60')}>\n\t\t\t\t{label}\n\t\t\t</span>\n\t\t</div>\n\t);\n}\n","// Default native DOM view for the `image` SheetsCell kind. Dependency-light: plain\n// JSX + Tailwind v4 + local `cn`, with no shared primitive dependency. Reads the URL\n// from the factory payload (`cell.data` is `[url]`).\n//\n// Mirrors the canvas painter (`grid/draw-image-cell.ts`): a uniform SQUARE\n// thumbnail with object-fit:cover (center-crop, NOT contain) and rounded corners,\n// inset by a small pad. A muted box sits UNDER the <img> so it shows through\n// while the image loads AND stands alone when the url is empty (the canvas drew\n// the same placeholder for both the loading and missing-url branches).\n//\n// Virtualization destroys off-screen rows, so the body <img> is recreated on every\n// scroll-back. We retain successfully-loaded URLs in a module LRU (`warmImage`) to\n// keep them warm in memory — a remounted <img> paints without a re-fetch. No\n// `loading=\"lazy\"` (it forces a fetch-after-mount on every remount).\n\nimport { FileIcon } from 'lucide-react';\n\nimport type { CellProps } from '../cell-props';\nimport { cn } from '../../utils/cn';\nimport { getImageMetadata } from '../../utils/file.utils';\nimport { warmImage } from '../image-cache';\n\nfunction readUrl(data: unknown): string {\n\tif (Array.isArray(data) && typeof data[0] === 'string') return data[0];\n\treturn '';\n}\n\n/** Last path segment of a url (sans query/hash), to label a file chip that has no filename. */\nfunction basename(url: string): string {\n\tconst path = url.split(/[?#]/)[0];\n\tconst seg = path.slice(path.lastIndexOf('/') + 1);\n\treturn seg || url;\n}\n\n/**\n * On a non-`image` media column (file/video/audio/upload), render a file chip UNLESS we KNOW\n * the value is an image (an `image/*` mime). Non-image mimes, unknown mimes and bare URL\n * strings all chip — mirroring the editor's stored-value preview so the grid never shows a\n * broken <img> for a document. The `image` column is unaffected (always a thumbnail).\n */\nfunction isNonImageFile(cellType: string, value: unknown): boolean {\n\tif (cellType === 'image' || value == null) return false;\n\tconst mime = getImageMetadata(value)?.mime;\n\treturn !(mime && mime !== 'unknown' && mime.startsWith('image/'));\n}\n\nexport function ImageCellView(props: CellProps) {\n\tconst url = readUrl(props.cell.data);\n\n\tif (url && isNonImageFile(props.column.cellType, props.value)) {\n\t\tconst meta = getImageMetadata(props.value);\n\t\tconst filename = meta?.filename && meta.filename !== 'Unknown' ? meta.filename : basename(url);\n\t\treturn (\n\t\t\t<div\n\t\t\t\tdata-slot=\"file-cell\"\n\t\t\t\trole=\"gridcell\"\n\t\t\t\tclassName={cn('flex h-full w-full items-center gap-1.5 overflow-hidden px-2')}\n\t\t\t>\n\t\t\t\t<FileIcon className=\"size-3.5 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n\t\t\t\t<span className=\"truncate text-sm\" title={filename}>\n\t\t\t\t\t{filename}\n\t\t\t\t</span>\n\t\t\t</div>\n\t\t);\n\t}\n\n\treturn (\n\t\t<div\n\t\t\tdata-slot=\"image-cell\"\n\t\t\trole=\"gridcell\"\n\t\t\tclassName={cn('flex h-full w-full items-center overflow-hidden p-1')}\n\t\t>\n\t\t\t<div className={cn('relative aspect-square h-full max-h-full overflow-hidden rounded-sm bg-muted')}>\n\t\t\t\t{url ? (\n\t\t\t\t\t<img\n\t\t\t\t\t\tsrc={url}\n\t\t\t\t\t\tdecoding=\"async\"\n\t\t\t\t\t\talt=\"\"\n\t\t\t\t\t\tonLoad={() => warmImage(url)}\n\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t'absolute inset-0 h-full w-full rounded-sm object-cover outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10',\n\t\t\t\t\t\t)}\n\t\t\t\t\t/>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t</div>\n\t);\n}\n","// Bounded module-level LRU that RETAINS decoded images by URL so they stay warm in\n// the browser's in-memory cache across unmount/remount. In a virtualized grid the\n// body <img> is destroyed when its row scrolls off-screen; without a live reference\n// the decoded bitmap is dropped and a remounted <img src> refetches/repaints (flicker,\n// pop-in). Holding a decoded Image reference keeps the URL warm — a remounted <img>\n// paints from memory instead of refetching, even for no-cache/short-lived URLs.\n\nconst CAP = 256;\nconst cache = new Map<string, HTMLImageElement>(); // Map preserves insertion order → LRU.\n\nexport function warmImage(url: string): void {\n\tif (!url || typeof Image === 'undefined') return; // SSR / empty-url guard.\n\n\tif (cache.has(url)) {\n\t\t// Mark most-recently-used: re-insert moves it to the end of the iteration order.\n\t\tconst img = cache.get(url)!;\n\t\tcache.delete(url);\n\t\tcache.set(url, img);\n\t\treturn;\n\t}\n\n\tconst img = new Image();\n\timg.decoding = 'async';\n\timg.src = url;\n\tcache.set(url, img);\n\n\twhile (cache.size > CAP) {\n\t\t// Evict the oldest (front of insertion order).\n\t\tconst oldest = cache.keys().next().value;\n\t\tif (oldest === undefined) break;\n\t\tcache.delete(oldest);\n\t}\n}\n","// Default DOM view for the grid-internal `loading` SheetsCell kind — the cell an\n// infinite-scroll row shows while its page is still in flight (getRowAtIndex is\n// null, so there is no value to render). The native analogue of v1's canvas\n// loading skeleton: a subtle `animate-pulse` placeholder bar filling the cell.\n// Dependency-light: plain JSX + Tailwind v4 + local `cn`, with no shared primitive dependency.\n\nimport type { CellProps } from '../cell-props';\nimport { cn } from '../../utils/cn';\n\nexport function LoadingCellView(_props: CellProps) {\n\treturn (\n\t\t<div\n\t\t\trole=\"gridcell\"\n\t\t\tdata-slot=\"loading-cell\"\n\t\t\taria-busy=\"true\"\n\t\t\tclassName={cn('flex h-full w-full items-center px-3')}\n\t\t>\n\t\t\t<span\n\t\t\t\taria-hidden=\"true\"\n\t\t\t\tclassName={cn('h-3 w-3/5 max-w-full rounded-full bg-muted', 'animate-pulse')}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n","// Default DOM view for the number SheetsCell family. Dependency-light: plain JSX\n// + Tailwind v4 + a `data-slot` hook, with no shared primitive dependency. Numbers\n// render right-aligned with tabular figures so digits line up column-wise. Reads\n// the already-formatted string off `props.cell.displayData` (the factory put\n// String(numValue) | '' there); the view does no numeric formatting itself.\n\nimport type { CellProps } from '../cell-props';\nimport { cn } from '../../utils/cn';\n\nexport function NumberCellView(props: CellProps) {\n\tconst { cell } = props;\n\treturn (\n\t\t<div\n\t\t\trole=\"gridcell\"\n\t\t\tdata-slot=\"number-cell\"\n\t\t\tclassName={cn('flex h-full w-full items-center justify-end truncate px-3 text-right text-sm tabular-nums text-foreground')}\n\t\t>\n\t\t\t{cell.displayData}\n\t\t</div>\n\t);\n}\n","// Default DOM view for the `relation` SheetsCell family. Dependency-light: plain\n// JSX + Tailwind v4 + a local `cn`, with no shared primitive dependency. Reads the\n// render payload off `props.cell` (produced by relationSheetsCellFactory):\n// - list relation -> cell.data is string[] (chips, possibly a trailing \"+N\")\n// - single relation -> cell.data is a string label\n// The factory already truncated labels and computed overflow; the view only paints.\n//\n// PARITY (canvas grid/draw-relation-badge.ts): for a list relation, paint a leading\n// COUNT BADGE pill — the number of related items — before the chips, mirroring the\n// canvas `drawRelationBadge`. Item count matches the canvas `getRelationCount`: the\n// trailing \"+N\" overflow chip means count = (chips − 1) + N, otherwise chips.length.\n// The single-relation (string) path stays plain text.\n\nimport React from 'react';\n\nimport { cn } from '../../utils/cn';\nimport type { CellProps } from '../cell-props';\n\n// Mirrors canvas `getRelationCount` for the Bubble (list) branch: a trailing \"+N\"\n// element is an overflow indicator, so the true count is (visible chips) + N.\nfunction getListRelationCount(chips: unknown[]): number {\n\tconst last = chips[chips.length - 1];\n\tif (typeof last === 'string' && last.startsWith('+')) {\n\t\tconst overflow = parseInt(last.slice(1), 10);\n\t\tif (!isNaN(overflow)) return chips.length - 1 + overflow;\n\t}\n\treturn chips.length;\n}\n\nexport function RelationCellView(props: CellProps): React.JSX.Element {\n\tconst { cell } = props;\n\tconst isList = Array.isArray(cell.data);\n\n\tif (!isList) {\n\t\treturn (\n\t\t\t<div\n\t\t\t\tdata-slot=\"relation-cell\"\n\t\t\t\trole=\"gridcell\"\n\t\t\t\tclassName=\"flex h-full w-full items-center gap-1 overflow-hidden px-3 text-sm\"\n\t\t\t>\n\t\t\t\t<span className=\"truncate text-foreground\">{String(cell.data ?? '')}</span>\n\t\t\t</div>\n\t\t);\n\t}\n\n\tconst chips = cell.data as unknown[];\n\tconst count = getListRelationCount(chips);\n\n\treturn (\n\t\t<div\n\t\t\tdata-slot=\"relation-cell\"\n\t\t\trole=\"gridcell\"\n\t\t\tclassName=\"flex h-full w-full items-center gap-1 overflow-hidden px-3 text-sm\"\n\t\t>\n\t\t\t{count > 0 ? (\n\t\t\t\t<span\n\t\t\t\t\tdata-slot=\"relation-count-badge\"\n\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t'inline-flex shrink-0 items-center rounded-sm border border-border bg-muted',\n\t\t\t\t\t\t'px-1 text-[10px] font-medium text-muted-foreground tabular-nums',\n\t\t\t\t\t)}\n\t\t\t\t>\n\t\t\t\t\t{count}\n\t\t\t\t</span>\n\t\t\t) : null}\n\t\t\t{chips.map((chip, index) => (\n\t\t\t\t<span\n\t\t\t\t\tkey={index}\n\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t'inline-flex shrink-0 items-center rounded-md bg-muted px-1.5 py-0.5',\n\t\t\t\t\t\t'text-xs font-medium text-muted-foreground',\n\t\t\t\t\t)}\n\t\t\t\t>\n\t\t\t\t\t{String(chip)}\n\t\t\t\t</span>\n\t\t\t))}\n\t\t</div>\n\t);\n}\n","// Default DOM view for the text family (the fallback). v1 renders the value as\n// plain truncated text inside the canvas; the native analogue is a single\n// truncated span. Dependency-light: plain JSX + Tailwind v4 + local `cn`, no\n// shared primitive dependency. Reads the rendered string off the SheetsCell\n// payload (`cell.displayData`) so it stays in lockstep with the factory.\n\nimport type { CellProps } from '../cell-props';\nimport { cn } from '../../utils/cn';\n\nexport function TextCellView(props: CellProps) {\n\tconst text = props.cell.displayData;\n\n\treturn (\n\t\t<div\n\t\t\trole=\"gridcell\"\n\t\t\tdata-slot=\"text-cell\"\n\t\t\ttitle={text}\n\t\t\tclassName={cn('flex h-full w-full items-center truncate px-3 text-sm')}\n\t\t>\n\t\t\t<span className=\"truncate\">{text}</span>\n\t\t</div>\n\t);\n}\n","// Native DOM view for the URI family (url | email). Dependency-light: plain JSX\n// + Tailwind v4 + local `cn`. Reads the render payload off `props.cell`\n// (`data` -> href, `displayData` -> visible label). The view owns the click\n// (v1's UriCellFactory dropped its onClickUri side-effect): the anchor opens in\n// a new tab. Empty cells (`data === ''`) render inert text, not a dead link.\n\nimport type { CellProps } from '../cell-props';\nimport { cn } from '../../utils/cn';\n\nexport function UriCellView(props: CellProps) {\n\tconst { cell } = props;\n\tconst href = String(cell.data ?? '');\n\tconst label = cell.displayData;\n\tconst hasHref = href.length > 0;\n\n\treturn (\n\t\t<div role=\"gridcell\" data-slot=\"uri-cell\" className=\"flex h-full w-full min-w-0 items-center px-3 text-sm\">\n\t\t\t{hasHref ? (\n\t\t\t\t<a\n\t\t\t\t\thref={href}\n\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\trel=\"noreferrer\"\n\t\t\t\t\ttitle={label}\n\t\t\t\t\tclassName={cn('truncate text-info underline-offset-2 hover:underline', 'focus-visible:outline-hidden')}\n\t\t\t\t>\n\t\t\t\t\t{label}\n\t\t\t\t</a>\n\t\t\t) : (\n\t\t\t\t<span className=\"truncate text-muted-foreground\">{label}</span>\n\t\t\t)}\n\t\t</div>\n\t);\n}\n","'use client';\n\n// Inline (in-cell) editor — a bare single-line <input> rendered DIRECTLY inside the\n// cell for the SIMPLE text-representable types (text-like + number-like). The\n// non-overlay counterpart of the portal editors: there is no card, no Save button and\n// no React portal — the input fills the cell (`absolute inset-0`) and overlays the\n// cell view while editing. Routed here by `resolveEditIntent` → `{ mode: 'inline-edit' }`\n// (url/inet/json/date/relation/… keep their specialised overlay editors).\n//\n// COMMIT MODEL (mirrors the overlay text/number editors, minus the chrome):\n// • Enter / blur (click-away) → commit. Escape → cancel. A numeric field that does\n// not parse blocks Enter (stay editing) and discards on blur (never clobbers the\n// value with garbage) — same guard as the overlay NumberEditor.\n// • `doneRef` makes commit/cancel idempotent: the explicit path returns focus to the\n// grid root (so keyboard nav resumes), and the blur THAT focus shift triggers is\n// short-circuited so it never double-fires.\n// • Pointer events stopPropagation so selecting text with the mouse does not trip the\n// cell's click-to-activate / range-drag handlers on the host wrapper.\n\nimport { useLayoutEffect, useRef, useState } from 'react';\n\nimport { cn } from '../utils/cn';\n\ninterface InlineCellEditorProps {\n\t/** Accessible name derived from the owning column. */\n\tariaLabel: string;\n\t/** The cell's committed value — seeds the input unless `initialText` overrides (type-to-edit). */\n\tvalue: unknown;\n\t/** Type-to-edit seed (OVERWRITE): a printable char that opened the editor replaces the value. */\n\tinitialText?: string;\n\t/** Number-like cell — parse to a finite number (or null) on commit and right-align like the view. */\n\tnumeric?: boolean;\n\t/** Commit the next raw value (string, or number|null when numeric). */\n\tonCommit: (next: unknown) => void;\n\t/** Discard — Escape, or an unparseable numeric field on blur. */\n\tonCancel: () => void;\n}\n\n/** Seed the input text from the raw value (anything stringifiable), else ''. */\nfunction seedText(value: unknown): string {\n\tif (value === null || value === undefined) return '';\n\treturn String(value);\n}\n\n/** Parse numeric input: '' → null (a valid clear); else a finite number, or `ok:false` for garbage. */\nfunction parseNumeric(text: string): { ok: boolean; value: number | null } {\n\tconst trimmed = text.trim();\n\tif (trimmed === '') return { ok: true, value: null };\n\tconst n = Number(trimmed);\n\treturn Number.isFinite(n) ? { ok: true, value: n } : { ok: false, value: null };\n}\n\nexport function InlineCellEditor({ ariaLabel, value, initialText, numeric, onCommit, onCancel }: InlineCellEditorProps) {\n\tconst [text, setText] = useState(() => (initialText != null ? initialText : seedText(value)));\n\tconst inputRef = useRef<HTMLInputElement | null>(null);\n\t// The grid root (role=grid, tabIndex=0) — focus returns here on commit/cancel so arrow-key\n\t// nav resumes (the input unmounts and would otherwise drop focus to <body>). Captured once.\n\tconst gridRef = useRef<HTMLElement | null>(null);\n\t// Guards commit/cancel idempotency: set before the explicit focus-return so the resulting\n\t// blur skips its commit-on-blur (no double commit, no commit-after-Escape).\n\tconst doneRef = useRef(false);\n\n\tuseLayoutEffect(() => {\n\t\tconst el = inputRef.current;\n\t\tgridRef.current = (el?.closest('[role=\"grid\"]') as HTMLElement | null) ?? null;\n\t\t// Seeded from the cell value (Enter / F2 / double-click) → select all so the first keystroke\n\t\t// replaces. A type-to-edit seed already IS the replacement, so leave the caret at the end.\n\t\tif (el && initialText == null) el.select();\n\t}, [initialText]);\n\n\tfunction finish(commit: boolean) {\n\t\tif (doneRef.current) return;\n\t\tdoneRef.current = true;\n\t\t// Return focus to the grid BEFORE the input unmounts; doneRef makes the blur a no-op.\n\t\tgridRef.current?.focus();\n\t\tif (!commit) {\n\t\t\tonCancel();\n\t\t\treturn;\n\t\t}\n\t\tif (numeric) {\n\t\t\tconst parsed = parseNumeric(text);\n\t\t\tif (!parsed.ok) {\n\t\t\t\tonCancel(); // unparseable on commit-by-blur → discard rather than clobber\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tonCommit(parsed.value);\n\t\t\treturn;\n\t\t}\n\t\tonCommit(text);\n\t}\n\n\tfunction handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {\n\t\tif (e.key === 'Enter') {\n\t\t\te.preventDefault();\n\t\t\t// Unparseable number on Enter → stay editing (mirror the overlay editor's Enter no-op).\n\t\t\tif (numeric && !parseNumeric(text).ok) return;\n\t\t\tfinish(true);\n\t\t\treturn;\n\t\t}\n\t\tif (e.key === 'Escape') {\n\t\t\te.preventDefault();\n\t\t\tfinish(false);\n\t\t}\n\t\t// Other keys (incl. arrows / Home / End) act on the input text. They bubble to the grid\n\t\t// root, which ignores keys while an editor is active, so they never move the grid cursor.\n\t}\n\n\treturn (\n\t\t<input\n\t\t\taria-label={ariaLabel}\n\t\t\tref={inputRef}\n\t\t\tvalue={text}\n\t\t\tonChange={(e) => setText(e.target.value)}\n\t\t\tonKeyDown={handleKeyDown}\n\t\t\tonBlur={() => finish(true)}\n\t\t\tonPointerDown={(e) => e.stopPropagation()}\n\t\t\tonClick={(e) => e.stopPropagation()}\n\t\t\tonDoubleClick={(e) => e.stopPropagation()}\n\t\t\tinputMode={numeric ? 'decimal' : undefined}\n\t\t\tspellCheck={false}\n\t\t\tdata-slot='inline-cell-editor'\n\t\t\tclassName={cn(\n\t\t\t\t'bg-background ring-primary absolute inset-0 h-full w-full px-3 font-sans text-sm outline-none ring-2 ring-inset',\n\t\t\t\tnumeric && 'text-right tabular-nums',\n\t\t\t)}\n\t\t\tautoFocus\n\t\t/>\n\t);\n}\n","// Native overlay open/close state machine. The Phase-4 analogue of glide's\n// imperative editor activation, but as a tiny React hook with NO heavy effects:\n// `open(cell)` records the active cell (rect captured by the caller from the cell\n// DOM node), `close()` clears it. `handleKeyDown` is a host-attachable helper —\n// Enter/F2 open (the caller supplies the cell to open, since only the host knows\n// which DOM node is focused), Escape closes.\n//\n// TODO(Phase 7): Tab should commit-and-open-next; today Tab is left to default.\n\nimport { useCallback, useState } from 'react';\n\nexport interface OverlayCell {\n\trowIndex: number;\n\tcolKey: string;\n\tanchorRect: DOMRect;\n\t/** Type-to-edit seed: when set, value editors initialize the input to this char (overwrite). */\n\tinitialText?: string;\n\t/**\n\t * Edit surface for this active cell. `'overlay'` (default when omitted) renders the portal\n\t * editor; `'inline'` edits IN PLACE inside the cell (no portal — the cell host renders the\n\t * input) yet still rides this controller so nav/clipboard suppression + scroll commit-on-unmount\n\t * are shared. The portal (`OverlayManager` / `editorNode`) is skipped for `'inline'`.\n\t */\n\tmode?: 'overlay' | 'inline';\n}\n\nexport interface OverlayController {\n\tactive: OverlayCell | null;\n\tisOpen: boolean;\n\topen: (cell: OverlayCell) => void;\n\tclose: () => void;\n\t/**\n\t * Re-anchor the open overlay to a freshly-measured rect WITHOUT changing the active\n\t * cell — the editor-follows-cell-on-scroll path (Stage B). No-op when closed. Keeps\n\t * the same {@link OverlayCell} identity for every field except `anchorRect`, so the\n\t * editor's local state (in-progress value, focus) survives the reposition.\n\t */\n\treanchor: (anchorRect: DOMRect) => void;\n\t/**\n\t * Host key handler. Enter/F2 open the cell returned by `resolveCell` (the host\n\t * resolves the focused cell + measures its rect); Escape closes. `resolveCell`\n\t * may return null (nothing focused / not editable) — then the open is skipped.\n\t */\n\thandleKeyDown: (e: React.KeyboardEvent, resolveCell: () => OverlayCell | null) => void;\n}\n\nexport function useOverlayController(): OverlayController {\n\tconst [active, setActive] = useState<OverlayCell | null>(null);\n\n\tconst open = useCallback((cell: OverlayCell) => {\n\t\tsetActive(cell);\n\t}, []);\n\n\tconst close = useCallback(() => {\n\t\tsetActive(null);\n\t}, []);\n\n\tconst reanchor = useCallback((anchorRect: DOMRect) => {\n\t\tsetActive((prev) => (prev ? { ...prev, anchorRect } : prev));\n\t}, []);\n\n\tconst handleKeyDown = useCallback(\n\t\t(e: React.KeyboardEvent, resolveCell: () => OverlayCell | null) => {\n\t\t\tif (e.key === 'Enter' || e.key === 'F2') {\n\t\t\t\tconst cell = resolveCell();\n\t\t\t\tif (!cell) return;\n\t\t\t\te.preventDefault();\n\t\t\t\tsetActive(cell);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (e.key === 'Escape') {\n\t\t\t\te.preventDefault();\n\t\t\t\tsetActive(null);\n\t\t\t}\n\t\t\t// TODO(Phase 7): Tab -> commit current + open next cell.\n\t\t},\n\t\t[],\n\t);\n\n\treturn { active, isOpen: active != null, open, close, reanchor, handleKeyDown };\n}\n","'use client';\n\n// Native (DOM React-portal) overlay container — the Phase-4 analogue of glide's\n// `#portal` fixed host, but it anchors off the cell DOM node's measured rect and\n// portals straight into `document.body` (viewport coords, matching the\n// `window.innerHeight` assumption in `computeOverlayGeometry`). It REUSES the pure\n// flip math + `EditorFocusTrap` + `EditorErrorGuard` + overlay-preset width class.\n// It NEVER mutates `.gdg-clip-region` — that DOM coupling stays in the canvas\n// `OverlayViewportGuard` so the glide path is untouched.\n\nimport React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { createPortal } from 'react-dom';\n\nimport { computeOverlayGeometry, OverlayMeasureContext } from '../../grid/editors/overlay-viewport-guard';\nimport { EditorFocusTrap } from '../../grid/editors/editor-focus-trap';\nimport { EditorErrorGuard } from '../../grid/feedback/editor-error-boundary';\nimport { cn } from '../../utils/cn';\n\nconst MARGIN_PX = 12;\nconst MIN_BELOW_PX = 320;\n\n// Nested floating layers an editor MIGHT portal outside the overlay (Base UI / Radix\n// / Floating UI popover, select, menu, dialog, tooltip). A pointerdown inside one of\n// these must NOT dismiss the overlay. The current editors render their pickers inline\n// inside the overlay, so this is a forward-looking safety net.\nconst FLOATING_LAYER_SELECTOR =\n\t'[role=\"listbox\"],[role=\"menu\"],[role=\"dialog\"],[role=\"tooltip\"],[data-floating-ui-portal],[data-base-ui-positioner],[data-radix-popper-content-wrapper]';\n\ninterface OverlayManagerProps {\n\tanchorRect: DOMRect | null;\n\topen: boolean;\n\tpresetClass?: string;\n\tonCancel: () => void;\n\t/**\n\t * Outside-pointerdown policy (Stage B). `'cancel'` (default) dismisses with no write\n\t * — for editors that DON'T commit-on-blur (relation/date/json/url/inet/…). `'commit'`\n\t * — for the commit-on-blur value editors (text/number) — instead BLURS the focused\n\t * element inside the overlay so its `onBlur → onCommit` fires (commit-on-click-away),\n\t * rather than cancelling. The blur path then commits AND closes; the manager does NOT\n\t * also call onCancel, so there is exactly one dismiss per click-away.\n\t */\n\tdismissMode?: 'cancel' | 'commit';\n\tchildren: React.ReactNode;\n}\n\nexport function OverlayManager({ anchorRect, open, presetClass, onCancel, dismissMode = 'cancel', children }: OverlayManagerProps): React.ReactNode {\n\tconst containerRef = useRef<HTMLDivElement | null>(null);\n\t// Measured, viewport-clamped position (both axes). Null until the overlay has been\n\t// measured once, so first paint stays hidden rather than flashing at an unclamped\n\t// spot. Covers the FLIP (no room below -> open above) AND the horizontal shift (an\n\t// anchor near the right edge -> slide left so the overlay stays on-screen instead of\n\t// overflowing off the viewport, e.g. the last column's editor).\n\tconst [pos, setPos] = useState<{ left: number; top: number } | null>(null);\n\n\tconst targetY = anchorRect?.top;\n\tconst targetH = anchorRect?.height;\n\tconst vh = typeof window !== 'undefined' ? window.innerHeight : 800;\n\tconst { shouldFlip, maxHeight } = computeOverlayGeometry(vh, targetY, targetH, MARGIN_PX, MIN_BELOW_PX);\n\n\t// Geometry an editor needs to self-bound its internal scroll areas (the canvas path\n\t// supplied this via OverlayViewportGuard; the DOM host must too). WITHOUT it, editors\n\t// that read OverlayMeasureContext (relation/image/geometry) see the default maxHeight:0,\n\t// skip their scroll-budget effect, and render UNBOUNDED lists — so a relation editor's\n\t// infinite \"related records\" sentinel stays permanently in view and pages continuously.\n\tconst overlayMeasure = useMemo(() => ({ maxHeight, shouldFlip }), [maxHeight, shouldFlip]);\n\n\t// Measure the rendered overlay, then position it: vertically below the anchor (or\n\t// flipped above when there's no room), horizontally left-aligned to the anchor (or\n\t// shifted left to stay on-screen), clamped into the viewport on BOTH axes. DOM-read\n\t// only — mirrors the canvas guard's layout-effect measure; no hasMounted flag.\n\tuseLayoutEffect(() => {\n\t\tif (!open || !anchorRect) {\n\t\t\tsetPos(null);\n\t\t\treturn;\n\t\t}\n\t\tconst el = containerRef.current;\n\t\tif (!el) return;\n\t\tconst rect = el.getBoundingClientRect();\n\t\tconst vw = window.innerWidth;\n\t\tconst vhNow = window.innerHeight;\n\n\t\tlet left = anchorRect.left;\n\t\tleft = Math.max(MARGIN_PX, Math.min(left, vw - MARGIN_PX - rect.width));\n\t\tif (!Number.isFinite(left)) left = MARGIN_PX;\n\n\t\tlet top = shouldFlip ? anchorRect.top - rect.height : anchorRect.bottom;\n\t\ttop = Math.max(MARGIN_PX, Math.min(top, vhNow - MARGIN_PX - rect.height));\n\t\tif (!Number.isFinite(top)) top = MARGIN_PX;\n\n\t\tsetPos({ left, top });\n\t}, [open, shouldFlip, anchorRect, maxHeight]);\n\n\t// Dismiss on a pointerdown OUTSIDE the overlay — standard popover behaviour. The\n\t// overlay was previously only closable via Esc / commit / scroll, so a click in the\n\t// grid or page left it stuck open. Attached in an effect (after commit) so the\n\t// activating double-click that OPENED the overlay has fully settled and cannot\n\t// self-dismiss; capture phase so an inner editor that stops propagation can't\n\t// suppress it. Clicks inside the overlay (or a nested floating layer it portals)\n\t// are ignored.\n\tuseEffect(() => {\n\t\tif (!open) return;\n\t\tconst onPointerDown = (e: PointerEvent) => {\n\t\t\tconst el = containerRef.current;\n\t\t\tconst target = e.target as Node | null;\n\t\t\tif (!el || (target && el.contains(target))) return;\n\t\t\tif (target instanceof Element && target.closest(FLOATING_LAYER_SELECTOR)) return;\n\t\t\t// COMMIT-ON-CLICK-AWAY (Stage B): for commit-on-blur editors, move DOM focus out of\n\t\t\t// the overlay so the focused input's `onBlur → onCommit` fires (commit, then close).\n\t\t\t// We DON'T also call onCancel — the blur path closes the overlay, so this is exactly\n\t\t\t// one dismiss. A bare outside element may not be focusable (so a natural focus shift\n\t\t\t// wouldn't fire), hence we blur explicitly. Falls back to onCancel when nothing in the\n\t\t\t// overlay is focused. `'cancel'` editors discard as before.\n\t\t\tif (dismissMode === 'commit') {\n\t\t\t\tconst focused = document.activeElement;\n\t\t\t\tif (focused instanceof HTMLElement && el.contains(focused)) {\n\t\t\t\t\tfocused.blur();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tonCancel();\n\t\t};\n\t\tdocument.addEventListener('pointerdown', onPointerDown, true);\n\t\treturn () => document.removeEventListener('pointerdown', onPointerDown, true);\n\t}, [open, onCancel, dismissMode]);\n\n\tif (!open || !anchorRect || typeof document === 'undefined') return null;\n\n\t// Animate only once the measured, viewport-clamped position is applied, so the\n\t// entrance transform never fights the layout-effect measure.\n\tconst positioned = pos !== null;\n\tconst style: React.CSSProperties = {\n\t\tposition: 'fixed',\n\t\t// Pre-measure default = the ANCHOR position (below, or above when flipping), NOT a\n\t\t// screen corner. So an overlay that fits (the common case) renders at its FINAL spot\n\t\t// with zero left/top change once measured — no travel. It stays hidden until measured\n\t\t// and `transition-none` keeps the rare off-screen clamp instant, so the overlay is\n\t\t// never seen sliding to the anchor (the correction happens off-screen, pre-reveal).\n\t\tleft: pos ? pos.left : anchorRect.left,\n\t\ttop: pos ? pos.top : shouldFlip ? anchorRect.top : anchorRect.bottom,\n\t\tmaxHeight,\n\t\t// Hidden until measured to avoid a 1-frame flash at an unclamped position.\n\t\tvisibility: positioned ? 'visible' : 'hidden',\n\t\t// Join the shared design-system overlay layer instead of an\n\t\t// arbitrary z, so the editor and any popover/tooltip it opens (e.g. the relation\n\t\t// \"Record Data\" popover, which portals into #portal-root) stack coherently.\n\t\tzIndex: 'var(--z-layer-floating)',\n\t};\n\n\t// Portal into the app's shared floating-overlay host (#portal-root) so the editor and\n\t// nested UI popovers live in the SAME stacking context (siblings) — fixing the\n\t// host-dependent z-index race where the editor could paint OVER a popover opened from\n\t// within it. Fall back to <body> when no portal root is mounted (e.g. tests). The host\n\t// has pointer-events:none, so the overlay opts back in with pointer-events-auto.\n\tconst portalHost = document.getElementById('portal-root') ?? document.body;\n\n\treturn createPortal(\n\t\t<div\n\t\t\tref={containerRef}\n\t\t\tstyle={style}\n\t\t\tclassName={cn(\n\t\t\t\t// `transition-none`: the entrance is an ANIMATION (scale + fade); left/top must NEVER\n\t\t\t\t// transition, or measuring/clamping the position would visibly slide the overlay across\n\t\t\t\t// the screen to its anchor. This keeps the position application instant.\n\t\t\t\t'pointer-events-auto transition-none',\n\t\t\t\t// Origin-aware entrance (DESIGN_SPEC §10 / Emil standards): subtle scale + fade from the\n\t\t\t\t// cell corner, reusing the UI popover's tw-animate utilities for a consistent feel. Gated\n\t\t\t\t// on `positioned` so the overlay animates only after its measured position is applied.\n\t\t\t\tpositioned && 'animate-[fade-scale-in_var(--duration-moderate)_ease-out] motion-reduce:animate-none',\n\t\t\t\tshouldFlip ? 'origin-bottom-left' : 'origin-top-left'\n\t\t\t)}\n\t\t>\n\t\t\t{/* Provide the overlay geometry so editors (relation/image/geometry) can self-bound their\n\t\t\t internal scroll lists; without it they read maxHeight:0 and render unbounded (the\n\t\t\t relation infinite-scroll bug). Mirrors the canvas OverlayViewportGuard's provider. */}\n\t\t\t<OverlayMeasureContext.Provider value={overlayMeasure}>\n\t\t\t\t<EditorErrorGuard onClose={onCancel}>\n\t\t\t\t\t{/* overflow-VISIBLE, never auto/hidden: each editor renders its own rounded card with a\n\t\t\t\t\t `shadow-lg`, and a clipping wrapper the same size as the card squares off that shadow\n\t\t\t\t\t into the \"weird halo\" around the rounded corners. Editors self-bound their height\n\t\t\t\t\t (relation/image/json scroll internally), so the wrapper never needs to scroll. */}\n\t\t\t\t\t<EditorFocusTrap onEscape={onCancel} className={cn('overflow-visible', presetClass)}>\n\t\t\t\t\t\t{children}\n\t\t\t\t\t</EditorFocusTrap>\n\t\t\t\t</EditorErrorGuard>\n\t\t\t</OverlayMeasureContext.Provider>\n\t\t</div>,\n\t\tportalHost,\n\t);\n}\n","'use client';\n\nimport { Component, type ErrorInfo, type ReactNode } from 'react';\n\nimport { useSheetsContext } from '../../context/sheets-context';\nimport { sheetsLogger } from '../../utils/sheets-logger';\n\ntype SheetsOnError = (\n\terror: unknown,\n\tctx?: { source?: 'grid' | 'editor' | 'mutation' | 'upload'; tableName?: string },\n) => void;\n\ninterface EditorErrorBoundaryProps {\n\tchildren: ReactNode;\n\t/** Closes the overlay so the grid stays interactive after a failure. */\n\tonClose: () => void;\n\t/** Called when a render/chunk-load error is caught. Mirrors SheetsConfig.onError. */\n\tonError?: SheetsOnError;\n}\n\ninterface EditorErrorBoundaryState {\n\terror: unknown;\n}\n\n/**\n * Per-overlay-editor error boundary. Catches render throws AND React.lazy\n * chunk-load rejections inside a single overlay editor so they never reach the\n * grid-level SheetsErrorBoundary (which blanks the whole grid). It must wrap the\n * editor's own Suspense so lazy rejections surface here. Routes the error to the\n * host via onError and renders a tiny inline fallback with a Close button.\n */\nexport class EditorErrorBoundary extends Component<EditorErrorBoundaryProps, EditorErrorBoundaryState> {\n\tstate: EditorErrorBoundaryState = { error: null };\n\n\tstatic getDerivedStateFromError(error: unknown): EditorErrorBoundaryState {\n\t\treturn { error };\n\t}\n\n\tcomponentDidCatch(error: unknown, info: ErrorInfo): void {\n\t\tsheetsLogger().error('[sheets] editor render error', { error, componentStack: info.componentStack });\n\t\tthis.props.onError?.(error, { source: 'editor' });\n\t}\n\n\trender(): ReactNode {\n\t\tif (this.state.error == null) {\n\t\t\treturn this.props.children;\n\t\t}\n\t\treturn (\n\t\t\t<div className='bg-popover text-foreground flex flex-col gap-2 rounded-lg border p-3 text-sm shadow-lg'>\n\t\t\t\t<span className='text-muted-foreground'>Editor failed to load/render</span>\n\t\t\t\t<button\n\t\t\t\t\ttype='button'\n\t\t\t\t\tonClick={this.props.onClose}\n\t\t\t\t\tclassName='border-border/60 hover:bg-muted/60 self-end rounded-md border px-2.5 py-1 text-xs'\n\t\t\t\t>\n\t\t\t\t\tClose\n\t\t\t\t</button>\n\t\t\t</div>\n\t\t);\n\t}\n}\n\ninterface EditorErrorGuardProps {\n\t// Optional so `React.createElement(EditorErrorGuard, { onClose }, child)` type-checks;\n\t// children are forwarded positionally to the class boundary below.\n\tchildren?: ReactNode;\n\tonClose: () => void;\n}\n\n/**\n * Functional shim that sources `onError` from the sheets context. Overlay editors\n * render in Glide's portal but stay within the provider tree (same path the\n * relation/image editors use for `useSheetsContext`), so the host callback is\n * reachable here.\n */\nexport function EditorErrorGuard({ children, onClose }: EditorErrorGuardProps): ReactNode {\n\tconst { config } = useSheetsContext();\n\treturn (\n\t\t<EditorErrorBoundary onClose={onClose} onError={config.onError}>\n\t\t\t{children}\n\t\t</EditorErrorBoundary>\n\t);\n}\n","// The SINGLE edit-intent resolver — the host's one entry point for \"what happens\n// when this cell is activated?\". It replaces the host's brittle\n// `resolveNativeEditor(cell.meta?.cellType ?? 'text')` lookup (which mis-routed\n// EVERY non-text cell to TextEditor) with an AUTHORITATIVE, exhaustive mapping\n// from a `typeKey` (CellType) + the cell's readonly flag to exactly one of:\n// • { mode: 'inline-toggle' } — no overlay; the host commits `!currentBool`.\n// • { mode: 'inline-edit' } — no overlay; the host edits IN PLACE with a bare\n// single-line <input> (the SIMPLE text-representable\n// types: text-like + number-like). url/inet are NOT\n// here — they keep their specialised overlay editors.\n// • { mode: 'overlay', editor } — open the resolved native overlay editor.\n// • { mode: 'none' } — not editable (readonly / non-editable type).\n//\n// EXHAUSTIVENESS is structural: the buckets are DRIVEN OFF the canonical\n// cell-type-groups Sets (BOOLEAN_TYPES / NUMBER_TYPES / DATE_TIME_TYPES /\n// GEOMETRY_TYPES / MEDIA_TYPES / isArrayCellType / NON_EDITABLE_TYPES /\n// VIEWER_ONLY_TYPES), never a hand-maintained list — so adding a member to a\n// group automatically routes it here. Every CellType in cell-types/types.ts lands\n// in exactly one bucket; anything unrecognised falls through to the text default\n// (TextEditor), matching the `unknown` cell-type contract.\n//\n// CONSUMER OVERRIDE: a registered `def.editorComponent` for the typeKey (looked up\n// via the injected `consumer`, i.e. `registry.getEditorComponent`) WINS as the\n// overlay editor for any type that opens an overlay — same precedence the glide\n// path gave `def.editor`. It does NOT override inline-toggle or readonly `none`.\n\nimport type { ComponentType } from 'react';\n\nimport {\n\tBOOLEAN_TYPES,\n\tDATE_TIME_TYPES,\n\tGEOMETRY_TYPES,\n\tMEDIA_TYPES,\n\tNON_EDITABLE_TYPES,\n\tNUMBER_TYPES,\n\tVIEWER_ONLY_TYPES,\n\tisArrayCellType,\n} from '../../cell-types/cell-type-groups';\nimport { DOM_EDITOR_REGISTRY, type NativeEditor } from './editor-registry-dom';\nimport type { EditorProps } from './editor-props';\n\nexport type EditIntent =\n\t| { mode: 'overlay'; editor: NativeEditor }\n\t| { mode: 'inline-toggle' }\n\t| { mode: 'inline-edit' }\n\t| { mode: 'none' };\n\ntype EditorConsumer = (typeKey: string) => ComponentType<EditorProps> | undefined;\n\n/** Build the overlay intent for a typeKey: consumer override wins, else the registry entry. */\nfunction overlay(typeKey: string, consumer: EditorConsumer | undefined): EditIntent {\n\tconst editor = (consumer?.(typeKey) as NativeEditor | undefined) ?? DOM_EDITOR_REGISTRY[typeKey];\n\t// No editor resolved for a type that should open one — degrade to no-edit rather\n\t// than portal an empty overlay. (Cannot happen for the buckets below: every one\n\t// has a DOM_EDITOR_REGISTRY entry.)\n\treturn editor ? { mode: 'overlay', editor } : { mode: 'none' };\n}\n\n/**\n * Simple text-representable types (text-like + number-like) edit IN PLACE with a bare\n * <input> — no overlay. A registered consumer editor for the typeKey still WINS as an\n * overlay editor (same override precedence the overlay types give `def.editor`); only\n * the built-in path becomes inline. The host derives text-vs-number from the cell kind.\n */\nfunction inlineOrOverride(typeKey: string, consumer: EditorConsumer | undefined): EditIntent {\n\tconst editor = consumer?.(typeKey) as NativeEditor | undefined;\n\tif (editor) return { mode: 'overlay', editor };\n\treturn { mode: 'inline-edit' };\n}\n\n/**\n * Resolve the edit intent for a cell.\n *\n * @param typeKey - resolved CellType key (the `SheetsCellResolution.typeKey`).\n * @param opts - `readonly` mirrors the cell's readonly flag (READONLY_CONDITIONS / draft-id / relation-not-inline).\n * @param consumer - optional per-instance editor override (`registry.getEditorComponent`).\n */\nexport function resolveEditIntent(\n\ttypeKey: string,\n\topts: { readonly?: boolean },\n\tconsumer?: EditorConsumer,\n): EditIntent {\n\t// 1) Readonly cell — never editable, regardless of type (matches the host already\n\t// skipping `cell.readonly`). Also covers NON_EDITABLE types that are not viewers.\n\tif (opts.readonly) return { mode: 'none' };\n\n\t// 2) Non-editable types that are NOT viewer-only → no edit. (tsvector is in\n\t// NON_EDITABLE_TYPES but is viewer-only, so it falls through to its viewer\n\t// overlay below; this guard catches any future non-viewer non-editable type.)\n\tif (NON_EDITABLE_TYPES.has(typeKey) && !VIEWER_ONLY_TYPES.has(typeKey)) return { mode: 'none' };\n\n\t// 3) Booleans → inline toggle (no overlay; the host commits `!currentBool`).\n\tif (BOOLEAN_TYPES.has(typeKey)) return { mode: 'inline-toggle' };\n\n\t// 4) Number-like → inline edit (simple text-representable). Overlay families below stay\n\t// overlay, driven off the canonical groups so they stay exhaustive.\n\tif (NUMBER_TYPES.has(typeKey)) return inlineOrOverride(typeKey, consumer);\n\tif (DATE_TIME_TYPES.has(typeKey)) return overlay(typeKey, consumer);\n\tif (isArrayCellType(typeKey)) return overlay(typeKey, consumer);\n\tif (GEOMETRY_TYPES.has(typeKey)) return overlay(typeKey, consumer);\n\tif (MEDIA_TYPES.has(typeKey)) return overlay(typeKey, consumer);\n\n\t// 5) Singleton overlay types (each has a DOM_EDITOR_REGISTRY entry).\n\tif (typeKey === 'interval') return overlay(typeKey, consumer);\n\tif (typeKey === 'json' || typeKey === 'jsonb') return overlay(typeKey, consumer);\n\tif (typeKey === 'inet') return overlay(typeKey, consumer);\n\tif (typeKey === 'relation') return overlay(typeKey, consumer);\n\tif (typeKey === 'url') return overlay(typeKey, consumer);\n\t// tsvector — VIEWER_ONLY, but still opens a read-only viewer overlay.\n\tif (VIEWER_ONLY_TYPES.has(typeKey)) return overlay(typeKey, consumer);\n\n\t// 6) Text-like default (text/textarea/email/phone/citext/bpchar/uuid/color/\n\t// origin/unknown + anything unrecognised) → inline edit. `color` is NOT a real\n\t// backend data type — just a hex/text string — so it edits inline too (no dedicated\n\t// color editor). A consumer override on a text-like typeKey still wins as an overlay\n\t// editor via `inlineOrOverride`; otherwise the cell edits in place.\n\treturn inlineOrOverride(typeKey, consumer);\n}\n","/**\n * Range-value extractor — pulls the matrix of cell values covered by a\n * {@link SelectionRect} out of the (possibly virtualized) row array.\n *\n * PURE + SSR-safe — no React, no DOM. The BOUNDED contract is load-bearing: it\n * reads only the cells inside the rect (w×h), never enumerates `rows.length`, so\n * a paste/fill/copy targeting a few cells of a million-row grid stays O(w·h). An\n * unfetched proxy row (infinite-mode) reads as `null` -> its cells come back as\n * `null`; an out-of-range column reads as `null` too.\n *\n * Reused by P3 (paste/fill writes the same coordinate matrix back) and P4 (copy\n * serializes {@link toTSV}).\n */\n\nimport type { SelectionRect } from './selection-model';\n\n/** The extracted block: a `values[row][col]` matrix plus the row indices + col keys it covers. */\nexport interface ExtractedRange {\n\t/** `values[r][c]` — outer index aligns with `rows[r]`, inner with `cols[c]`. */\n\tvalues: unknown[][];\n\t/** Absolute row indices covered (y .. y+height-1). */\n\trows: number[];\n\t/** Column keys covered (columnKeys[x .. x+width-1]). */\n\tcols: string[];\n}\n\n/**\n * Read every cell inside `range` (half-open: x/width = cols, y/height = rows) from\n * `rows` keyed by `columnKeys`. `getDisplay`, when supplied, maps the raw value to\n * the value to emit (e.g. a display string for copy) — defaults to the raw value.\n * Null-safe for unfetched proxy rows and out-of-range columns.\n */\nexport function getCellsInRange(\n\trange: SelectionRect,\n\trows: readonly unknown[],\n\tcolumnKeys: readonly string[],\n\tgetDisplay?: (value: unknown, rowIndex: number, colKey: string) => unknown,\n): ExtractedRange {\n\tconst cols: string[] = [];\n\tfor (let c = 0; c < range.width; c++) {\n\t\tcols.push(columnKeys[range.x + c]);\n\t}\n\n\tconst rowIndices: number[] = [];\n\tconst values: unknown[][] = [];\n\tfor (let r = 0; r < range.height; r++) {\n\t\tconst rowIndex = range.y + r;\n\t\trowIndices.push(rowIndex);\n\t\tconst rowData = rows[rowIndex] as Record<string, unknown> | null | undefined;\n\t\tconst line: unknown[] = [];\n\t\tfor (let c = 0; c < range.width; c++) {\n\t\t\tconst colKey = cols[c];\n\t\t\tconst raw = rowData && colKey != null ? rowData[colKey] : null;\n\t\t\tconst cellValue = raw === undefined ? null : raw;\n\t\t\tline.push(getDisplay ? getDisplay(cellValue, rowIndex, colKey) : cellValue);\n\t\t}\n\t\tvalues.push(line);\n\t}\n\n\treturn { values, rows: rowIndices, cols };\n}\n\n/**\n * Serialize a value matrix to TSV (tab-joined cols, newline-joined rows). Each value\n * is stringified; `null`/`undefined` become an empty cell. Spreadsheet-paste shape —\n * reused by P4 copy.\n */\nexport function toTSV(values: readonly (readonly unknown[])[]): string {\n\treturn values\n\t\t.map((row) => row.map((cell) => (cell == null ? '' : String(cell))).join('\\t'))\n\t\t.join('\\n');\n}\n","/**\n * Fill-math — REPLICATE a source row/column across a target range (P4 Phase 3).\n *\n * PURE + SSR-safe (no React, no DOM) — the analog of {@link getCellsInRange} on the\n * WRITE side: it reads the seed cells out of the raw `rows` array (null-safe for\n * unfetched proxy rows / out-of-range columns, exactly like the extractor) and emits\n * the {@link CellWrite}[] the command hands to `commitCells` (readonly/UUID skips +\n * undo live inside that batch, never here).\n *\n * SCOPE — value REPLICATION only. Numeric/date SERIES detection (1,2 -> 3,4 ; Jan,Feb\n * -> Mar) is DEFERRED: every filled cell is a verbatim copy of the seed.\n */\n\nimport type { SelectionRect } from './selection-model';\nimport type { CellWrite } from '../grid/hooks/use-batch-commit';\n\n/** Read one raw cell value, null-safe (mirrors getCellsInRange: undefined -> null). */\nfunction readCell(rows: readonly unknown[], rowIndex: number, colKey: string): unknown {\n\tconst rowData = rows[rowIndex] as Record<string, unknown> | null | undefined;\n\tconst raw = rowData && colKey != null ? rowData[colKey] : null;\n\treturn raw === undefined ? null : raw;\n}\n\n/**\n * Fill DOWN: SOURCE = the TOP row of `range` (y). For each col `x..x+width-1`, replicate\n * the seed cell value into every row `y+1..y+height-1`. Returns the writes column-major\n * is not required — emitted row-major (top-to-bottom within each... actually outer loop is\n * target rows, inner is cols) so commitCells coalesces per row. A single-row range yields\n * no writes (nothing below the seed).\n */\nexport function fillDownWrites(\n\trange: SelectionRect,\n\trows: readonly unknown[],\n\tcolumnKeys: readonly string[],\n): CellWrite[] {\n\tconst writes: CellWrite[] = [];\n\tconst sourceRow = range.y;\n\tfor (let targetRow = range.y + 1; targetRow < range.y + range.height; targetRow++) {\n\t\tfor (let c = 0; c < range.width; c++) {\n\t\t\tconst colKey = columnKeys[range.x + c];\n\t\t\tif (colKey == null) continue;\n\t\t\twrites.push({ rowIndex: targetRow, colKey, value: readCell(rows, sourceRow, colKey) });\n\t\t}\n\t}\n\treturn writes;\n}\n\n/**\n * Fill RIGHT: SOURCE = the LEFT column of `range` (x). For each col `x+1..x+width-1`,\n * replicate that column's seed (the value in the LEFT column of the SAME row) rightward\n * across every row `y..y+height-1`. A single-column range yields no writes.\n */\nexport function fillRightWrites(\n\trange: SelectionRect,\n\trows: readonly unknown[],\n\tcolumnKeys: readonly string[],\n): CellWrite[] {\n\tconst writes: CellWrite[] = [];\n\tconst sourceColKey = columnKeys[range.x];\n\tfor (let r = 0; r < range.height; r++) {\n\t\tconst rowIndex = range.y + r;\n\t\tconst seed = sourceColKey == null ? null : readCell(rows, rowIndex, sourceColKey);\n\t\tfor (let c = 1; c < range.width; c++) {\n\t\t\tconst colKey = columnKeys[range.x + c];\n\t\t\tif (colKey == null) continue;\n\t\t\twrites.push({ rowIndex, colKey, value: seed });\n\t\t}\n\t}\n\treturn writes;\n}\n\n/**\n * Bulk-edit: FAN a single committed `value` across every cell of `range` (the classic\n * \"select range, type, commit, fill\" edit). Unlike fill-down/right this reads NO seed\n * out of the data — every cell in the range gets the SAME `value` (per-column coercion\n * happens downstream in commitCells/resolveServerPatch). The write set is the COMPLETE\n * range INCLUDING the active cell, so the caller does ONE commitCells (never a single\n * commit + a separate range commit) — no double-write, one optimistic patch, one undo.\n * Out-of-bounds column slots are skipped (mirrors the other fill writers).\n */\nexport function bulkEditWrites(\n\trange: SelectionRect,\n\tvalue: unknown,\n\tcolumnKeys: readonly string[],\n): CellWrite[] {\n\tconst writes: CellWrite[] = [];\n\tfor (let r = 0; r < range.height; r++) {\n\t\tconst rowIndex = range.y + r;\n\t\tfor (let c = 0; c < range.width; c++) {\n\t\t\tconst colKey = columnKeys[range.x + c];\n\t\t\tif (colKey == null) continue;\n\t\t\twrites.push({ rowIndex, colKey, value });\n\t\t}\n\t}\n\treturn writes;\n}\n\n/**\n * Fill-handle DRAG geometry — extend `from` toward target cell `[col,row]` along the\n * DOMINANT axis (v1 supports one axis at a time). PURE.\n *\n * The axis is chosen by which direction the target overshoots `from` the most: if the\n * vertical overshoot (below the bottom / above the top) exceeds the horizontal one we\n * fill VERTICALLY (the rect's height grows); otherwise HORIZONTALLY (width grows). Ties\n * and a target already inside `from` collapse to `from` (no extension). The off-axis span\n * is left exactly as `from`'s.\n */\nexport function extendedFillRect(from: SelectionRect, target: readonly [number, number]): SelectionRect {\n\tconst [col, row] = target;\n\tconst bottom = from.y + from.height - 1;\n\tconst right = from.x + from.width - 1;\n\t// Overshoot past the source band on each axis (0 when target is within the band).\n\tconst vOver = row > bottom ? row - bottom : from.y - row > 0 ? from.y - row : 0;\n\tconst hOver = col > right ? col - right : from.x - col > 0 ? from.x - col : 0;\n\tif (vOver === 0 && hOver === 0) return from;\n\tif (vOver >= hOver) {\n\t\t// Vertical fill: grow the height toward `row`, keep x/width.\n\t\tconst y = Math.min(from.y, row);\n\t\tconst yEnd = Math.max(bottom, row);\n\t\treturn { x: from.x, y, width: from.width, height: yEnd - y + 1 };\n\t}\n\t// Horizontal fill: grow the width toward `col`, keep y/height.\n\tconst x = Math.min(from.x, col);\n\tconst xEnd = Math.max(right, col);\n\treturn { x, y: from.y, width: xEnd - x + 1, height: from.height };\n}\n\n/**\n * Replicate the SOURCE band `from` across the NEW cells of `extended` (the cells in\n * `extended` that are NOT in `from`). For a vertical extension each new row copies the\n * matching column's value from the NEAREST source row (the band repeats); for a horizontal\n * extension each new column copies the matching row's nearest source column. Value\n * REPLICATION only — SERIES detection DEFERRED. Skips the `from` band (already populated).\n */\nexport function fillDragWrites(\n\tfrom: SelectionRect,\n\textended: SelectionRect,\n\trows: readonly unknown[],\n\tcolumnKeys: readonly string[],\n): CellWrite[] {\n\tconst writes: CellWrite[] = [];\n\tfor (let ty = extended.y; ty < extended.y + extended.height; ty++) {\n\t\tfor (let tx = extended.x; tx < extended.x + extended.width; tx++) {\n\t\t\t// Inside the source band — already has its value, never overwrite.\n\t\t\tif (tx >= from.x && tx < from.x + from.width && ty >= from.y && ty < from.y + from.height) continue;\n\t\t\tconst colKey = columnKeys[tx];\n\t\t\tif (colKey == null) continue;\n\t\t\t// Tile the source band: map the target back into the band on each axis.\n\t\t\tconst srcCol = from.x + ((tx - from.x) % from.width + from.width) % from.width;\n\t\t\tconst srcRow = from.y + ((ty - from.y) % from.height + from.height) % from.height;\n\t\t\tconst srcKey = columnKeys[srcCol];\n\t\t\twrites.push({ rowIndex: ty, colKey, value: srcKey == null ? null : readCell(rows, srcRow, srcKey) });\n\t\t}\n\t}\n\treturn writes;\n}\n","/**\n * TSV parse + tile — the INVERSE of {@link toTSV} (cell-extract.ts), used by the\n * clipboard.paste command. PURE + SSR-safe (no React, no DOM, no clipboard).\n *\n * `parseTSV` round-trips a `toTSV` string back into a `string[][]` matrix (split rows\n * on `\\n`, cols on `\\t`), tolerating ONE trailing newline (a spreadsheet copy ends the\n * last row with `\\n`) so it does not yield a spurious empty trailing row. `tileMatrix`\n * implements spreadsheet fill semantics: a 1×N / N×1 source REPEATS to fill a larger\n * target, otherwise the source is written from the anchor as-is.\n */\n\n/**\n * Parse a TSV string into a `string[][]` matrix (rows × cols). Splits rows on `\\n`\n * (a lone trailing `\\n` is dropped so it does not add an empty row) and cols on `\\t`.\n * `\\r` is stripped so a CRLF clipboard payload parses the same as LF. An empty string\n * yields a single empty cell `[['']]` (mirrors a 1×1 blank paste).\n */\nexport function parseTSV(text: string): string[][] {\n\tconst normalized = text.replace(/\\r\\n?/g, '\\n');\n\t// Drop a single trailing newline so a spreadsheet copy's terminal `\\n` is not an extra row.\n\tconst body = normalized.endsWith('\\n') ? normalized.slice(0, -1) : normalized;\n\treturn body.split('\\n').map((line) => line.split('\\t'));\n}\n\n/**\n * Tile `source` to fill a `targetW × targetH` region (spreadsheet fill semantics):\n * • a 1×N source (single row) repeats DOWN to fill targetH rows.\n * • an N×1 source (single col) repeats ACROSS to fill targetW cols.\n * • a 1×1 source repeats in both axes.\n * • any other (genuinely 2-D) source is returned unchanged — the caller writes it\n * from the anchor as-is (no tiling), matching spreadsheet \"paste block\" behavior.\n *\n * Only repeats when the source is strictly smaller than the target on the repeating\n * axis; a source already >= the target is left intact (clamping is the caller's job).\n */\nexport function tileMatrix(source: string[][], targetW: number, targetH: number): string[][] {\n\tconst srcH = source.length;\n\tconst srcW = srcH > 0 ? source[0].length : 0;\n\tif (srcH === 0 || srcW === 0) return source;\n\n\tconst isSingleRow = srcH === 1;\n\tconst isSingleCol = srcW === 1;\n\t// Only 1×N / N×1 (and 1×1) sources tile; a real 2-D block pastes as-is.\n\tif (!isSingleRow && !isSingleCol) return source;\n\n\tconst outH = isSingleRow && targetH > srcH ? targetH : srcH;\n\tconst outW = isSingleCol && targetW > srcW ? targetW : srcW;\n\n\tconst out: string[][] = [];\n\tfor (let r = 0; r < outH; r++) {\n\t\tconst srcRow = source[r % srcH];\n\t\tconst line: string[] = [];\n\t\tfor (let c = 0; c < outW; c++) {\n\t\t\tline.push(srcRow[c % srcW]);\n\t\t}\n\t\tout.push(line);\n\t}\n\treturn out;\n}\n","/**\n * DEFAULT_COMMANDS + createGridCommandRegistry (P4 Phase 1).\n *\n * Each command body is LIFTED VERBATIM from grid/sheets.tsx's handleGridKeyDown /\n * handleActivateCell / openEditor / openEditorAtActiveCell branches — same dispatcher\n * calls, same anchor resets, same clamp/scroll order. The handler's local guards\n * (`if (rows === 0 || colCount === 0) return`) are preserved as `canRun` where the\n * original returned WITHOUT preventing default, and inline where the original DID\n * prevent default first (Ctrl+A / arrows / nav: the original called preventDefault()\n * before the empty-grid early return, so the no-op must still preventDefault — that is\n * the core's job once the command resolves, and the body simply returns early).\n *\n * Phase 1 is a refactor: these bodies call `ctx.<dispatcher>` (the existing stable fns).\n */\n\nimport { computeKeyNavTarget, emptySheetsSelection, selectAllCells } from '../selection/selection-model';\nimport type { SelectionRect } from '../selection/selection-model';\nimport { parseTSV, tileMatrix } from '../selection/tsv';\nimport { fillDownWrites, fillRightWrites, extendedFillRect, fillDragWrites } from '../selection/fill';\nimport type { CellWrite } from '../grid/hooks/use-batch-commit';\nimport type { GridCommand, GridCommandRegistry } from './types';\nimport type { GridCommandContext, CellMatrix } from './context';\n\n/** Payload for `cell.activate` / `cell.extendToClicked` (pointer). */\nexport interface CellPointerPayload {\n\tcol: number;\n\trow: number;\n}\n\n/** Payload for `editor.open` (dblclick). */\nexport interface EditorOpenPayload {\n\trowIndex: number;\n\tcolKey: string;\n\tanchorRect: DOMRect;\n\tinitialText?: string;\n}\n\n/** Payload for `editor.typeToEdit` (printable key sentinel). */\nexport interface TypeToEditPayload {\n\tchar: string;\n}\n\n/** Payload for `cell.navAbsolute` (Tab/Home/End/PageUp/PageDown). */\nexport interface NavAbsolutePayload {\n\tkey: string;\n\tctrlOrMeta: boolean;\n\tshift: boolean;\n\t/** Visible page span (rows); the funnel derives this from the scroll element clientHeight. */\n\tpageRows: number;\n}\n\n/** Payload for `header.sortToggle`. */\nexport interface SortTogglePayload {\n\tcolKey: string;\n}\n\n/** Payload for `rowmarker.toggleRow`. */\nexport interface ToggleRowPayload {\n\trowIndex: number;\n\tshift: boolean;\n}\n\n/** Payload for `fill.drag` (fill-handle nub release). `from` = source band, `to` = `[col,row]` under the pointer. */\nexport interface FillDragPayload {\n\tfrom: SelectionRect;\n\tto: [number, number];\n}\n\n/**\n * The minimal `DataTransfer` slice the clipboard commands read/write — `ClipboardEvent.clipboardData`\n * conforms (so does a test stub). Kept narrow so the command never depends on the full DOM type.\n */\nexport interface ClipboardLike {\n\tgetData(format: string): string;\n\tsetData(format: string, data: string): void;\n}\n\n/** Payload for `clipboard.copy` / `clipboard.cut` / `clipboard.paste` (native clipboard event). */\nexport interface ClipboardPayload {\n\tclipboard: ClipboardLike | null;\n}\n\n/** Shared empty-grid guard (the original `rows === 0 || colCount === 0` short-circuit). */\nfunction gridNonEmpty(ctx: GridCommandContext): boolean {\n\treturn ctx.rowCount > 0 && ctx.colCount > 0;\n}\n\n/**\n * The cell range the clipboard commands act on: the active selection range when present,\n * else a 1×1 rect at the active cell. `null` when there is no active cell (empty grid /\n * no cursor) — the copy/cut/paste `canRun` guards return false on null.\n */\nfunction clipboardRange(ctx: GridCommandContext): SelectionRect | null {\n\tconst range = ctx.selection?.current?.range;\n\tif (range) return range;\n\tconst cell = ctx.activeCell;\n\tif (!cell) return null;\n\treturn { x: cell[0], y: cell[1], width: 1, height: 1 };\n}\n\n/** Build a `null` write for every cell in `rect` (clamped to the column keys). */\nfunction clearRangeWrites(rect: SelectionRect, columnKeys: readonly string[]): CellWrite[] {\n\tconst writes: CellWrite[] = [];\n\tfor (let r = 0; r < rect.height; r++) {\n\t\tfor (let c = 0; c < rect.width; c++) {\n\t\t\tconst colKey = columnKeys[rect.x + c];\n\t\t\tif (colKey == null) continue;\n\t\t\twrites.push({ rowIndex: rect.y + r, colKey, value: null });\n\t\t}\n\t}\n\treturn writes;\n}\n\n/** True when the async `navigator.clipboard` API is reachable (secure context, browser). */\nfunction navigatorClipboard(): Clipboard | null {\n\treturn typeof navigator !== 'undefined' && navigator.clipboard ? navigator.clipboard : null;\n}\n\n/** The `null` writes that clear every cell of a copied/cut matrix (cut's source clear). */\nfunction cutRangeWrites(matrix: CellMatrix): CellWrite[] {\n\tconst writes: CellWrite[] = [];\n\tfor (let r = 0; r < matrix.rows.length; r++) {\n\t\tfor (let c = 0; c < matrix.cols.length; c++) {\n\t\t\tconst colKey = matrix.cols[c];\n\t\t\tif (colKey == null) continue;\n\t\t\twrites.push({ rowIndex: matrix.rows[r], colKey, value: null });\n\t\t}\n\t}\n\treturn writes;\n}\n\n/**\n * Tile a parsed TSV `source` onto the target and build the clamped writes — the shared body\n * of both paste paths (native event + navigator fallback). `anchor` is the active cell's\n * top-left; `range` (when present + larger than the source) drives tiling.\n */\nfunction pasteWrites(ctx: GridCommandContext, anchor: readonly [number, number], text: string): CellWrite[] {\n\tconst source = parseTSV(text);\n\tconst range = ctx.selection?.current?.range;\n\tconst targetW = range ? range.width : source[0]?.length ?? 0;\n\tconst targetH = range ? range.height : source.length;\n\tconst matrix = tileMatrix(source, targetW, targetH);\n\n\tconst [anchorCol, anchorRow] = anchor;\n\tconst writes: CellWrite[] = [];\n\tfor (let r = 0; r < matrix.length; r++) {\n\t\tconst rowIndex = anchorRow + r;\n\t\tif (rowIndex >= ctx.rowCount) break; // clamp to grid bottom\n\t\tconst line = matrix[r];\n\t\tfor (let c = 0; c < line.length; c++) {\n\t\t\tconst colIndex = anchorCol + c;\n\t\t\tif (colIndex >= ctx.colCount) break; // clamp to grid right\n\t\t\tconst colKey = ctx.columnKeys[colIndex];\n\t\t\tif (colKey == null) continue;\n\t\t\twrites.push({ rowIndex, colKey, value: line[c] });\n\t\t}\n\t}\n\treturn writes;\n}\n\n/**\n * The default command set. Authored as plain objects (no classes). Frozen array so the\n * registry factory can clone it; consumer overrides replace by id (Phase 2 seam).\n */\nexport const DEFAULT_COMMANDS: GridCommand[] = [\n\t// ---- UNDO / REDO (lifted: handleGridKeyDown undo/redo branch) ----\n\t{\n\t\tid: 'edit.undo',\n\t\trun: (ctx) => {\n\t\t\tvoid ctx.undo();\n\t\t},\n\t},\n\t{\n\t\tid: 'edit.redo',\n\t\trun: (ctx) => {\n\t\t\tvoid ctx.redo();\n\t\t},\n\t},\n\n\t// ---- SELECT ALL (lifted: Ctrl/Cmd+A branch) ----\n\t{\n\t\tid: 'selection.all',\n\t\tcanRun: gridNonEmpty,\n\t\trun: (ctx) => {\n\t\t\tctx.setAnchor([0, 0]);\n\t\t\tctx.setSelection(selectAllCells(ctx.selection ?? emptySheetsSelection, ctx.colCount, ctx.rowCount));\n\t\t},\n\t},\n\n\t// ---- CLIPBOARD COPY (serialize range → TSV → clipboard) ----\n\t// Serializes the active range (or the 1×1 active cell) to TSV. TWO paths:\n\t// • NATIVE: `payload.clipboard` is the `copy` event's DataTransfer — write it synchronously.\n\t// preventDefault happens in the dispatch CORE (so the browser does not ALSO copy its own —\n\t// empty — selection).\n\t// • MENU/PROGRAMMATIC: no DataTransfer (the context menu has no native event) — fall back to\n\t// the async `navigator.clipboard.writeText` (rejection caught → no-op; secure-context gated).\n\t// canRun gates on an active cell/range existing.\n\t{\n\t\tid: 'clipboard.copy',\n\t\tcanRun: (ctx) => clipboardRange(ctx) !== null,\n\t\trun: (ctx, payload) => {\n\t\t\tconst range = clipboardRange(ctx);\n\t\t\tif (!range) return;\n\t\t\tconst tsv = ctx.toTSV(ctx.getCellsInRange(range).values);\n\t\t\tconst clipboard = (payload as ClipboardPayload | undefined)?.clipboard;\n\t\t\tif (clipboard) {\n\t\t\t\tclipboard.setData('text/plain', tsv);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst nav = navigatorClipboard();\n\t\t\tif (nav) return nav.writeText(tsv).catch(() => {});\n\t\t},\n\t},\n\n\t// ---- CLIPBOARD CUT (copy serialize + clear the source range) ----\n\t// Runs the copy serialize (native DataTransfer or navigator fallback, same branch as copy),\n\t// then commits `null` across every cell of the source range as ONE undo-aware batch\n\t// (commitCells skips readonly/UUID cells internally). Same range source.\n\t{\n\t\tid: 'clipboard.cut',\n\t\tcanRun: (ctx) => clipboardRange(ctx) !== null,\n\t\trun: (ctx, payload) => {\n\t\t\tconst range = clipboardRange(ctx);\n\t\t\tif (!range) return;\n\t\t\tconst matrix = ctx.getCellsInRange(range);\n\t\t\tconst tsv = ctx.toTSV(matrix.values);\n\t\t\tconst writes = cutRangeWrites(matrix);\n\t\t\tconst clipboard = (payload as ClipboardPayload | undefined)?.clipboard;\n\t\t\tif (clipboard) {\n\t\t\t\tclipboard.setData('text/plain', tsv);\n\t\t\t\tvoid ctx.commitCells(writes);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst nav = navigatorClipboard();\n\t\t\tif (!nav) return;\n\t\t\t// Clear only once the write resolves so a clipboard rejection leaves the source intact.\n\t\t\treturn nav.writeText(tsv).then(() => {\n\t\t\t\tvoid ctx.commitCells(writes);\n\t\t\t}).catch(() => {});\n\t\t},\n\t},\n\n\t// ---- CLIPBOARD PASTE (parse TSV → tile → commitCells) ----\n\t// Parses the clipboard TSV, TILES it onto the target (a 1×N / N×1 source repeats to fill a\n\t// larger selection range; a 2-D block writes from the anchor as-is), clamps to grid bounds, and\n\t// commits ONE batch (single optimistic patch + coalesced per-row mutations + ONE undo entry).\n\t// commitCells skips readonly/UUID cells. The anchor is the active cell's top-left. TWO paths:\n\t// • NATIVE: `payload.clipboard` is the `paste` event's DataTransfer — read it synchronously.\n\t// • MENU/PROGRAMMATIC: no DataTransfer — fall back to async `navigator.clipboard.readText`\n\t// (rejection caught → no-op; secure-context gated).\n\t{\n\t\tid: 'clipboard.paste',\n\t\tcanRun: (ctx) => ctx.activeCell != null,\n\t\trun: (ctx, payload) => {\n\t\t\tconst anchor = ctx.activeCell;\n\t\t\tif (!anchor) return;\n\t\t\tconst clipboard = (payload as ClipboardPayload | undefined)?.clipboard;\n\t\t\tif (clipboard) {\n\t\t\t\tconst text = clipboard.getData('text/plain');\n\t\t\t\tif (!text) return;\n\t\t\t\tconst writes = pasteWrites(ctx, anchor, text);\n\t\t\t\tif (writes.length) void ctx.commitCells(writes);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst nav = navigatorClipboard();\n\t\t\tif (!nav) return;\n\t\t\treturn nav.readText().then((text) => {\n\t\t\t\tif (!text) return;\n\t\t\t\tconst writes = pasteWrites(ctx, anchor, text);\n\t\t\t\tif (writes.length) void ctx.commitCells(writes);\n\t\t\t}).catch(() => {});\n\t\t},\n\t},\n\n\t// ---- CELL CLEAR (Delete / Backspace: write null over the active range) ----\n\t// range = the active selection range, else a 1×1 rect at the active cell. Builds a\n\t// {rowIndex, colKey, value: null} write for every cell in the rect and commits ONE\n\t// undo-aware batch (commitCells skips readonly/UUID internally; non-nullable columns\n\t// reject server-side and the optimistic patch reverts — null is the DB-clear default).\n\t// canRun gates on an active cell/range existing.\n\t{\n\t\tid: 'cell.clear',\n\t\tcanRun: (ctx) => clipboardRange(ctx) !== null,\n\t\trun: (ctx) => {\n\t\t\tconst range = clipboardRange(ctx);\n\t\t\tif (!range) return;\n\t\t\tconst writes = clearRangeWrites(range, ctx.columnKeys);\n\t\t\tif (writes.length) void ctx.commitCells(writes);\n\t\t},\n\t},\n\n\t// ---- FILL DOWN (Mod+D: replicate the TOP row of the range downward) ----\n\t// SOURCE = the range's top row; every lower row in the range gets the seed value of the\n\t// column above it. ONE undo-aware batch via commitCells (readonly/UUID skipped internally).\n\t// SCOPE: value replication only — numeric/date SERIES detection is DEFERRED.\n\t{\n\t\tid: 'fill.down',\n\t\tcanRun: (ctx) => {\n\t\t\tconst range = ctx.selection?.current?.range;\n\t\t\treturn !!range && range.height > 1;\n\t\t},\n\t\trun: (ctx) => {\n\t\t\tconst range = ctx.selection?.current?.range;\n\t\t\tif (!range) return;\n\t\t\tconst writes = fillDownWrites(range, ctx.combinedRows, ctx.columnKeys);\n\t\t\tif (writes.length) void ctx.commitCells(writes);\n\t\t},\n\t},\n\n\t// ---- FILL RIGHT (Mod+R: replicate the LEFT column of the range rightward) ----\n\t// SOURCE = the range's left column; every column to its right gets that row's left-column\n\t// seed. ONE undo-aware batch. SCOPE: value replication only — SERIES detection DEFERRED.\n\t{\n\t\tid: 'fill.right',\n\t\tcanRun: (ctx) => {\n\t\t\tconst range = ctx.selection?.current?.range;\n\t\t\treturn !!range && range.width > 1;\n\t\t},\n\t\trun: (ctx) => {\n\t\t\tconst range = ctx.selection?.current?.range;\n\t\t\tif (!range) return;\n\t\t\tconst writes = fillRightWrites(range, ctx.combinedRows, ctx.columnKeys);\n\t\t\tif (writes.length) void ctx.commitCells(writes);\n\t\t},\n\t},\n\n\t// ---- FILL DRAG (fill-handle nub release: extend `from` toward `to`, tile the source) ----\n\t// The pointer-driven analogue of fill.down/right: extend the SOURCE band toward the dropped\n\t// cell along the dominant axis, REPLICATE the band across the new cells (one undo-aware batch),\n\t// then WIDEN the selection to the extended rect so the band grows to match. canRun gates on a\n\t// payload (from + to) being present. SCOPE: value replication only — SERIES detection DEFERRED.\n\t{\n\t\tid: 'fill.drag',\n\t\tcanRun: (_ctx, payload) => {\n\t\t\tconst p = payload as FillDragPayload | undefined;\n\t\t\treturn !!p && !!p.from && !!p.to;\n\t\t},\n\t\trun: (ctx, payload) => {\n\t\t\tconst { from, to } = payload as FillDragPayload;\n\t\t\tconst extended = extendedFillRect(from, to);\n\t\t\t// Target inside the source band — nothing to extend.\n\t\t\tif (extended.width === from.width && extended.height === from.height && extended.x === from.x && extended.y === from.y)\n\t\t\t\treturn;\n\t\t\tconst writes = fillDragWrites(from, extended, ctx.combinedRows, ctx.columnKeys);\n\t\t\tif (writes.length) void ctx.commitCells(writes);\n\t\t\t// Grow the band: active cell parks on the far corner, range becomes the extended rect.\n\t\t\tconst base = ctx.selection ?? emptySheetsSelection;\n\t\t\tctx.setSelection({\n\t\t\t\t...base,\n\t\t\t\tcurrent: {\n\t\t\t\t\tcell: [extended.x + extended.width - 1, extended.y + extended.height - 1],\n\t\t\t\t\trange: extended,\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t},\n\n\t// ---- ARROW MOVE (plain arrow: setAnchor + moveActiveCell + scroll) ----\n\t// Each direction is its own named command; the funnel resolves the arrow key to it.\n\tmakeMoveCommand('cell.moveUp', 0, -1),\n\tmakeMoveCommand('cell.moveDown', 0, 1),\n\tmakeMoveCommand('cell.moveLeft', -1, 0),\n\tmakeMoveCommand('cell.moveRight', 1, 0),\n\n\t// ---- ARROW EXTEND (shift+arrow: extendToCell + scroll) ----\n\tmakeExtendCommand('cell.extendUp', 0, -1),\n\tmakeExtendCommand('cell.extendDown', 0, 1),\n\tmakeExtendCommand('cell.extendLeft', -1, 0),\n\tmakeExtendCommand('cell.extendRight', 1, 0),\n\n\t// ---- ABSOLUTE NAV (Tab/Home/End/PageUp/PageDown: computeKeyNavTarget) ----\n\t{\n\t\tid: 'cell.navAbsolute',\n\t\tcanRun: gridNonEmpty,\n\t\trun: (ctx, payload) => {\n\t\t\tconst p = payload as NavAbsolutePayload;\n\t\t\tconst base = ctx.selection?.current?.cell ?? [0, 0];\n\t\t\tconst target = computeKeyNavTarget(\n\t\t\t\tp.key,\n\t\t\t\t{ ctrlOrMeta: p.ctrlOrMeta, shift: p.shift },\n\t\t\t\tbase,\n\t\t\t\tctx.colCount,\n\t\t\t\tctx.rowCount,\n\t\t\t\tp.pageRows,\n\t\t\t);\n\t\t\tif (!target) return;\n\t\t\t// Absolute moves are plain activates — reset the range anchor to the landing cell.\n\t\t\tctx.setAnchor([target[0], target[1]]);\n\t\t\tctx.setActiveCell(target[0], target[1]);\n\t\t\tctx.scrollToCell(target[0], target[1]);\n\t\t},\n\t},\n\n\t// ---- OPEN EDITOR AT ACTIVE (Enter / F2) ----\n\t{\n\t\tid: 'editor.openActive',\n\t\t// Mirrors the original `if (openEditorAtActiveCell()) e.preventDefault()`: only\n\t\t// prevent default when an overlay actually opened. canRun probes the same path.\n\t\tcanRun: (ctx) => ctx.openEditorAtActive(),\n\t\trun: () => {\n\t\t\t// canRun already opened the editor (it returns true only when it opened) — running\n\t\t\t// again would double-open, so the effect lives in canRun and run is a no-op. This is\n\t\t\t// the verbatim \"open then conditionally preventDefault\" semantics, expressed through\n\t\t\t// the gate so a non-opening Enter falls through WITHOUT preventDefault.\n\t\t},\n\t},\n\n\t// ---- TYPE-TO-EDIT SENTINEL (printable key: openEditorAtActive(char)) ----\n\t// The LAST-RESOLVED sentinel for printable keys — it goes THROUGH dispatch (so it is\n\t// interceptable), NOT an out-of-band fallback. canRun opens with the seed char and gates\n\t// preventDefault on a real open (readonly cells return false → key falls through).\n\t{\n\t\tid: 'editor.typeToEdit',\n\t\tcanRun: (ctx, payload) => ctx.openEditorAtActive((payload as TypeToEditPayload).char),\n\t\trun: () => {\n\t\t\t// effect performed in canRun (same conditional-preventDefault rationale as openActive).\n\t\t},\n\t},\n\n\t// ---- POINTER ACTIVATE (click: setAnchor + setActiveCell) ----\n\t{\n\t\tid: 'cell.activate',\n\t\trun: (ctx, payload) => {\n\t\t\tconst { col, row } = payload as CellPointerPayload;\n\t\t\tctx.setAnchor([col, row]);\n\t\t\tctx.setActiveCell(col, row);\n\t\t},\n\t},\n\n\t// ---- POINTER SHIFT-EXTEND (shift-click: extendToCell) ----\n\t{\n\t\tid: 'cell.extendToClicked',\n\t\trun: (ctx, payload) => {\n\t\t\tconst { col, row } = payload as CellPointerPayload;\n\t\t\tctx.extendToCell(col, row);\n\t\t},\n\t},\n\n\t// ---- DBLCLICK OPEN (openEditorAt) ----\n\t{\n\t\tid: 'editor.open',\n\t\trun: (ctx, payload) => {\n\t\t\tconst { rowIndex, colKey, anchorRect, initialText } = payload as EditorOpenPayload;\n\t\t\tctx.openEditorAt(rowIndex, colKey, anchorRect, initialText);\n\t\t},\n\t},\n\n\t// ---- STRUCTURAL POINTER (routed through dispatch for invariant completeness) ----\n\t{\n\t\tid: 'header.sortToggle',\n\t\trun: (ctx, payload) => {\n\t\t\tctx.sortToggle((payload as SortTogglePayload).colKey);\n\t\t},\n\t},\n\t{\n\t\tid: 'rowmarker.toggleRow',\n\t\trun: (ctx, payload) => {\n\t\t\tconst { rowIndex, shift } = payload as ToggleRowPayload;\n\t\t\t// Delegated to the existing rowMarker.onToggleRow (anchor + selectRange/toggleRow). Phase 1\n\t\t\t// keeps that handler the source of truth; the command threads it so the id exists in the map.\n\t\t\tctx.toggleRow(rowIndex, shift);\n\t\t},\n\t},\n\t{\n\t\tid: 'rowmarker.toggleAll',\n\t\trun: (ctx) => {\n\t\t\tctx.toggleAll();\n\t\t},\n\t},\n];\n\n/**\n * Plain-arrow MOVE command factory (verbatim: arrow branch, non-shift path). Computes the\n * clamped target off the LATEST selection, RESETS the anchor, moves, then scrolls.\n */\nfunction makeMoveCommand(id: string, dCol: number, dRow: number): GridCommand {\n\treturn {\n\t\tid,\n\t\tcanRun: gridNonEmpty,\n\t\trun: (ctx) => {\n\t\t\tconst base = ctx.selection?.current?.cell ?? [0, 0];\n\t\t\tconst nextCol = Math.max(0, Math.min(base[0] + dCol, ctx.colCount - 1));\n\t\t\tconst nextRow = Math.max(0, Math.min(base[1] + dRow, ctx.rowCount - 1));\n\t\t\tctx.setAnchor([nextCol, nextRow]);\n\t\t\tctx.moveActiveCell(dCol, dRow, ctx.colCount, ctx.rowCount);\n\t\t\tctx.scrollToCell(nextCol, nextRow);\n\t\t},\n\t};\n}\n\n/**\n * Shift-arrow EXTEND command factory (verbatim: arrow branch, shift path). Extends the\n * range from the FIXED anchor to the clamped target, then scrolls the target into view.\n */\nfunction makeExtendCommand(id: string, dCol: number, dRow: number): GridCommand {\n\treturn {\n\t\tid,\n\t\tcanRun: gridNonEmpty,\n\t\trun: (ctx) => {\n\t\t\tconst base = ctx.selection?.current?.cell ?? [0, 0];\n\t\t\tconst nextCol = Math.max(0, Math.min(base[0] + dCol, ctx.colCount - 1));\n\t\t\tconst nextRow = Math.max(0, Math.min(base[1] + dRow, ctx.rowCount - 1));\n\t\t\tctx.extendToCell(nextCol, nextRow);\n\t\t\tctx.scrollToCell(nextCol, nextRow);\n\t\t},\n\t};\n}\n\n/**\n * Build a command registry: DEFAULT_COMMANDS, with optional consumer overrides folded in\n * LAST so a matching id REPLACES the default and a new id ADDS a command (Phase 2 seam).\n */\nexport function createGridCommandRegistry(overrides?: GridCommand[]): GridCommandRegistry {\n\tconst registry: GridCommandRegistry = new Map();\n\tfor (const cmd of DEFAULT_COMMANDS) registry.set(cmd.id, cmd);\n\tif (overrides) {\n\t\tfor (const cmd of overrides) registry.set(cmd.id, cmd);\n\t}\n\treturn registry;\n}\n","/**\n * The ONE interceptable dispatch pipeline (P4 Phase 1).\n *\n * `dispatch(command, native?, payload?)`:\n * 1. resolve `command` in the registry — a missing / null id is a silent NO-OP\n * (so an unbound key falls through to the browser: NO `preventDefault`).\n * 2. run the interceptor chain (reduceRight → first-listed is OUTERMOST). Each\n * interceptor may VETO (not call `next` → command never runs, nothing prevented),\n * TRANSFORM (mutate `ev.payload` before `next`), or OBSERVE (read `next()`'s result).\n * 3. AFTER the chain, check `command.canRun(ctx, payload)` — false NO-OPs (and does\n * NOT preventDefault).\n * 4. `native?.preventDefault()` happens ONLY here in the core (so a vetoed / unresolved /\n * can't-run command leaves the native event untouched and the key reaches the browser).\n * 5. `command.run(ctx, payload)` — synchronous return (it MAY kick a Promise; we never\n * await — NO async-dispatch / re-entrancy machinery).\n *\n * Phase 1 ships ZERO interceptors (the consumer seam is Phase 2); the chain is wired so\n * adding one later is purely additive and behavior stays byte-for-byte identical.\n */\n\nimport type { GridCommandContext } from './context';\nimport type { GridCommandRegistry } from './types';\n\n/** The mutable event threaded through the interceptor chain. */\nexport interface DispatchEvent {\n\t/** The resolved command id. */\n\tcommand: string;\n\t/** The originating native event, if any (the funnel's `preventDefault` target). */\n\tnative?: Event;\n\t/** The command payload — interceptors MAY mutate this in place to TRANSFORM. */\n\tpayload?: unknown;\n}\n\n/** Result of a dispatch attempt — observable by interceptors via `next()`. */\nexport interface CommandResult {\n\t/** The dispatched command id (or null when nothing resolved). */\n\tcommand: string | null;\n\t/** Whether `command.run` was invoked (false = unresolved / vetoed / canRun=false). */\n\tran: boolean;\n\t/** Whether `native.preventDefault()` was called. */\n\tprevented: boolean;\n}\n\n/**\n * An interceptor wraps the rest of the chain (`next`). Call `next()` to continue\n * (returning its CommandResult); SKIP it to VETO; mutate `ev.payload` before `next()`\n * to TRANSFORM. The OUTERMOST (first-listed) interceptor sees the final result.\n */\nexport type Interceptor = (ev: DispatchEvent, next: () => CommandResult) => CommandResult;\n\n/** The dispatch fn signature wired into the grid root. */\nexport type Dispatch = (command: string | null, native?: Event, payload?: unknown) => CommandResult;\n\nconst UNRESOLVED: CommandResult = { command: null, ran: false, prevented: false };\n\n/**\n * Wrap an `onCommand(ev, result)` callback as an INNERMOST tail OBSERVER interceptor:\n * it always calls `next()` (never vetoes / transforms), then reports the final\n * {@link CommandResult} to the consumer. Listed LAST in the interceptor array so it\n * runs after all consumer interceptors (closest to the core) and observes the actual\n * outcome — purely observational, never altering behavior.\n */\nexport function tailObserver(onCommand: (ev: DispatchEvent, result: CommandResult) => void): Interceptor {\n\treturn (ev, next) => {\n\t\tconst result = next();\n\t\tonCommand(ev, result);\n\t\treturn result;\n\t};\n}\n\n/**\n * Build the dispatch fn over a registry + live context + (optional) interceptor list.\n * `getContext` is read fresh per dispatch so the latched context is always current.\n */\nexport function makeDispatch(\n\tregistry: GridCommandRegistry,\n\tgetContext: () => GridCommandContext,\n\tinterceptors: Interceptor[] = [],\n): Dispatch {\n\treturn function dispatch(command, native, payload): CommandResult {\n\t\tif (command == null) return UNRESOLVED;\n\t\tconst cmd = registry.get(command);\n\t\tif (!cmd) return { command, ran: false, prevented: false };\n\n\t\tconst ev: DispatchEvent = { command, native, payload };\n\n\t\t// The CORE runs last (innermost): canRun gate → preventDefault → run.\n\t\tconst core = (): CommandResult => {\n\t\t\tconst ctx = getContext();\n\t\t\tif (cmd.canRun && !cmd.canRun(ctx, ev.payload)) {\n\t\t\t\treturn { command, ran: false, prevented: false };\n\t\t\t}\n\t\t\tlet prevented = false;\n\t\t\tif (ev.native) {\n\t\t\t\tev.native.preventDefault();\n\t\t\t\tprevented = true;\n\t\t\t}\n\t\t\tvoid cmd.run(ctx, ev.payload);\n\t\t\treturn { command, ran: true, prevented };\n\t\t};\n\n\t\t// reduceRight so the FIRST-LISTED interceptor is the OUTERMOST wrapper.\n\t\tconst chain = interceptors.reduceRight<() => CommandResult>(\n\t\t\t(next, interceptor) => () => interceptor(ev, next),\n\t\t\tcore,\n\t\t);\n\t\treturn chain();\n\t};\n}\n","/**\n * Keybinding primitives — COPIED from packages/command-palette/src/keybinding.ts\n * (kbd / matchKeyBinding / isMac / isEditableTarget) so @constructive-io/sheets stays\n * distributable WITHOUT a dependency on command-palette. Keep the two in sync by hand;\n * the logic is intentionally identical (strict modifier matching, Mac mod=meta).\n */\n\n/** Modifier key abstraction. 'mod' = Cmd on Mac, Ctrl on Windows/Linux. */\nexport type KeyModifier = 'mod' | 'shift' | 'alt';\n\n/** Structured key binding — matchable against KeyboardEvents. */\nexport interface KeyBinding {\n\tmodifiers?: KeyModifier[];\n\t/** Lowercase key name: 'h', 'k', 'enter', 'backspace', ',', '/', etc. */\n\tkey: string;\n}\n\n/** Ergonomic KeyBinding factory. */\nexport function kbd(key: string, ...modifiers: KeyModifier[]): KeyBinding {\n\treturn modifiers.length > 0 ? { key, modifiers } : { key };\n}\n\n/** Platform detection with SSR fallback (assumes non-Mac). */\nexport function isMac(): boolean {\n\tif (typeof navigator === 'undefined') return false;\n\treturn /mac|ipod|iphone|ipad/i.test(navigator.platform ?? '');\n}\n\n/** Check if event target is an editable element (input, textarea, select, contenteditable). */\nexport function isEditableTarget(target: EventTarget | null): boolean {\n\tif (!target || !(target instanceof HTMLElement)) return false;\n\tconst tag = target.tagName;\n\tif (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;\n\treturn target.contentEditable === 'true';\n}\n\n/** Match a KeyboardEvent against a KeyBinding with strict modifier check. */\nexport function matchKeyBinding(event: KeyboardEvent, binding: KeyBinding): boolean {\n\t// Compare key (case-insensitive)\n\tif (event.key.toLowerCase() !== binding.key.toLowerCase()) return false;\n\n\tconst mods = binding.modifiers ?? [];\n\tconst wantMod = mods.includes('mod');\n\tconst wantShift = mods.includes('shift');\n\tconst wantAlt = mods.includes('alt');\n\n\t// On Mac, 'mod' maps to metaKey; elsewhere, ctrlKey\n\tconst modPressed = isMac() ? event.metaKey : event.ctrlKey;\n\n\t// Strict: every required modifier must be pressed, no extras\n\tif (wantMod !== modPressed) return false;\n\tif (wantShift !== event.shiftKey) return false;\n\tif (wantAlt !== event.altKey) return false;\n\n\t// Prevent false positives: if mod maps to meta on Mac, ctrl shouldn't be pressed (and vice versa)\n\tif (isMac()) {\n\t\tif (!wantMod && event.ctrlKey) return false;\n\t} else {\n\t\tif (!wantMod && event.metaKey) return false;\n\t}\n\n\treturn true;\n}\n","/**\n * DEFAULT_KEYMAP + resolveKeyCommand (P4 Phase 1).\n *\n * A keymap is an ordered Binding[]; `resolveKeyCommand` returns the FIRST matching\n * binding's command id (first-match-wins) or `null` when nothing matches — including\n * for an unbound PRINTABLE key, so the dispatch funnel can fall to the `editor.typeToEdit`\n * sentinel (the printable-key path is NOT in the keymap; the funnel routes it explicitly).\n *\n * Triggers come in three kinds — `key` (matched here via the copied matchKeyBinding),\n * `pointer` (gesture, wired in Stage B / Phase 2), and `native` (a raw DOM event name).\n * Pointer + native triggers are declared in the table for invariant completeness even\n * though only key triggers resolve through `resolveKeyCommand`.\n *\n * `Mod` is ctrl on win/linux, cmd on mac — encoded as the copied `'mod'` KeyModifier, so\n * matchKeyBinding's platform branch (isMac) picks the right physical key.\n */\n\nimport { kbd, matchKeyBinding, type KeyBinding } from './keybinding';\n\n/** A pointer gesture name (resolved by the pointer handlers, not the key funnel). */\nexport type PointerGesture = 'click' | 'shiftClick' | 'dblclick' | 'headerClick' | 'rowToggle' | 'rowToggleAll';\n\n/** What fires a command. */\nexport type Trigger =\n\t| { kind: 'key'; binding: KeyBinding }\n\t| { kind: 'pointer'; gesture: PointerGesture }\n\t| { kind: 'native'; event: string };\n\n/** A trigger -> command id mapping. */\nexport interface Binding {\n\ttrigger: Trigger;\n\tcommand: string;\n}\n\n/** key-trigger shorthand. */\nfunction key(binding: KeyBinding, command: string): Binding {\n\treturn { trigger: { kind: 'key', binding }, command };\n}\n\n/** pointer-trigger shorthand. */\nfunction pointer(gesture: PointerGesture, command: string): Binding {\n\treturn { trigger: { kind: 'pointer', gesture }, command };\n}\n\n/**\n * The default key + pointer + native bindings. Order matters for the key kind\n * (first-match-wins). matchKeyBinding is STRICT on modifiers, so the undo (Mod+Z) and\n * redo (Mod+Shift+Z) chords never alias even though they share the 'z' key.\n */\nexport const DEFAULT_KEYMAP: Binding[] = [\n\t// undo / redo\n\tkey(kbd('z', 'mod'), 'edit.undo'),\n\tkey(kbd('z', 'mod', 'shift'), 'edit.redo'),\n\tkey(kbd('y', 'mod'), 'edit.redo'),\n\n\t// select all\n\tkey(kbd('a', 'mod'), 'selection.all'),\n\n\t// clear cells (Delete / Backspace → null over the active range). The funnel bails\n\t// while an overlay editor is open, so these still edit text inside an editor.\n\tkey(kbd('Delete'), 'cell.clear'),\n\tkey(kbd('Backspace'), 'cell.clear'),\n\n\t// fill (Mod = Cmd/mac, Ctrl/win)\n\tkey(kbd('d', 'mod'), 'fill.down'),\n\tkey(kbd('r', 'mod'), 'fill.right'),\n\n\t// arrow move (plain)\n\tkey(kbd('ArrowUp'), 'cell.moveUp'),\n\tkey(kbd('ArrowDown'), 'cell.moveDown'),\n\tkey(kbd('ArrowLeft'), 'cell.moveLeft'),\n\tkey(kbd('ArrowRight'), 'cell.moveRight'),\n\n\t// arrow extend (shift)\n\tkey(kbd('ArrowUp', 'shift'), 'cell.extendUp'),\n\tkey(kbd('ArrowDown', 'shift'), 'cell.extendDown'),\n\tkey(kbd('ArrowLeft', 'shift'), 'cell.extendLeft'),\n\tkey(kbd('ArrowRight', 'shift'), 'cell.extendRight'),\n\n\t// absolute nav — base + ctrl/meta + shift variants all resolve to one command (the\n\t// command body branches on the payload via computeKeyNavTarget, matching the original).\n\tkey(kbd('Tab'), 'cell.navAbsolute'),\n\tkey(kbd('Tab', 'shift'), 'cell.navAbsolute'),\n\tkey(kbd('Home'), 'cell.navAbsolute'),\n\tkey(kbd('Home', 'mod'), 'cell.navAbsolute'),\n\tkey(kbd('End'), 'cell.navAbsolute'),\n\tkey(kbd('End', 'mod'), 'cell.navAbsolute'),\n\tkey(kbd('PageUp'), 'cell.navAbsolute'),\n\tkey(kbd('PageDown'), 'cell.navAbsolute'),\n\n\t// open editor at active cell\n\tkey(kbd('Enter'), 'editor.openActive'),\n\tkey(kbd('F2'), 'editor.openActive'),\n\n\t// pointer gestures (wired Stage B / Phase 2)\n\tpointer('click', 'cell.activate'),\n\tpointer('shiftClick', 'cell.extendToClicked'),\n\tpointer('dblclick', 'editor.open'),\n\tpointer('headerClick', 'header.sortToggle'),\n\tpointer('rowToggle', 'rowmarker.toggleRow'),\n\tpointer('rowToggleAll', 'rowmarker.toggleAll'),\n];\n\n/**\n * Resolve a KeyboardEvent to a command id via the keymap (first key-trigger match wins).\n * Returns `null` when no key binding matches — including unbound printable keys — so the\n * caller can fall to the `editor.typeToEdit` sentinel. Pointer / native triggers are\n * ignored here (they are not key events).\n */\nexport function resolveKeyCommand(event: KeyboardEvent, keymap: Binding[] = DEFAULT_KEYMAP): string | null {\n\tfor (const binding of keymap) {\n\t\tif (binding.trigger.kind !== 'key') continue;\n\t\tif (matchKeyBinding(event, binding.trigger.binding)) return binding.command;\n\t}\n\treturn null;\n}\n","/**\n * Sheets theme tokens.\n *\n * A small, semantic token set a host can override per light/dark mode, plus a\n * reader that lifts tokens off CSS custom properties. The native DOM grid styles\n * from CSS variables directly, so these tokens are the glide-free surface that\n * survived the canvas cutover (the old glide `Theme` mapping was removed).\n */\n\n/**\n * Semantic, composable theme tokens. A small surface a host can override per mode.\n */\nexport interface SheetsThemeTokens {\n\t/** Primary accent (selection, links, focus). */\n\taccent: string;\n\t/** Foreground rendered on top of `accent` (e.g. selected header text). */\n\taccentForeground: string;\n\t/** Base canvas / cell background. */\n\tbackground: string;\n\t/** Header / muted cell surface. */\n\tsurface: string;\n\t/** Hover / focused surface (one step from `surface`). */\n\tsurfaceMuted: string;\n\t/** Grid + header border color. */\n\tborder: string;\n\t/** Primary text color. */\n\ttext: string;\n\t/** Secondary (muted) text color. */\n\ttextMuted: string;\n\t/** Optional font stack; falls back to the default Inter-based stack. */\n\tfontFamily?: string;\n}\n\n/**\n * Host theme input: a partial token override keyed by mode (deep-merged over the\n * grid's defaults).\n */\nexport type SheetsThemeInput = Partial<Record<'light' | 'dark', Partial<SheetsThemeTokens>>>;\n\n/**\n * Read theme tokens off CSS custom properties on `el` (defaults to\n * `document.documentElement`). Only properties that resolve to a non-empty value\n * are returned, so the result is safe to deep-merge over a defaults object.\n */\nexport function tokensFromCssVars(\n\tel: Element | null = typeof document !== 'undefined' ? document.documentElement : null,\n): Partial<SheetsThemeTokens> {\n\tif (!el || typeof window === 'undefined') return {};\n\tconst cs = window.getComputedStyle(el);\n\tconst read = (name: string): string | undefined => {\n\t\tconst v = cs.getPropertyValue(name).trim();\n\t\treturn v.length > 0 ? v : undefined;\n\t};\n\n\tconst out: Partial<SheetsThemeTokens> = {};\n\tconst accent = read('--sheets-accent') ?? read('--primary');\n\tconst background = read('--background');\n\tconst border = read('--border');\n\tconst text = read('--foreground');\n\n\tif (accent !== undefined) out.accent = accent;\n\tif (background !== undefined) out.background = background;\n\tif (border !== undefined) out.border = border;\n\tif (text !== undefined) out.text = text;\n\treturn out;\n}\n","import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { RiAddLine, RiDatabaseLine, RiSearchLine } from '@remixicon/react';\nimport { ChevronRight } from 'lucide-react';\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { cn } from '../utils/cn';\nimport { Button } from '@constructive-io/ui/button';\nimport { Collapsible, CollapsibleTrigger } from '@constructive-io/ui/collapsible';\nimport { Input } from '@constructive-io/ui/input';\nimport { ProgressiveBlur } from '@constructive-io/ui/progressive-blur';\nimport { ScrollArea } from '@constructive-io/ui/scroll-area';\nimport { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@constructive-io/ui/tooltip';\n\nconst BLUR_HEIGHT_PERCENT = 0.28;\nconst BLUR_HEIGHT_MIN_PX = 64;\nconst BLUR_HEIGHT_MAX_PX = 140;\n\nexport type TableWithCategory = {\n\tname: string;\n\tcategory?: string;\n};\n\ninterface TableItemProps {\n\ttable: { value: string; label: string };\n\tactiveTable: string;\n\tonTableSelect: (tableName: string) => void;\n\t/** Ref to attach to this item (used for scroll-into-view on active item) */\n\titemRef?: React.RefObject<HTMLButtonElement | null>;\n}\n\nconst TableItem = memo(function TableItem({ table, activeTable, onTableSelect, itemRef }: TableItemProps) {\n\tconst isActive = activeTable === table.value;\n\n\treturn (\n\t\t<Button\n\t\t\tref={isActive ? itemRef : undefined}\n\t\t\taria-pressed={isActive}\n\t\t\tdata-testid='table-item'\n\t\t\tstatic\n\t\t\tsize='sm'\n\t\t\ttype='button'\n\t\t\tvariant='ghost'\n\t\t\tclassName={cn(\n\t\t\t\t'group relative my-1 flex h-8 w-full shrink items-center justify-between rounded-lg px-2 text-left text-xs font-normal transition-colors duration-(--duration-moderate)',\n\t\t\t\tisActive\n\t\t\t\t\t? 'bg-primary/10 text-foreground ring-primary/30 dark:bg-primary/15 dark:ring-primary/40 ring-1'\n\t\t\t\t\t: 'text-muted-foreground hover:text-foreground',\n\t\t\t)}\n\t\t\tonClick={() => onTableSelect(table.value)}\n\t\t>\n\t\t\t<span className='flex min-w-0 flex-1 items-center'>\n\t\t\t\t<Tooltip>\n\t\t\t\t\t<TooltipTrigger asChild>\n\t\t\t\t\t\t<span className='truncate text-xs'>{table.label}</span>\n\t\t\t\t\t</TooltipTrigger>\n\t\t\t\t\t<TooltipContent side='right' align='start'>\n\t\t\t\t\t\t<span className='text-xs font-medium'>{table.label}</span>\n\t\t\t\t\t</TooltipContent>\n\t\t\t\t</Tooltip>\n\t\t\t</span>\n\t\t</Button>\n\t);\n});\n\nexport interface TableSelectorProps {\n\ttables: string[] | TableWithCategory[];\n\tactiveTable: string;\n\tonTableChange: (table: string) => void;\n\tisLoading?: boolean;\n\t/** When true, scroll the active table into view and expand its section */\n\tshouldScrollToActive?: boolean;\n\t/** Optional callback when user clicks the \"New table\" button */\n\tonNewTable?: () => void;\n}\n\nexport const SheetsTableSelector = memo(function SheetsTableSelector({\n\ttables,\n\tactiveTable,\n\tonTableChange,\n\tisLoading = false,\n\tshouldScrollToActive = false,\n\tonNewTable,\n}: TableSelectorProps) {\n\tconst [searchQuery, setSearchQuery] = useState('');\n\tconst containerRef = useRef<HTMLDivElement>(null);\n\tconst [_containerHeight, setContainerHeight] = useState(0);\n\n\t// Local expand/collapse state (not persisted -- standalone component)\n\tconst [isExpanded, setIsExpanded] = useState(true);\n\n\t// Transform tables to internal format\n\tconst tableData = useMemo(() => {\n\t\treturn tables.map((table) => {\n\t\t\tconst isObject = typeof table === 'object';\n\t\t\tconst name = isObject ? table.name : table;\n\t\t\treturn {\n\t\t\t\tvalue: name,\n\t\t\t\tlabel: name,\n\t\t\t};\n\t\t});\n\t}, [tables]);\n\n\t// Apply search filter\n\tconst filteredTables = useMemo(() => {\n\t\tif (!searchQuery) return tableData;\n\t\treturn tableData.filter((table) => table.label.toLowerCase().includes(searchQuery.toLowerCase()));\n\t}, [tableData, searchQuery]);\n\n\t// Measure container height on mount and resize\n\tuseEffect(() => {\n\t\tconst container = containerRef.current;\n\t\tif (!container) return;\n\n\t\tconst updateHeight = () => {\n\t\t\tsetContainerHeight(container.clientHeight);\n\t\t};\n\n\t\tupdateHeight();\n\n\t\tconst resizeObserver = new ResizeObserver(updateHeight);\n\t\tresizeObserver.observe(container);\n\n\t\treturn () => resizeObserver.disconnect();\n\t}, []);\n\n\tconst handleTableSelect = useCallback(\n\t\t(tableName: string) => {\n\t\t\tonTableChange(tableName);\n\t\t},\n\t\t[onTableChange],\n\t);\n\n\tconst handleNewTable = useCallback(() => {\n\t\tif (onNewTable) {\n\t\t\tonNewTable();\n\t\t}\n\t}, [onNewTable]);\n\n\tif (isLoading) {\n\t\treturn (\n\t\t\t<div data-part-id='sheets-table-selector-loading' className='bg-background flex h-full flex-col'>\n\t\t\t\t{/* Header skeleton */}\n\t\t\t\t<div className='border-border/60 flex-shrink-0 border-b p-6'>\n\t\t\t\t\t<div className='bg-muted mb-6 h-8 w-32 animate-pulse rounded'></div>\n\n\t\t\t\t\t{/* Schema selector skeleton */}\n\t\t\t\t\t<div className='bg-muted mb-4 h-10 w-full animate-pulse rounded-md'></div>\n\n\t\t\t\t\t{/* New table button skeleton */}\n\t\t\t\t\t<div className='bg-muted mb-4 h-10 w-full animate-pulse rounded-md'></div>\n\n\t\t\t\t\t{/* Search input skeleton */}\n\t\t\t\t\t<div className='bg-muted h-10 w-full animate-pulse rounded-md'></div>\n\t\t\t\t</div>\n\n\t\t\t\t{/* Table list skeleton */}\n\t\t\t\t<div className='flex-1 space-y-2 p-6'>\n\t\t\t\t\t{[1, 2, 3, 4, 5].map((i) => (\n\t\t\t\t\t\t<div key={i} className='flex items-center justify-between rounded-lg border p-3'>\n\t\t\t\t\t\t\t<div className='flex items-center gap-3'>\n\t\t\t\t\t\t\t\t<div className='bg-muted h-4 w-4 animate-pulse rounded'></div>\n\t\t\t\t\t\t\t\t<div className='bg-muted h-4 w-24 animate-pulse rounded'></div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div className='bg-muted h-6 w-20 animate-pulse rounded-full'></div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t))}\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t);\n\t}\n\n\treturn (\n\t\t<TooltipProvider delayDuration={150}>\n\t\t\t<div\n\t\t\t\tdata-part-id='sheets-table-selector'\n\t\t\t\tclassName='bg-background flex h-full max-h-[calc(100vh-4rem)] flex-col'\n\t\t\t>\n\t\t\t\t{/* Header */}\n\t\t\t\t<div className='flex-shrink-0 py-4'>\n\t\t\t\t\t<div className='flex flex-col gap-2 pr-2 pb-2'>\n\t\t\t\t\t\t{/* New table button */}\n\t\t\t\t\t\t<Button onClick={handleNewTable} className='h-8 w-full justify-start gap-2' variant='outline'>\n\t\t\t\t\t\t\t<RiAddLine size={16} />\n\t\t\t\t\t\t\tNew table\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t{/* Search input */}\n\t\t\t\t\t<div className='relative pr-2'>\n\t\t\t\t\t\t<RiSearchLine\n\t\t\t\t\t\t\tsize={16}\n\t\t\t\t\t\t\tclassName='text-muted-foreground absolute top-1/2 left-3 -translate-y-1/2 transform'\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t<Input\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\tplaceholder='Search tables...'\n\t\t\t\t\t\t\tvalue={searchQuery}\n\t\t\t\t\t\t\tonChange={(e) => setSearchQuery(e.target.value)}\n\t\t\t\t\t\t\tclassName='pl-10'\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\n\t\t\t\t{/* Table list */}\n\t\t\t\t<div\n\t\t\t\t\tref={containerRef}\n\t\t\t\t\tdata-part-id='table-selector-table-list'\n\t\t\t\t\tclassName='mt-4 flex min-h-0 flex-1 flex-col gap-2 overflow-hidden pr-2'\n\t\t\t\t>\n\t\t\t\t\t{filteredTables.length === 0 ? (\n\t\t\t\t\t\t<div className='flex flex-col items-center justify-center py-12 text-center'>\n\t\t\t\t\t\t\t<div className='bg-muted mb-4 flex h-12 w-12 items-center justify-center rounded-full'>\n\t\t\t\t\t\t\t\t<RiSearchLine size={20} className='text-muted-foreground' />\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<p className='text-muted-foreground mb-1 text-sm font-medium'>No tables found</p>\n\t\t\t\t\t\t\t<p className='text-muted-foreground/80 text-xs'>\n\t\t\t\t\t\t\t\t{searchQuery ? 'Try adjusting your search terms' : 'No tables available in this schema'}\n\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t) : (\n\t\t\t\t\t\t<SheetsTableListByCategory\n\t\t\t\t\t\t\ttitle='Tables'\n\t\t\t\t\t\t\ttables={filteredTables}\n\t\t\t\t\t\t\tactiveTable={activeTable}\n\t\t\t\t\t\t\tisExpanded={isExpanded}\n\t\t\t\t\t\t\tonToggleExpand={() => setIsExpanded((prev) => !prev)}\n\t\t\t\t\t\t\tonTableSelect={handleTableSelect}\n\t\t\t\t\t\t\temptyMessage='No tables yet'\n\t\t\t\t\t\t\thasSearchTerm={searchQuery.length > 0}\n\t\t\t\t\t\t\tshouldScrollToActive={shouldScrollToActive}\n\t\t\t\t\t\t/>\n\t\t\t\t\t)}\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</TooltipProvider>\n\t);\n});\n\ninterface TableListByCategoryProps {\n\ttitle: string;\n\ttables: { value: string; label: string }[];\n\tactiveTable: string;\n\tisExpanded: boolean;\n\tonToggleExpand: () => void;\n\tonTableSelect: (tableName: string) => void;\n\temptyMessage?: string;\n\thasSearchTerm?: boolean;\n\tmaxContentHeight?: number;\n\t/** When true, scroll the active table into view */\n\tshouldScrollToActive?: boolean;\n}\n\nfunction SheetsTableListByCategory({\n\ttitle,\n\ttables,\n\tactiveTable,\n\tisExpanded,\n\tonToggleExpand,\n\tonTableSelect,\n\temptyMessage = 'No tables',\n\thasSearchTerm = false,\n\tmaxContentHeight,\n\tshouldScrollToActive = false,\n}: TableListByCategoryProps) {\n\tconst scrollRef = useRef<HTMLDivElement>(null);\n\tconst activeItemRef = useRef<HTMLButtonElement>(null);\n\tconst [showBottomBlur, setShowBottomBlur] = useState(false);\n\tconst [scrollAreaHeight, setScrollAreaHeight] = useState(0);\n\n\tconst hasSelectedItem = activeTable ? tables.some((t) => t.value === activeTable) : false;\n\n\t// Scroll active item into view when requested\n\tuseEffect(() => {\n\t\tif (!shouldScrollToActive || !isExpanded || !activeItemRef.current) return;\n\n\t\t// Wait for animation to complete before scrolling\n\t\tconst timer = setTimeout(() => {\n\t\t\tactiveItemRef.current?.scrollIntoView({\n\t\t\t\tbehavior: 'smooth',\n\t\t\t\tblock: 'center',\n\t\t\t});\n\t\t}, 350); // Match the collapsible animation duration\n\n\t\treturn () => clearTimeout(timer);\n\t}, [shouldScrollToActive, isExpanded, activeTable]);\n\n\tconst handleScroll = useCallback((event: React.UIEvent<HTMLDivElement>) => {\n\t\tconst el = event.currentTarget;\n\t\tconst atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 1;\n\t\tsetShowBottomBlur(!(atBottom || el.scrollHeight <= el.clientHeight));\n\t}, []);\n\n\tuseEffect(() => {\n\t\tconst el = scrollRef.current;\n\t\tif (!el) return;\n\t\tconst atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 1;\n\t\tsetShowBottomBlur(!(atBottom || el.scrollHeight <= el.clientHeight));\n\t}, [tables.length, isExpanded, maxContentHeight]);\n\n\tuseEffect(() => {\n\t\tconst el = scrollRef.current;\n\t\tif (!el) return;\n\n\t\tconst update = () => setScrollAreaHeight(el.clientHeight);\n\t\tupdate();\n\n\t\tconst ro = new ResizeObserver(update);\n\t\tro.observe(el);\n\t\treturn () => ro.disconnect();\n\t}, [isExpanded, maxContentHeight]);\n\n\tconst blurHeight = useMemo(() => {\n\t\tif (!scrollAreaHeight) return '28%';\n\t\tconst percentPx = scrollAreaHeight * BLUR_HEIGHT_PERCENT;\n\t\tconst clamped = Math.min(scrollAreaHeight, Math.min(BLUR_HEIGHT_MAX_PX, Math.max(BLUR_HEIGHT_MIN_PX, percentPx)));\n\t\treturn `${Math.round(clamped)}px`;\n\t}, [scrollAreaHeight]);\n\n\t// Calculate max-height style\n\tconst scrollAreaStyle = maxContentHeight !== undefined ? { maxHeight: `${maxContentHeight}px` } : undefined;\n\n\treturn (\n\t\t<Collapsible open={isExpanded} onOpenChange={onToggleExpand} className='flex min-h-0 shrink-0 flex-col'>\n\t\t\t<CollapsibleTrigger\n\t\t\t\tclassName={cn(\n\t\t\t\t\t'group flex w-full items-center gap-2 rounded-lg py-1.5 pr-2 pl-1 transition-colors duration-(--duration-moderate)',\n\t\t\t\t\t'bg-muted hover:bg-muted/50',\n\t\t\t\t\tisExpanded && 'bg-muted/50',\n\t\t\t\t)}\n\t\t\t>\n\t\t\t\t<motion.div\n\t\t\t\t\tanimate={{ rotate: isExpanded ? 90 : 0 }}\n\t\t\t\t\ttransition={{ type: 'spring', stiffness: 400, damping: 25 }}\n\t\t\t\t\tclassName='flex shrink-0 items-center justify-center'\n\t\t\t\t>\n\t\t\t\t\t<ChevronRight className='text-muted-foreground/60 h-3.5 w-3.5' />\n\t\t\t\t</motion.div>\n\t\t\t\t<span className='text-muted-foreground text-xs font-medium'>{title}</span>\n\t\t\t\t<span className='ml-auto flex items-center gap-1.5'>\n\t\t\t\t\t{!isExpanded && hasSelectedItem && (\n\t\t\t\t\t\t<span className='bg-primary/50 h-1.5 w-1.5 rounded-full' aria-label='Contains selected item' />\n\t\t\t\t\t)}\n\t\t\t\t\t<span className='text-muted-foreground/70 text-[10px] tabular-nums'>{tables.length}</span>\n\t\t\t\t</span>\n\t\t\t</CollapsibleTrigger>\n\n\t\t\t<AnimatePresence initial={false}>\n\t\t\t\t{isExpanded && (\n\t\t\t\t\t<motion.div\n\t\t\t\t\t\tdata-testid={`collapsible-content-${title}`}\n\t\t\t\t\t\tinitial={{ height: 0, opacity: 0 }}\n\t\t\t\t\t\tanimate={{\n\t\t\t\t\t\t\theight: 'auto',\n\t\t\t\t\t\t\topacity: 1,\n\t\t\t\t\t\t\ttransition: {\n\t\t\t\t\t\t\t\theight: { type: 'spring', stiffness: 500, damping: 40, mass: 0.8 },\n\t\t\t\t\t\t\t\topacity: { duration: 0.2, ease: 'easeOut' },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}}\n\t\t\t\t\t\texit={{\n\t\t\t\t\t\t\theight: 0,\n\t\t\t\t\t\t\topacity: 0,\n\t\t\t\t\t\t\ttransition: {\n\t\t\t\t\t\t\t\theight: { type: 'spring', stiffness: 500, damping: 40, mass: 0.8 },\n\t\t\t\t\t\t\t\topacity: { duration: 0.15, ease: 'easeIn' },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tclassName='min-h-0 overflow-hidden'\n\t\t\t\t\t>\n\t\t\t\t\t\t{tables.length > 0 ? (\n\t\t\t\t\t\t\t<div className='relative mt-2 min-h-0'>\n\t\t\t\t\t\t\t\t<ScrollArea\n\t\t\t\t\t\t\t\t\tref={scrollRef}\n\t\t\t\t\t\t\t\t\tonScroll={handleScroll}\n\t\t\t\t\t\t\t\t\tstyle={scrollAreaStyle}\n\t\t\t\t\t\t\t\t\tclassName='scrollbar-neutral-thin min-h-0'\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<div className='space-y-0.5 pr-1 pb-2 pl-1'>\n\t\t\t\t\t\t\t\t\t\t{tables.map((table) => (\n\t\t\t\t\t\t\t\t\t\t\t<TableItem\n\t\t\t\t\t\t\t\t\t\t\t\tkey={table.value}\n\t\t\t\t\t\t\t\t\t\t\t\ttable={table}\n\t\t\t\t\t\t\t\t\t\t\t\tactiveTable={activeTable}\n\t\t\t\t\t\t\t\t\t\t\t\tonTableSelect={onTableSelect}\n\t\t\t\t\t\t\t\t\t\t\t\titemRef={table.value === activeTable ? activeItemRef : undefined}\n\t\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</ScrollArea>\n\t\t\t\t\t\t\t\t{showBottomBlur && tables.length > 3 && (\n\t\t\t\t\t\t\t\t\t<ProgressiveBlur position='bottom' height={blurHeight} surface='background' intensity={0.22} />\n\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t<div className='flex flex-col items-center justify-center py-6 text-center'>\n\t\t\t\t\t\t\t\t<div className='bg-muted mb-2 flex h-10 w-10 items-center justify-center rounded-full'>\n\t\t\t\t\t\t\t\t\t{hasSearchTerm ? (\n\t\t\t\t\t\t\t\t\t\t<RiSearchLine className='text-muted-foreground h-5 w-5' />\n\t\t\t\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t\t\t\t<RiDatabaseLine className='text-muted-foreground h-5 w-5' />\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<p className='text-muted-foreground text-xs'>{emptyMessage}</p>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t)}\n\t\t\t\t\t</motion.div>\n\t\t\t\t)}\n\t\t\t</AnimatePresence>\n\t\t</Collapsible>\n\t);\n}\n","// Public contract for defining and overriding cell types.\n//\n// A CellTypeDefinition unifies DETECTION (`match`) and native DISPLAY\n// (`toSheetsCell` / `cell`) and native EDITING (`editorComponent`) in one object.\n// Consumers register them per-instance via `<SheetsProvider config={{ plugins }}>`\n// or `<Sheets cellTypes>`; a def whose `typeKey` matches a built-in overrides that\n// built-in for this grid, and a def with a `match()` adds detection. Any concern\n// left undefined falls back to the built-in behavior, so a def may override just\n// the editor, just the display, or add a brand-new type end-to-end.\n\nimport type { CellCategory } from './types';\n// Type-only imports (erased at runtime) — avoids a cell-types -> grid cycle.\nimport type { CellCreationMetadata } from '../grid/grid-cell-types';\nimport type { SheetsCell } from '../cell-model/sheets-cell';\nimport type { CellProps } from '../cell-model/cell-props';\nimport type { EditorProps } from '../grid-dom/editors/editor-props';\n\n/** Schema-only inputs used to DETECT a cell type. Never the runtime value. */\nexport interface CellTypeMatchInput {\n\tgqlType: string;\n\tisArray: boolean;\n\tpgAlias?: string | null;\n\tpgType?: string | null;\n\tsubtype?: string | null;\n\tfieldName?: string;\n}\n\n/** Context handed to `toSheetsCell` so a definition can build the neutral cell.\n * Geometry uses the built-in fallback, so no `createGeometry` callback is needed. */\nexport interface SheetsCellRenderContext {\n\tmetadata: CellCreationMetadata;\n}\n\nexport interface CellTypeDefinition<TValue = unknown> {\n\t/** Stable key. A def whose typeKey equals a built-in (e.g. 'relation') overrides it. */\n\ttypeKey: string;\n\tcategory?: CellCategory;\n\t/** Toolbar / type-picker icon. */\n\ticon?: React.ComponentType<{ size?: number }>;\n\tdefaultWidth?: number;\n\tsupportsInlineEdit?: boolean;\n\t/** DETECTION (schema-only). Highest-priority match wins; omit for typeKey-only. */\n\tmatch?: (meta: CellTypeMatchInput) => boolean;\n\t/** Native DISPLAY. Build the neutral SheetsCell. Omit to keep the built-in renderer. */\n\ttoSheetsCell?: (value: TValue, ctx: SheetsCellRenderContext) => SheetsCell;\n\t/** Native cell COMPONENT override (the slot target). Omit to keep the built-in view. */\n\tcell?: React.ComponentType<CellProps>;\n\t/** Native EDITOR override (DOM portal overlay). Omit to keep the built-in native editor. */\n\teditorComponent?: React.ComponentType<EditorProps>;\n\t/** Value -> display/copy/export string. */\n\tformat?: (value: TValue) => string;\n\tdefaultValue?: () => TValue;\n}\n\n/** Identity helper that pins the generic — `defineCellType<number>({ ... })`. */\nexport function defineCellType<T = unknown>(def: CellTypeDefinition<T>): CellTypeDefinition<T> {\n\treturn def;\n}\n\n/** A named bundle of cell types, registered via `SheetsConfig.plugins`. */\nexport interface CellTypePlugin {\n\tname: string;\n\tcellTypes: CellTypeDefinition<any>[];\n}\n\nexport type { CellCreationMetadata };\n","export function createMetadataHash(value: unknown): string {\n\tconst serialized = JSON.stringify(value, stableReplacer);\n\tlet hash = 0;\n\tfor (let index = 0; index < serialized.length; index += 1) {\n\t\thash = (hash * 33) ^ serialized.charCodeAt(index);\n\t}\n\n\treturn `h${(hash >>> 0).toString(16)}`;\n}\n\nfunction stableReplacer(_key: string, value: unknown): unknown {\n\tif (value && typeof value === 'object' && !Array.isArray(value)) {\n\t\treturn Object.keys(value)\n\t\t\t.sort()\n\t\t\t.reduce<Record<string, unknown>>((acc, key) => {\n\t\t\t\tacc[key] = (value as Record<string, unknown>)[key];\n\t\t\t\treturn acc;\n\t\t\t}, {});\n\t}\n\treturn value;\n}\n","import { mapToFrontendCellType } from '../cell-types/type-mapping';\n\nimport { createMetadataHash } from './metadata-hash';\nimport type {\n\tBuildFormSpecOptions,\n\tDynamicFormSpec,\n\tMetaField,\n\tMetaTable,\n\tScalarFieldKind,\n\tScalarFieldSpec,\n} from './types';\n\nconst SCALAR_CELL_TYPE_TO_KIND: Partial<Record<string, ScalarFieldKind>> = {\n\ttext: 'text',\n\ttextarea: 'multiline',\n\tcitext: 'text',\n\tbpchar: 'text',\n\temail: 'email',\n\turl: 'url',\n\tphone: 'phone',\n\tuuid: 'uuid',\n\tinet: 'inet',\n\tnumber: 'number',\n\tinteger: 'integer',\n\tsmallint: 'smallint',\n\tdecimal: 'decimal',\n\tcurrency: 'currency',\n\tpercentage: 'percentage',\n\tboolean: 'boolean',\n\tbit: 'bit',\n\tdate: 'date',\n\tdatetime: 'datetime',\n\ttime: 'time',\n\ttimestamptz: 'timestamptz',\n\tjson: 'json',\n\tjsonb: 'json',\n\ttsvector: 'tsvector',\n};\n\nconst HUMAN_CASE_REGEX = /([a-z0-9])([A-Z])/g;\n\nexport function buildScalarFormSpec(metaTable: MetaTable, options: BuildFormSpecOptions = {}): DynamicFormSpec | null {\n\tconst fields: ScalarFieldSpec[] = [];\n\tconst uniqueFieldSet = collectSingleFieldUniqueNames(metaTable);\n\tconst primaryFieldSet = collectSingleFieldPrimaryNames(metaTable);\n\n\tfor (const field of metaTable.fields ?? []) {\n\t\tif (!field) continue;\n\n\t\tconst spec = createScalarFieldSpec(field, options, uniqueFieldSet, primaryFieldSet);\n\t\tif (!spec) continue;\n\n\t\tfields.push(spec);\n\t}\n\n\tif (fields.length === 0) {\n\t\treturn null;\n\t}\n\n\tconst versionHash = createMetadataHash({\n\t\ttable: metaTable.name,\n\t\tfields: fields.map((f) => ({\n\t\t\tname: f.name,\n\t\t\tkind: f.kind,\n\t\t\tnullable: f.nullable,\n\t\t\tmetadata: f.metadata,\n\t\t\tmaxLength: f.maxLength,\n\t\t\tminLength: f.minLength,\n\t\t\tminimum: f.minimum,\n\t\t\tmaximum: f.maximum,\n\t\t\tenumValues: f.enumValues,\n\t\t})),\n\t});\n\n\treturn {\n\t\ttableName: metaTable.name,\n\t\tversionHash,\n\t\tfields,\n\t};\n}\n\nexport function findTableFormSpec(\n\tmeta: MetaTable[] | null | undefined,\n\ttableName: string,\n\toptions: BuildFormSpecOptions = {},\n): DynamicFormSpec | null {\n\tif (!meta) return null;\n\tconst table = meta.find((item) => item?.name === tableName);\n\tif (!table) return null;\n\treturn buildScalarFormSpec(table, options);\n}\n\nfunction createScalarFieldSpec(\n\tmetaField: MetaField,\n\toptions: BuildFormSpecOptions,\n\tuniqueFields: Set<string>,\n\tprimaryFields: Set<string>,\n): ScalarFieldSpec | null {\n\tconst { multilineFields } = options;\n\tconst cellType = mapToFrontendCellType({\n\t\tgqlType: metaField.type.gqlType,\n\t\tisArray: metaField.type.isArray,\n\t\tpgAlias: metaField.type.pgAlias,\n\t\tpgType: metaField.type.pgType,\n\t\tsubtype: metaField.type.subtype ?? undefined,\n\t\tencoding: metaField.type.encoding,\n\t});\n\n\tif (metaField.type.isArray) {\n\t\treturn null;\n\t}\n\n\tlet kind = SCALAR_CELL_TYPE_TO_KIND[cellType];\n\n\tif (!kind && cellType === 'text' && multilineFields?.has(metaField.name)) {\n\t\tkind = 'multiline';\n\t}\n\n\tif (!kind) {\n\t\treturn null;\n\t}\n\n\tconst nullable = isFieldNullable(metaField);\n\tconst { maxLength, numericPrecision, numericScale } = extractTypmodConstraints(metaField);\n\n\tconst label = humanize(metaField.name);\n\tconst description = buildDescription(metaField);\n\n\tconst spec: ScalarFieldSpec = {\n\t\tname: metaField.name,\n\t\tlabel,\n\t\tdescription,\n\t\tkind,\n\t\tnullable,\n\t\tmetadata: {\n\t\t\tcellType,\n\t\t\tgqlType: metaField.type.gqlType,\n\t\t\tpgAlias: metaField.type.pgAlias ?? undefined,\n\t\t\tpgType: metaField.type.pgType ?? undefined,\n\t\t\tsubtype: metaField.type.subtype ?? undefined,\n\t\t\ttypmod: metaField.type.typmod ?? undefined,\n\t\t\tencoding: metaField.type.encoding ?? undefined,\n\t\t},\n\t\tconstraints: {\n\t\t\tisUnique: uniqueFields.has(metaField.name) || undefined,\n\t\t\tisPrimaryKey: primaryFields.has(metaField.name) || undefined,\n\t\t},\n\t};\n\n\tif (metaField.enumValues?.values?.length) {\n\t\tspec.enumValues = [...metaField.enumValues.values];\n\t}\n\n\tif (maxLength != null) {\n\t\tspec.maxLength = maxLength;\n\t}\n\n\tif (numericPrecision != null) {\n\t\tspec.numericPrecision = numericPrecision;\n\t}\n\n\tif (numericScale != null) {\n\t\tspec.numericScale = numericScale;\n\t}\n\n\tif (\n\t\tkind === 'decimal' ||\n\t\tkind === 'number' ||\n\t\tkind === 'integer' ||\n\t\tkind === 'smallint' ||\n\t\tkind === 'currency' ||\n\t\tkind === 'percentage'\n\t) {\n\t\tconst { minimum, maximum } = extractNumericCheckBounds(metaField);\n\t\tif (minimum != null) spec.minimum = minimum;\n\t\tif (maximum != null) spec.maximum = maximum;\n\t}\n\n\tif (kind === 'json') {\n\t\tspec.description = description ?? 'JSON value';\n\t}\n\n\tif (kind === 'boolean') {\n\t\tspec.defaultValue = false;\n\t}\n\n\treturn spec;\n}\n\nfunction buildDescription(metaField: MetaField): string | undefined {\n\tif (metaField.description) return metaField.description;\n\tconst details: string[] = [];\n\tconst { pgAlias, pgType, subtype } = metaField.type;\n\n\tif (pgAlias && pgAlias !== pgType) {\n\t\tdetails.push(pgAlias);\n\t}\n\tif (pgType) {\n\t\tdetails.push(pgType);\n\t}\n\tif (subtype) {\n\t\tdetails.push(subtype);\n\t}\n\n\treturn details.length > 0 ? details.join(' • ') : undefined;\n}\n\nfunction humanize(name: string): string {\n\treturn name.replace(HUMAN_CASE_REGEX, '$1 $2').replace(/^./, (str) => str.toUpperCase());\n}\n\nfunction isFieldNullable(metaField: MetaField): boolean {\n\tif (metaField.isNotNull === true || metaField.type.isNotNull === true) return false;\n\tconst gqlType = metaField.type.gqlType;\n\tif (gqlType.endsWith('!')) return false;\n\t// Note: modifier is a numeric code from PostgreSQL, not a string enum\n\t// The gqlType check above is the primary indicator of non-nullability\n\treturn true;\n}\n\nfunction extractTypmodConstraints(metaField: MetaField): {\n\tmaxLength?: number;\n\tnumericPrecision?: number;\n\tnumericScale?: number;\n} {\n\tconst typmod = metaField.type.typmod ?? null;\n\tconst pgType = metaField.type.pgType?.toLowerCase();\n\n\tif (typmod == null || typmod < 0) {\n\t\treturn {};\n\t}\n\n\tif (pgType === 'varchar' || pgType === 'character varying' || pgType === 'bpchar' || pgType === 'character') {\n\t\treturn { maxLength: Math.max(0, typmod - 4) };\n\t}\n\n\tif (pgType === 'numeric' || pgType === 'decimal') {\n\t\tconst precision = ((typmod - 4) >> 16) & 65535;\n\t\tconst scale = (typmod - 4) & 65535;\n\t\treturn {\n\t\t\tnumericPrecision: precision || undefined,\n\t\t\tnumericScale: scale || undefined,\n\t\t};\n\t}\n\n\treturn {};\n}\n\nfunction extractNumericCheckBounds(_metaField: MetaField): { minimum?: number; maximum?: number } {\n\t// Placeholder for future enhancements: currently return empty bounds.\n\t// Backend check constraints can be parsed here when the metadata exposes readable expressions.\n\treturn {};\n}\n\nfunction collectSingleFieldUniqueNames(metaTable: MetaTable): Set<string> {\n\tconst result = new Set<string>();\n\n\tfor (const constraint of metaTable.uniqueConstraints ?? []) {\n\t\tif (!constraint || !constraint.fields) continue;\n\t\tconst fields = constraint.fields.filter((field): field is MetaField => Boolean(field));\n\t\tif (fields.length === 1) {\n\t\t\tresult.add(fields[0].name);\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction collectSingleFieldPrimaryNames(metaTable: MetaTable): Set<string> {\n\tconst result = new Set<string>();\n\tfor (const constraint of metaTable.primaryKeyConstraints ?? []) {\n\t\tif (!constraint) continue;\n\t\tconst fields = constraint.fields?.filter((field): field is MetaField => Boolean(field));\n\t\tif (fields && fields.length === 1) {\n\t\t\tresult.add(fields[0].name);\n\t\t}\n\t}\n\treturn result;\n}\n","import { z } from 'zod';\n\nimport type { DynamicFormSpec, ScalarFieldSpec } from './types';\n\nconst schemaCache = new Map<string, z.ZodObject<Record<string, z.ZodTypeAny>>>();\n\nexport function buildZodSchema(spec: DynamicFormSpec): z.ZodObject<Record<string, z.ZodTypeAny>> {\n\tconst cached = schemaCache.get(spec.versionHash);\n\tif (cached) {\n\t\treturn cached;\n\t}\n\n\tconst shape: Record<string, z.ZodTypeAny> = {};\n\n\tfor (const field of spec.fields) {\n\t\tshape[field.name] = buildFieldSchema(field);\n\t}\n\n\tconst schema = z.object(shape);\n\tschemaCache.set(spec.versionHash, schema);\n\treturn schema;\n}\n\nfunction buildFieldSchema(field: ScalarFieldSpec): z.ZodTypeAny {\n\tlet baseSchema: z.ZodTypeAny;\n\tlet isStringSchema = false;\n\n\tswitch (field.kind) {\n\t\tcase 'email':\n\t\t\tbaseSchema = z.string({ error: 'Email is required' }).email('Invalid email address');\n\t\t\tisStringSchema = true;\n\t\t\tbreak;\n\t\tcase 'url':\n\t\t\tbaseSchema = z.string({ error: 'URL is required' }).url('Invalid URL');\n\t\t\tisStringSchema = true;\n\t\t\tbreak;\n\t\tcase 'phone':\n\t\t\tbaseSchema = z\n\t\t\t\t.string({ error: 'Phone number is required' })\n\t\t\t\t.refine((value) => /^\\+?[0-9\\-()\\s]+$/.test(value), { message: 'Invalid phone number' });\n\t\t\tbreak;\n\t\tcase 'uuid':\n\t\t\tbaseSchema = z.string({ error: 'UUID is required' }).uuid('Invalid UUID');\n\t\t\tisStringSchema = true;\n\t\t\tbreak;\n\t\tcase 'inet':\n\t\t\tbaseSchema = z\n\t\t\t\t.string({ error: 'IP address is required' })\n\t\t\t\t.refine((value) => isValidInet(value), { message: 'Invalid IP address' });\n\t\t\tbreak;\n\t\tcase 'boolean':\n\t\t\tbaseSchema = z.preprocess(\n\t\t\t\t(value) => {\n\t\t\t\t\tif (typeof value === 'string') {\n\t\t\t\t\t\tif (value === 'true') return true;\n\t\t\t\t\t\tif (value === 'false') return false;\n\t\t\t\t\t}\n\t\t\t\t\treturn value;\n\t\t\t\t},\n\t\t\t\tz.boolean({ error: 'Required' }),\n\t\t\t);\n\t\t\tbreak;\n\t\tcase 'bit':\n\t\t\tbaseSchema = z.union([z.literal('0'), z.literal('1')]);\n\t\t\tbreak;\n\t\tcase 'integer':\n\t\tcase 'smallint':\n\t\tcase 'number':\n\t\tcase 'decimal':\n\t\tcase 'currency':\n\t\tcase 'percentage':\n\t\t\tbaseSchema = buildNumericSchema(field);\n\t\t\tbreak;\n\t\tcase 'date':\n\t\tcase 'datetime':\n\t\tcase 'timestamptz':\n\t\tcase 'time':\n\t\t\tbaseSchema = z\n\t\t\t\t.string({ error: 'Required' })\n\t\t\t\t.refine((value) => value.length > 0, { message: 'Required' });\n\t\t\tbreak;\n\t\tcase 'json':\n\t\t\tbaseSchema = z\n\t\t\t\t.string({ error: 'JSON is required' })\n\t\t\t\t.superRefine((value, ctx) => {\n\t\t\t\t\tif (value === '' && field.nullable) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tJSON.parse(value);\n\t\t\t\t} catch (_error) {\n\t\t\t\t\t\tctx.addIssue({\n\t\t\t\t\t\t\tcode: z.ZodIssueCode.custom,\n\t\t\t\t\t\t\tmessage: 'Invalid JSON',\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.transform((value) => {\n\t\t\t\t\tif (value === '') {\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\treturn JSON.parse(value);\n\t\t\t\t});\n\t\t\tbreak;\n\t\tcase 'tsvector':\n\t\tcase 'multiline':\n\t\tcase 'text':\n\t\tdefault:\n\t\t\tbaseSchema = z.string({ error: 'Required' });\n\t\t\tisStringSchema = true;\n\t\t\tbreak;\n\t}\n\n\t// Apply string constraints (tracked via isStringSchema flag for zod v4 compat)\n\tif (isStringSchema) {\n\t\tif ('maxLength' in field && typeof field.maxLength === 'number') {\n\t\t\tbaseSchema = (baseSchema as z.ZodString).max(field.maxLength, `Must be at most ${field.maxLength} characters`);\n\t\t}\n\n\t\tif ('minLength' in field && typeof field.minLength === 'number') {\n\t\t\tbaseSchema = (baseSchema as z.ZodString).min(field.minLength, `Must be at least ${field.minLength} characters`);\n\t\t}\n\t}\n\n\tif (field.enumValues && field.enumValues.length > 0) {\n\t\tbaseSchema = z.enum(field.enumValues as [string, ...string[]]);\n\t}\n\n\tif (!field.nullable) {\n\t\treturn baseSchema;\n\t}\n\n\tif (field.kind === 'json') {\n\t\treturn baseSchema.optional().nullable();\n\t}\n\n\treturn baseSchema.nullable().optional();\n}\n\nfunction buildNumericSchema(field: ScalarFieldSpec): z.ZodTypeAny {\n\t// Build inner number schema with all constraints\n\tconst preprocessFn = (value: unknown) => {\n\t\tif (value === '' || value === null || value === undefined) {\n\t\t\treturn value;\n\t\t}\n\t\tif (typeof value === 'number') return value;\n\t\tif (typeof value === 'string') {\n\t\t\tconst parsed = Number(value);\n\t\t\treturn Number.isNaN(parsed) ? value : parsed;\n\t\t}\n\t\treturn value;\n\t};\n\n\tlet innerSchema = z.number({\n\t\terror: 'Must be a valid number',\n\t});\n\n\t// Apply integer constraint\n\tif (field.kind === 'integer' || field.kind === 'smallint') {\n\t\tinnerSchema = innerSchema.int('Must be an integer');\n\t}\n\n\t// Apply range constraints\n\tif (field.kind === 'smallint') {\n\t\tinnerSchema = innerSchema.min(-32768, 'Must be >= -32768').max(32767, 'Must be <= 32767');\n\t} else {\n\t\tif (typeof field.minimum === 'number') {\n\t\t\tinnerSchema = innerSchema.min(field.minimum, `Must be >= ${field.minimum}`);\n\t\t}\n\n\t\tif (typeof field.maximum === 'number') {\n\t\t\tinnerSchema = innerSchema.max(field.maximum, `Must be <= ${field.maximum}`);\n\t\t}\n\t}\n\n\treturn z.preprocess(preprocessFn, innerSchema);\n}\n\nfunction isValidInet(value: string): boolean {\n\tconst ipv4 = /^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$/;\n\tconst ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::1)$/;\n\treturn ipv4.test(value) || ipv6.test(value);\n}\n","import * as React from 'react';\n\nimport { useSheetsTable } from '../hooks/use-sheets-table';\nimport type { SheetsRowIdentifier } from '../row-identity';\n\nexport interface DynamicMutationResult<TData = unknown> {\n\tsubmit: (values: Record<string, unknown>) => Promise<TData | null>;\n\tisSubmitting: boolean;\n\terror: Error | null;\n}\n\nexport function useDynamicCreate(tableName: string): DynamicMutationResult {\n\tconst table = useSheetsTable(tableName, { enabled: false });\n\n\tconst submit = React.useCallback(\n\t\tasync (values: Record<string, unknown>) => {\n\t\t\tconst result = await table.create(values);\n\t\t\treturn result.createdRow ?? null;\n\t\t},\n\t\t[table],\n\t);\n\n\treturn {\n\t\tsubmit,\n\t\tisSubmitting: table.isCreating,\n\t\terror: table.createError,\n\t};\n}\n\nexport function useDynamicUpdate(tableName: string, rowId: SheetsRowIdentifier): DynamicMutationResult {\n\tconst table = useSheetsTable(tableName, { enabled: false });\n\n\tconst submit = React.useCallback(\n\t\tasync (values: Record<string, unknown>) => {\n\t\t\tconst result = await table.update(rowId, values);\n\t\t\treturn result.updatedRow ?? null;\n\t\t},\n\t\t[table, rowId],\n\t);\n\n\treturn {\n\t\tsubmit,\n\t\tisSubmitting: table.isUpdating,\n\t\terror: table.updateError,\n\t};\n}\n","import { useCallback, useMemo, useState } from 'react';\nimport type { ReactNode } from 'react';\n\nimport { isValuelessOperator } from '../filter-operators';\nimport {\n\tcreateEmptyGroup,\n\ttype FilterGroup,\n\ttype FilterNode,\n} from '../sheets.controls';\nimport { buildWhereFromFilters } from '../sheets.utils';\n\n// Data filtering context type\nexport interface DataFilteringContextValue {\n\tfilterTree: FilterGroup;\n\tfiltersOpen: boolean;\n\teffectiveWhere: any;\n\thasActiveFilters: boolean;\n\tsetFilterTree: (tree: FilterGroup) => void;\n\tsetFiltersOpen: (open: boolean) => void;\n\tclearAllFilters: () => void;\n\tapplyFilters: () => void;\n}\n\n// Data filtering hook configuration\nexport interface UseDataFilteringConfig {\n\tcolumnKeys: string[];\n\ttableMeta?: {\n\t\tfields?: Array<{\n\t\t\tname?: string | null;\n\t\t\ttype?: {\n\t\t\t\tgqlType?: string | null;\n\t\t\t} | null;\n\t\t} | null> | null;\n\t} | null;\n\tinitialFilterTree?: FilterGroup;\n}\n\nfunction hasActiveNode(node: FilterNode): boolean {\n\tif (node.type === 'condition') {\n\t\treturn isValuelessOperator(node.operator) ||\n\t\t\t(node.value !== '' && node.value !== null && node.value !== undefined);\n\t}\n\treturn node.children.some(hasActiveNode);\n}\n\n// Main data filtering hook — uses local state instead of global Zustand store\nexport function useDataFiltering({\n\tcolumnKeys,\n\ttableMeta,\n\tinitialFilterTree,\n}: UseDataFilteringConfig) {\n\tconst [filterTree, setFilterTree] = useState<FilterGroup>(initialFilterTree ?? createEmptyGroup());\n\tconst [filtersOpen, setFiltersOpen] = useState(false);\n\n\tconst clearAllFilters = useCallback(() => {\n\t\tsetFilterTree(createEmptyGroup());\n\t}, []);\n\n\t// applyFilters is a no-op since state is already reactive\n\tconst applyFilters = useCallback(() => {}, []);\n\n\t// Compute effective where clause from current filters\n\tconst effectiveWhere = useMemo(\n\t\t() => buildWhereFromFilters(filterTree, tableMeta),\n\t\t[filterTree, tableMeta],\n\t);\n\n\t// Check if there are active filters\n\tconst hasActiveFilters = useMemo(\n\t\t() => hasActiveNode(filterTree),\n\t\t[filterTree],\n\t);\n\n\tconst contextValue: DataFilteringContextValue = useMemo(\n\t\t() => ({\n\t\t\tfilterTree,\n\t\t\tfiltersOpen,\n\t\t\teffectiveWhere,\n\t\t\thasActiveFilters,\n\t\t\tsetFilterTree,\n\t\t\tsetFiltersOpen,\n\t\t\tclearAllFilters,\n\t\t\tapplyFilters,\n\t\t}),\n\t\t[filterTree, filtersOpen, effectiveWhere, hasActiveFilters, clearAllFilters, applyFilters],\n\t);\n\n\treturn {\n\t\tcontextValue,\n\t\tProvider: ({ children }: { children: ReactNode }) => children,\n\t};\n}\n","import { useCallback, useEffect, useMemo, useState } from 'react';\n\n// Data pagination context type\nexport interface DataPaginationContextValue {\n\t// Pagination state\n\tpageIndex: number;\n\tpageSize: number;\n\ttotalCount: number;\n\ttotalPages: number;\n\n\t// Computed values\n\thasNextPage: boolean;\n\thasPreviousPage: boolean;\n\tstartIndex: number;\n\tendIndex: number;\n\n\t// Actions\n\tsetPageIndex: (index: number) => void;\n\tsetPageSize: (size: number) => void;\n\tgoToNextPage: () => void;\n\tgoToPreviousPage: () => void;\n\tgoToFirstPage: () => void;\n\tgoToLastPage: () => void;\n}\n\n// Data pagination hook configuration\nexport interface UseDataPaginationConfig {\n\tinitialPageSize?: number;\n\tinitialPageIndex?: number;\n\ttotalCount?: number;\n\tonPageChange?: (pageIndex: number, pageSize: number) => void;\n}\n\n// Main data pagination hook — uses local state instead of global Zustand store\nexport function useDataPagination({\n\tinitialPageSize = 100,\n\tinitialPageIndex = 0,\n\ttotalCount = 0,\n\tonPageChange,\n}: UseDataPaginationConfig) {\n\tconst [pageIndex, setPageIndexState] = useState(initialPageIndex);\n\tconst [pageSize, setPageSizeState] = useState(initialPageSize);\n\n\t// Compute pagination values\n\tconst totalPages = useMemo(() => Math.max(1, Math.ceil(totalCount / pageSize)), [totalCount, pageSize]);\n\tconst hasNextPage = useMemo(() => pageIndex < totalPages - 1, [pageIndex, totalPages]);\n\tconst hasPreviousPage = useMemo(() => pageIndex > 0, [pageIndex]);\n\tconst startIndex = useMemo(() => pageIndex * pageSize + 1, [pageIndex, pageSize]);\n\tconst endIndex = useMemo(() => Math.min((pageIndex + 1) * pageSize, totalCount), [pageIndex, pageSize, totalCount]);\n\n\tuseEffect(() => {\n\t\tif (pageSize !== initialPageSize) {\n\t\t\tsetPageSizeState(initialPageSize);\n\t\t}\n\t}, [initialPageSize]); // eslint-disable-line react-hooks/exhaustive-deps\n\n\tuseEffect(() => {\n\t\tif (pageIndex !== initialPageIndex) {\n\t\t\tsetPageIndexState(initialPageIndex);\n\t\t}\n\t}, [initialPageIndex]); // eslint-disable-line react-hooks/exhaustive-deps\n\n\t// Auto-adjust page index when total pages changes\n\tuseEffect(() => {\n\t\tif (pageIndex >= totalPages && totalPages > 0) {\n\t\t\tsetPageIndexState(Math.max(0, totalPages - 1));\n\t\t}\n\t}, [pageIndex, totalPages]);\n\n\t// Page index setter with callback\n\tconst setPageIndex = useCallback(\n\t\t(index: number) => {\n\t\t\tconst clampedIndex = Math.max(0, Math.min(index, totalPages - 1));\n\t\t\tsetPageIndexState(clampedIndex);\n\t\t\tonPageChange?.(clampedIndex, pageSize);\n\t\t},\n\t\t[totalPages, pageSize, onPageChange],\n\t);\n\n\t// Page size setter with callback and reset to first page\n\tconst setPageSize = useCallback(\n\t\t(size: number) => {\n\t\t\tsetPageSizeState(size);\n\t\t\tsetPageIndexState(0);\n\t\t\tonPageChange?.(0, size);\n\t\t},\n\t\t[onPageChange],\n\t);\n\n\t// Navigation actions\n\tconst goToNextPage = useCallback(() => {\n\t\tif (hasNextPage) {\n\t\t\tsetPageIndex(pageIndex + 1);\n\t\t}\n\t}, [hasNextPage, pageIndex, setPageIndex]);\n\n\tconst goToPreviousPage = useCallback(() => {\n\t\tif (hasPreviousPage) {\n\t\t\tsetPageIndex(pageIndex - 1);\n\t\t}\n\t}, [hasPreviousPage, pageIndex, setPageIndex]);\n\n\tconst goToFirstPage = useCallback(() => {\n\t\tsetPageIndex(0);\n\t}, [setPageIndex]);\n\n\tconst goToLastPage = useCallback(() => {\n\t\tsetPageIndex(totalPages - 1);\n\t}, [totalPages, setPageIndex]);\n\n\tconst contextValue: DataPaginationContextValue = useMemo(\n\t\t() => ({\n\t\t\tpageIndex,\n\t\t\tpageSize,\n\t\t\ttotalCount,\n\t\t\ttotalPages,\n\t\t\thasNextPage,\n\t\t\thasPreviousPage,\n\t\t\tstartIndex,\n\t\t\tendIndex,\n\t\t\tsetPageIndex,\n\t\t\tsetPageSize,\n\t\t\tgoToNextPage,\n\t\t\tgoToPreviousPage,\n\t\t\tgoToFirstPage,\n\t\t\tgoToLastPage,\n\t\t}),\n\t\t[\n\t\t\tpageIndex,\n\t\t\tpageSize,\n\t\t\ttotalCount,\n\t\t\ttotalPages,\n\t\t\thasNextPage,\n\t\t\thasPreviousPage,\n\t\t\tstartIndex,\n\t\t\tendIndex,\n\t\t\tsetPageIndex,\n\t\t\tsetPageSize,\n\t\t\tgoToNextPage,\n\t\t\tgoToPreviousPage,\n\t\t\tgoToFirstPage,\n\t\t\tgoToLastPage,\n\t\t],\n\t);\n\n\treturn {\n\t\tcontextValue,\n\t\tProvider: ({ children }: { children: any }) => children,\n\t};\n}\n\n// Convenience hooks for accessing specific parts of the context\nexport function usePaginationState() {\n\t// Placeholder — real values come from the contextValue returned by useDataPagination\n\treturn { pageIndex: 0, pageSize: 100 };\n}\n\nexport function usePaginationActions() {\n\t// Placeholder — real actions come from the contextValue\n\treturn {\n\t\tsetPageIndex: (_index: number) => {},\n\t\tsetPageSize: (_size: number) => {},\n\t\tgoToNext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Aa,CAAC;AAAA,EAC5B,GAAG,CAAC,YAAY,YAAY,CAAC;AAE7B,QAAM,eAA2CE;AAAA,IAChD,OAAO;AAAA,MACN;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACD;AAAA,IACA;AAAA,MACC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACD;AAAA,EACD;AAEA,SAAO;AAAA,IACN;AAAA,IACA,UAAU,CAAC,EAAE,SAAS,MAAyB;AAAA,EAChD;AACD;","names":["useCallback","useEffect","useImperativeHandle","useMemo","useRef","useState","Button","FilterConditionRow","FilterGroupUI","useState","RiAddLine","RiDeleteBin6Line","AlertDialog","AlertDialogAction","AlertDialogCancel","AlertDialogContent","AlertDialogDescription","AlertDialogFooter","AlertDialogHeader","AlertDialogTitle","Fragment","jsx","jsxs","key","useCallback","useEffect","useMemo","jsx","useEffect","useCallback","useMemo","useCallback","Button","jsx","jsxs","useCallback","Button","useCallback","RiCheckLine","RiCloseLine","RiErrorWarningLine","RiLoader4Line","AnimatePresence","motion","jsx","jsxs","useCallback","AnimatePresence","motion","StatusIcon","RiCloseLine","RiLoader4Line","RiCheckLine","RiErrorWarningLine","RiAddLine","RiErrorWarningLine","Button","jsx","jsxs","RiErrorWarningLine","Button","RiAddLine","jsx","Button","jsx","jsxs","useCallback","useEffect","useMemo","useRef","useCallback","useMemo","baseType","key","relationData","fkField","foreignKeyUpdates","useCallback","useMemo","useMemo","useCallback","useMemo","key","useCallback","columnKeys","useCallback","useCallback","useCallback","useRef","legacyRowIdentifier","useRef","useCallback","useCallback","useRef","useState","clear","useMemo","useMemo","useCallback","useMemo","useState","useState","useCallback","useMemo","useCallback","useMemo","key","isDraftRow","useMemo","cache","useCallback","hit","resolution","useCallback","useCallback","useMemo","useMemo","useCallback","useMemo","useReducer","key","useReducer","useCallback","useMemo","useCallback","useMemo","useCallback","useEffect","useMemo","useRef","useState","useQueryClient","cleanTable","useQueryClient","useMemo","useState","useRef","cleanTable","useEffect","useCallback","useMemo","useCallback","useMemo","buildFieldMetaMap","useMemo","useRef","useCallback","useMemo","useEffect","key","useMemo","useMemo","useMemo","useRef","jsx","jsxs","useRef","useMemo","memo","useCallback","useRef","jsx","Checkbox","jsx","Button","jsx","jsxs","Button","jsx","jsxs","img","jsx","jsxs","jsx","jsx","jsx","jsxs","jsx","jsx","useRef","useState","jsx","useState","useRef","jsx","memo","SheetsCellHostInner","useRef","useCallback","Component","useCallback","useState","useEffect","useLayoutEffect","useMemo","useRef","useState","Component","jsx","jsxs","Component","jsx","useRef","useState","useMemo","useLayoutEffect","useEffect","key","Fragment","jsx","jsxs","ESTIMATED_ROW_HEIGHT","useRef","useMemo","useCallback","key","useImperativeHandle","useEffect","overlay","useState","active","Button","memo","useCallback","useEffect","useMemo","useRef","useState","RiAddLine","AnimatePresence","motion","Button","Input","jsx","jsxs","memo","TableItem","SheetsTableSelector","useState","useRef","useMemo","useEffect","useCallback","RiAddLine","motion","AnimatePresence","key","React","useCallback","useMemo","useState","useState","useCallback","useMemo","useCallback","useEffect","useMemo","useState"]}