Core API signatures

API catalog generated from the exported TypeScript GridEngine type. Use the package guide for behavior/examples and match the selected documentation version to your installed packages. Coordinates are zero-based visible indices unless a con

npm 0.2.1文档修订 13更新 2026-10-2215e5a98

已发布软件包的范围。请选择与应用已安装软件包一致的版本。

技术正文为英文;导航使用所选语言。

Package guide · Version policy

Data and lifecycle

subscribe

subscribe: (subscriber: { readonly onEvent?: (event: GridEvent) => void; readonly onInvalidate?: (change: GridInvalidation) => void; }) => () => void

Register independent event/invalidation observers. Returns an unsubscribe function; callbacks observe committed state and cannot perform nested mutations. Registration requires a live engine.

takeObserverErrors

takeObserverErrors: () => unknown[]

Drain the bounded observer error queue without changing data or history. Observer failures do not roll back committed commands.

captureRowIdentity

captureRowIdentity: () => readonly RowId[]

Capture source row IDs before an external structural change. This explicit operation scans every source row; call refreshData with the captured IDs afterward.

refreshData

refreshData: (previousRowIds?: readonly RowId[] | "values") => void

Reconcile external source changes and clear history/pending cut. Values mode requires unchanged IDs/order/count; an ID snapshot enables remapping; without IDs row-dependent metadata is dropped.

sourceRowCount

sourceRowCount: number

Number of source rows, before local filtering or collapsed groups. This differs from the visible rowCount.

getRowId

getRowId: (row: number) => RowId

Resolve a visible row to its stable source ID. Invalid row indices are rejected by the source/mapping contract.

columns

columns: readonly Readonly<{ permissions?: CellPermissionPolicy; defaultValue?: unknown; key: string; title: string; editable?: boolean; parse?: (text: string) => unknown; validate?: (value: unknown) => string | undefined; invalidInput?: "reject" | "allow"; }>[]

Frozen snapshots of the current column definitions in current display order. Application callbacks remain trusted code.

rowCount

rowCount: number

Visible row count after local view and collapsed-group projection; use sourceRowCount for the unprojected count.

getValue

getValue: (row: number, key: string) => unknown

Read a raw value using a visible row and column key. No parsing/formatting occurs; missing or unloaded values may be undefined according to the source contract.

editCell

editCell: (row: number, col: number, text: string) => void

Editor-style text command: resolve visible coordinates, require editable/writable, parse and validate before committing. Supports setValue or atomic setValues.

updateCells

updateCells: (updates: readonly CellUpdate[]) => void

Typed-value updates: resolve visible rows, validate and require writable, without editor parsing or editable checks. Duplicate cells use the last value. Multi-cell changes require atomic setValues.

updateCellsAsync

updateCellsAsync: (updates: readonly CellUpdate[], options: GridBulkOptions) => Promise<void>

Cooperative typed batch preparation with host scheduling, cancellation and optional external revision guard. One final synchronous atomic write; other engine mutations are blocked while pending.

replaceText

replaceText: (search: string, replacement: string, options?: { readonly scope?: "view" | "selection"; readonly caseSensitive?: boolean; }) => Readonly<{ changedCells: number; matches: number; }>

Available in 0.2.0: bounded literal replacement of string values in the view or selection. Requires editable/writable and validation; one atomic undo command. It is not a regular-expression API.

destroy

destroy: () => void

Idempotently release engine-owned observers, history and selection. The host still owns source destruction/transport. Data/layout commands and clipboard operations reject after destruction; undo/redo return false. Do not use retained read getters as a live engine after disposal.

Selection and clipboard

getSelection

getSelection: () => CellSelection | null

Current visible active cell, or null. It is not a source-coordinate address; use getRowSourceIndex when needed.

getSelectionRange

getSelectionRange: () => SelectionRange | null

Current active visible range, or null. Other retained selection ranges are available through getSelectionRanges.

getSelectionRanges

getSelectionRanges: () => SelectionRange[]

Visible selection ranges including retained ranges. Projection can split source ranges into multiple visible fragments; serialization has explicit fragment limits.

select

select: (row: number, col: number, extend?: boolean) => boolean

Select a visible cell, or extend from the anchor when extend is true. Selectable policy can veto; returns whether selection changed.

selectRange

selectRange: (range: SelectionRange, mode?: "replace" | "add" | "extend") => boolean

Select an inclusive visible rectangle with replace/add/extend semantics. Validate bounds, policies and projected fragmentation before changing selection.

clearSelection

clearSelection: () => void

Clear active/retained selection and anchor, with selection invalidation/events when changed. Does not change values or create a value-history command.

cutSelectionBlocks

cutSelectionBlocks: () => string

Stage a same-engine cut and return structured clipboard text. Data is not deleted until a successful matching paste commit.

cancelCut

cancelCut: () => void

Cancel the staged cut without modifying data. It is harmless when no cut exists, including after disposal. Host clipboard ownership remains separate.

pasteCutSelectionBlocks

pasteCutSelectionBlocks: (text: string) => void

Move a matching staged cut to the selected destination after complete validation/permissions/conflict preflight. A failed operation preserves source values.

copySelectionBlocks

copySelectionBlocks: () => string

Return versioned structured clipboard text including supported formatting through copy permissions. Values use string clipboard encoding; fragment/cell/text limits apply.

pasteSelectionBlocks

pasteSelectionBlocks: (text: string, options?: PasteOptions) => void

Decode structured clipboard text and atomically preflight values/formats. PasteOptions supports all/values/formats, transpose and skipEmpty; format-only bypasses parsers/value writes and checks format permission. Clipboard strings never execute callbacks.

copySelection

copySelection: () => string

Return packed TSV through copy permissions. Core does not access the operating-system clipboard; cell/fragment/text limits apply.

paste

paste: (text: string, options?: PasteOptions) => void

Parse TSV/editor text and atomically preflight destinations, parsing, permissions and validation. PasteOptions supports all/values/formats, transpose and skipEmpty; TSV carries no formats. Empty means an empty clipboard string, not whitespace.

pasteAsync

pasteAsync: (text: string, bulk: GridBulkOptions, options?: PasteOptions) => Promise<void>

Cooperative TSV parsing/preflight with the same paste options, limits and permissions. One atomic commit/history entry. Structured clipboard operations remain synchronous.

History

undo

undo: () => boolean

Replay the most recent command under current identity/value/permission checks. Return false when no command exists; conflicts can reject without changing history/data.

redo

redo: () => boolean

Replay a previously undone command under current identity/value/permission checks. A new committed command clears redo; refresh clears both stacks.

undoAsync

undoAsync: (options: GridBulkOptions) => Promise<boolean>

Cooperatively preflight value history, then replay atomically. Other history kinds and final commit remain synchronous; cancellation retains the entry.

redoAsync

redoAsync: (options: GridBulkOptions) => Promise<boolean>

Cooperatively preflight value redo, then replay atomically. Current identity, values and authority are rechecked before commit.

canUndo

canUndo: () => boolean

Whether a live engine has an undo entry. This is not a guarantee that current policies/identities/values will permit replay.

canRedo

canRedo: () => boolean

Whether a live engine has a redo entry. Replay still checks current policies and conflicts.

Views and persistence

exportState

exportState: () => GridState

Export versioned domain UI state and selection/metadata. Excludes source data, callback policies, transport and history; identity capture can scan source rows.

restoreState

restoreState: (state: unknown) => void

Stage and validate unknown saved state, including current layout/structure/lock/format policies, before committing. Application callbacks/policies are never supplied by saved state.

setView

setView: (next: LocalViewOptions) => void

Set a core-owned local sort/filter view; this scans local source data and is not a server query. Preserve stable source identities; clear projected views before structural commands.

setViewAsync

setViewAsync: (next: LocalViewOptions, options: GridBulkOptions) => Promise<void>

Cooperative local filtering and stable merge sort with the same ordering as setView. Installs the completed projection once; server queries belong to the data source.

view

view: Readonly<LocalViewOptions>

Current immutable local sort/filter criteria. This does not represent a remote query or an arbitrary host projection.

exportConfiguration

exportConfiguration: () => GridConfiguration

Export JSON-safe column order/widths, frozen counts and local view. Excludes data, callbacks, selection and undo history.

Structure and groups

getMergedCells

getMergedCells: () => readonly Readonly<{ startRow: number; endRow: number; startColumn: number; endColumn: number; }>[]

Return merge spans in source row coordinates. Use getMerge for a visible-cell lookup; merged metadata is separate from cell values.

getMerge

getMerge: (row: number, col: number) => Readonly<{ startRow: number; endRow: number; startColumn: number; endColumn: number; }> | null

Find the merge containing a visible cell and return its visible bounds, or null. Source metadata uses getMergedCells.

canMerge

canMerge: (range: SelectionRange) => boolean

Preflight an inclusive visible merge range against bounds, existing merges, projected view, feature flags and layout policies. No mutation occurs.

mergeCells

mergeCells: (range: SelectionRange) => void

Create a permitted rectangular merge without combining or deleting raw values. Validate before changing metadata; participates in layout history.

unmergeCells

unmergeCells: (range: SelectionRange) => void

Remove merges intersecting the requested visible range, subject to current layout policy. Underlying values are retained.

getRowGroups

getRowGroups: () => readonly Readonly<{ id: string; startRow: number; endRow: number; collapsed: boolean; }>[]

Return nested manual row-group metadata in source coordinates. These are not computed group-by aggregations.

groupRows

groupRows: (start: number, end: number) => string

Create a manual source-row group from inclusive source indices, subject to grouping/layout rules. Projected views must be cleared for this structural layout operation.

ungroupRows

ungroupRows: (id: string) => void

Remove a manual group by ID under layout policy. This does not delete source rows.

setGroupCollapsed

setGroupCollapsed: (id: string, collapsed: boolean) => void

Collapse/expand a manual group by ID, changing visible projection while preserving source rows. Current layout policy applies.

insertColumns

insertColumns: (index: number, added: readonly Column[]) => void

Insert definitions before a current column index under structural policy; keys must be unique and the source must support initializing added fields.

deleteColumns

deleteColumns: (indices: readonly number[]) => void

Remove specified current column indices under structural policy and remap related metadata. The source retains its row fields for history/restoration.

insertRows

insertRows: (index: number, rows: readonly DataRow[]) => void

Insert DataRow snapshots before a source row index under structural policy. Requires atomic source splices and valid unique IDs; projected views must be cleared.

deleteRows

deleteRows: (indices: readonly number[]) => void

Delete selected source row indices under structural policy, preserving full shallow row snapshots for undo. Requires source row snapshots/splices.

moveRows

moveRows: (indices: readonly number[], beforeIndex: number) => void

Move source row indices before a source insertion position, preserving their relative order. Requires structural policy/source support and no projected view.

moveColumns

moveColumns: (indices: readonly number[], beforeIndex: number) => void

Move current column indices before an insertion position, preserving their relative order and remapping metadata under structural policy.

Permissions and formatting

getCellPermission

getCellPermission: (row: number, col: number) => CellPermission

Resolve policy capabilities for a visible cell, including current locks and explicit false vetoes. writable does not prove that the source exposes a setter; canEdit checks setter support. Server authorization remains host-owned.

getFormat

getFormat: (row: number, col: number) => Readonly<CellFormat>

Resolve supported formatting for a visible cell using sparse table/row/column/cell metadata. Raw source values are unchanged.

canFormat

canFormat: (targets: readonly CellFormatTarget[]) => boolean

Preflight visible format targets against bounds and formatting policy. Format permission is independent of value writable permission.

format

format: (targets: readonly CellFormatTarget[], patch: CellFormatPatch | null) => void

Apply or remove supported formatting on visible targets after complete validation/policy checks. Participates in formatting history; does not change source values.

isLocked

isLocked: (target: CellLockTarget) => boolean

Check the requested visible table/row/column/cell lock target. Lock metadata is a client capability constraint, not backend authorization.

canManageLocks

canManageLocks: () => boolean

Whether lock management is enabled for the engine. Target validation and command lifecycle still apply when changing locks.

setLocked

setLocked: (target: CellLockTarget, locked: boolean) => void

Set or clear a validated visible lock target when lock changes are allowed. Value commands and history replay resolve current effective locks.

Layout and browser controls

frozenRows

frozenRows: number

Visible frozen leading row count after projection/group collapse, derived from the source frozen prefix.

frozenColumns

frozenColumns: number

Current frozen leading column count. Freeze boundaries must fit the current structure.

getViewport

getViewport: (viewport: ViewportOptions) => Readonly<{ hitTest(x: number, y: number): { row: number; col: number; } | null; cellRect(row: number, col: number): Readonly<{ x: number; y: number; width: number; height: number; clip: Readonly<{ x: number; y: number; width: number; height: number; }>; }>; width: number; height: number; scrollLeft: number; scrollTop: number; frozenWidth: number; frozenHeight: number; regions: readonly ViewportRegion[]; }>

Compute numeric scroll/frozen pane ranges, cell geometry and hit-testing for the visible layout. It does not load remote pages or prove renderer frame rate.

canChangeLayout

canChangeLayout: (request: LayoutRequest) => boolean

Preflight a source-coordinate layout request against feature flags and current layout policy. A permission probe is not a committed command.

getRowSourceIndex

getRowSourceIndex: (row: number) => number

Map a visible row index to its source row index. Use this explicitly at host/source boundaries; do not pass visible indices directly to a projected source.

rows

rows: Readonly<{ size: (i: number) => number; position: (i: number) => number; indexAt: (offset: number) => number; range: (offset: number, extent: number) => { start: number; end: number; }; }>

Read-only visible-row size/position/indexAt/range geometry. Sparse overrides do not allocate metadata for every source row.

columnsLayout

columnsLayout: Readonly<{ size: (index: number) => number; position: (index: number) => number; indexAt: (offset: number) => number; range: (offset: number, extent: number) => { start: number; end: number; }; }>

Read-only current column size/position/indexAt/range geometry. Numeric viewport boundaries are end-exclusive; selection rectangles are inclusive.

canChangeStructure

canChangeStructure: (request: Readonly<StructureRequest>) => boolean

Preflight a source-coordinate structural request against current view, source support, locks and policy. No mutation occurs.

isRowHeightManual

isRowHeightManual: (index: number) => boolean

Whether a visible row has an explicit manual height override. Automatic measurement does not mark a row as manually resized.

measureRowHeight

measureRowHeight: (index: number, size: number) => void

Apply a finite positive measured height to a visible row through layout policy, without adding a manual resize history entry.

canEdit

canEdit: (row: number, col: number) => boolean

Preflight edit capability for a visible cell, including source setter support and effective editable/writable permission. Actual parsing/validation can still reject an edit.

canPaste

canPaste: () => boolean

Whether current selection/source permissions permit paste in principle. Payload shape, bounds, parsing and validation are checked by the actual paste command.

addSelection

addSelection: (row: number, col: number) => boolean

Retain the existing selection and add a visible active cell. Subject to selectable policy and range/fragment limits.

toggleSelection

toggleSelection: (row: number, col: number) => boolean

Toggle a visible cell or its entire merged span. Subtract selected cells from every overlapping rectangle; add unselected cells. Invalid coordinates, denied policies and the 128-source-range limit preserve prior state.

setFrozen

setFrozen: (rows: number, columns: number) => void

Set the requested visible leading row/column counts after validation/layout policy; collapsed groups map the row prefix to source coordinates. Participates in layout history; collapsed groups cannot cross a frozen boundary.

setRowsHidden

setRowsHidden: (indices: readonly number[], hidden: boolean) => void

Hide/show specified visible rows under table lock and canChangeVisibility policy. Retain underlying data, stored size and identity; clear selection/cut and record one undo command.

setColumnsHidden

setColumnsHidden: (indices: readonly number[], hidden: boolean) => void

Hide/show current column indices under table lock and visibility policy; retain fields, widths and metadata. History replay rechecks the policy.

getHiddenRows

getHiddenRows: () => readonly number[]

Return hidden rows mapped into the current projection. Rows excluded by filters or collapsed groups are omitted; saved state retains source hidden indices.

getHiddenColumns

getHiddenColumns: () => readonly number[]

Return sorted hidden column indices in current display order.

isRowHidden

isRowHidden: (index: number) => boolean

Check the hidden flag at a visible row; invalid indices reject. Hidden is separate from filter/group projection.

isColumnHidden

isColumnHidden: (index: number) => boolean

Check the hidden flag at a current column; invalid indices reject. Hiding is layout, not data authorization.

setColumnWidth

setColumnWidth: (index: number, size: number) => void

Set a finite positive current column width under layout policy, with sparse geometry and undo/redo.

setRowHeight

setRowHeight: (index: number, size: number) => void

Set a finite positive visible row height under layout policy, mark it manual and record layout history.

Construction options

Call createGridEngine with GridEngineOptions. Required fields are marked; options are read at construction unless the package guide specifies a runtime setter.

Field Required Type
historyLimits No GridHistoryLimits | undefined
onObserverError No ((error: unknown) => void) | undefined
allowMerging No boolean | undefined
allowRowGrouping No boolean | undefined
canChangeVisibility No ((request: Readonly<{ axis: "row" | "column"; indices: readonly number[]; hidden: boolean; }>) => boolean) | undefined
canChangeLayout No ((request: Readonly<LayoutRequest>) => boolean) | undefined
columns Yes readonly Column[]
view No LocalViewOptions | undefined
canChangeStructure No ((request: Readonly<StructureRequest>) => boolean) | undefined
dataSource Yes DataSource
permissions No Partial<CellPermission> | undefined
resolveCellPermission No CellPermissionResolver | undefined
onEvent No ((event: GridEvent) => void) | undefined
rowHeight No number | undefined
columnWidth No number | undefined
columnWidths No Readonly<Record<string, number>> | undefined
allowLockChanges No boolean | undefined
frozenRows No number | undefined
frozenColumns No number | undefined
onInvalidate No ((change: GridInvalidation) => void) | undefined

Public exports and source interfaces

The root and headless alias expose the same API. Source interfaces use their own row indices, not an engine visible projection. The table lists every public export, including types; declarations and the package guide define their contracts. createAsyncDataSource and createLiveDataSource remain read-only; createPagedRemoteDataSource adds explicit writable paging.

Export Kind Defined in Contract
createGridEngine Runtime engine.ts Create the headless domain instance from application-owned columns/source/policies. See the member contracts and construction options above.
GridEngine Type engine.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
GridEngineOptions Type engine.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
GridInvalidation Type engine.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
GridBulkOptions Type bulk.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
GridBulkProgress Type bulk.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
GridHistoryLimits Type history-budget.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
LocalDataSource Runtime data-source.ts Shallow immutable local row snapshots with unique string/finite-number IDs, synchronous atomic batches and sequential atomic splices. Nested objects remain host-owned.
LocalDataView Runtime data-source.ts A fixed local projection using stable ties and nullish-last sorting. Delegated writes map view indices to underlying source indices; reconstruct the view to reapply criteria.
createAsyncDataSource Runtime async-data-source.ts Read-only synchronous cache with explicit asynchronous page/range loading. The host owns load scheduling, AbortController creation, engine refresh and dataset revision consistency.
createLiveDataSource Runtime live-data-source.ts Read-only bounded local cache of a host stream. Start with a matching snapshot; receive consecutive sequences, coalesce pending cells and flush explicitly. Gaps/disconnect require resync.
createRemoteDataSource Runtime remote-data-source.ts Bounded optimistic JSON snapshot cache with synchronous atomic drafts and explicit async commit/resync. Host server must provide atomic revision checks and mutation ID deduplication. Lost ACK retains an immutable retry; conflict requires explicit resolution.
createPagedRemoteDataSource Runtime paged-remote-data-source.ts Create a bounded writable page cache with stable-ID drafts, server-owned query/revision, dirty-cohort receipts, exact uncertain retry and whole-cache invalidation after accepted writes. Load only required pages; reconcile engine identity/history after cache changes.
PagedRemoteDataSourceOptions Type paged-remote-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
PagedRemoteWriteResult Type paged-remote-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
RemoteDataSourceOptions Type remote-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
RemoteSnapshot Type remote-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
RemoteDelta Type remote-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
RemoteChange Type remote-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
RemoteMutation Type remote-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
RemoteWriteResult Type remote-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
RemoteStatus Type remote-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
LiveUpdate Type live-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
LiveSnapshot Type live-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
AsyncDataSourceOptions Type async-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
PageState Type async-data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
DataSource Type data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
CellUpdate Type data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
RowId Type data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
LocalViewOptions Type data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
DataRow Type data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
RowSplice Type data-source.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
Column Type types.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
CellSelection Type types.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
SelectionRange Type types.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
CellLockTarget Type types.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
CellFormatTarget Type types.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
CellFormat Type types.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
CellFormatPatch Type types.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
NumberFormat Type types.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
PasteOptions Type types.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
CellPermission Type permissions.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
CellPermissionPolicy Type permissions.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
CellPermissionResolver Type permissions.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
GridEvent Type events.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
GridChangeSource Type events.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
ViewportOptions Type panes.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
ViewportLayout Type panes.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
ViewportRegion Type panes.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
ViewportRect Type panes.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
reorderedIndices Runtime structure.ts Validate move indices/insertion position and return a new index order preserving relative order. It does not mutate rows, permissions or history.
StructureRequest Type structure.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
gridClipboardType Runtime clipboard.ts MIME identifier for the internal versioned structured clipboard format. TSV remains the external plain-text fallback.
encodeBlocks Runtime clipboard.ts Validate clipboard block shape/limits and serialize string values plus supported formatting to the versioned wire payload. This is not an arbitrary object codec.
decodeBlocks Runtime clipboard.ts Parse unknown structured clipboard text and validate schema, dimensions, supported formatting and budgets before use. It does not write to a source.
blocksToTsv Runtime clipboard.ts Pack structured string blocks into TSV. Core command wrappers additionally enforce effective copy permissions; direct helper calls have no engine authorization context.
ClipboardBlock Type clipboard.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
RowGroup Type types.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
LayoutRequest Type types.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
restoreGridConfiguration Runtime configuration.ts Validate unknown versioned configuration against application column definitions and row count; return construction options. Saved input cannot supply executable callbacks/policies.
GridConfiguration Type configuration.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.
GridState Type state.ts Compile-time contract; see the exported type definitions below or engine construction/member signatures.

LocalDataSource source members

Use source indices here; engine selection/value APIs use visible indices.

getRowCount: () => number
getRowId: (index: number) => RowId
getValue: (index: number, columnKey: string) => unknown
setValue: (index: number, columnKey: string, value: unknown) => void
setValues: (updates: readonly CellUpdate[]) => void
addColumns: (keys: readonly string[], defaults?: Readonly<Record<string, unknown>>) => void
getRow: (index: number) => DataRow
spliceRows: (splices: readonly RowSplice[]) => void
Source member Behavior
getRowCount Synchronous row count of this source/view. Engine projection is a separate layer.
getRowId Read the ID using this source/view index. Async positional identity belongs to one query; the host must manage dataset revisions.
getValue Read a raw shallow value using this source/view index and key. Missing fields return undefined; async unloaded rows also return undefined, so inspect page state separately.
setValue Remote: stage one optimistic value only while ready. Local atomic single-value replacement, or an optional delegated view setter when the underlying source supports it. No engine permissions/history are applied by direct source writes.
setValues Remote: bounded atomic optimistic JSON-safe staging only while ready. Local atomic batch, or an optional mapped view batch when the underlying source supports it. Direct source changes require engine refresh and remain outside engine history.
addColumns Validate new keys and initialize missing fields atomically while preserving existing fields/defaults. Direct use is outside engine history.
getRow Return a shallow row snapshot including hidden fields; nested values are caller-owned.
spliceRows Apply sequential row splices atomically with unique valid IDs and shallow snapshots. Capture engine IDs before external structure changes.

LocalDataView source members

Use source indices here; engine selection/value APIs use visible indices. This view fixes a projection at construction; rebuild it to reapply criteria.

setValue?: ((index: number, key: string, value: unknown) => void) | undefined
setValues?: ((updates: readonly CellUpdate[]) => void) | undefined
getSourceIndex: (index: number) => number
getRowCount: () => number
getRowId: (index: number) => RowId
getValue: (index: number, columnKey: string) => unknown
Source member Behavior
setValue Remote: stage one optimistic value only while ready. Local atomic single-value replacement, or an optional delegated view setter when the underlying source supports it. No engine permissions/history are applied by direct source writes.
setValues Remote: bounded atomic optimistic JSON-safe staging only while ready. Local atomic batch, or an optional mapped view batch when the underlying source supports it. Direct source changes require engine refresh and remain outside engine history.
getSourceIndex Map a fixed LocalDataView index to the underlying source index. Rebuild the view after changes requiring new sorting/filtering.
getRowCount Synchronous row count of this source/view. Engine projection is a separate layer.
getRowId Read the ID using this source/view index. Async positional identity belongs to one query; the host must manage dataset revisions.
getValue Read a raw shallow value using this source/view index and key. Missing fields return undefined; async unloaded rows also return undefined, so inspect page state separately.

createAsyncDataSource source members

Use source indices here; engine selection/value APIs use visible indices.

pageSize: number
maxConcurrentLoads: number
maxPendingLoads: number
query: Readonly<LocalViewOptions>
setQuery: (next: LocalViewOptions, rowCount?: number) => void
loadPage: (offset: number) => Promise<void>
loadRange: (start: number, end: number) => Promise<void>
getPageState: (offset: number) => PageState | null
subscribe: (listener: (state: PageState) => void) => () => void
takeObserverErrors: () => unknown[]
cancel: () => void
reset: (rowCount?: number) => void
destroy: () => void
getRowCount: () => number
getRow?: ((index: number) => DataRow) | undefined
addColumns?: ((keys: readonly string[], defaults?: Readonly<Record<string, unknown>>) => void) | undefined
spliceRows?: ((splices: readonly RowSplice[]) => void) | undefined
getRowId: (index: number) => RowId
getValue: (index: number, columnKey: string) => unknown
setValue?: ((index: number, columnKey: string, value: unknown) => void) | undefined
setValues?: ((updates: readonly CellUpdate[]) => void) | undefined
Source member Behavior
pageSize Validated positive page length fixed at construction; loadPage offsets must be aligned.
maxConcurrentLoads Maximum active loader calls; a canceled loader must settle so its active slot can be released.
maxPendingLoads Maximum active plus queued loads. Duplicate pages share a promise; admission failures occur before scheduling extra work.
query Immutable captured server criteria. Each load receives the snapshot for its generation; this is not local sorting of cached rows.
setQuery Validate new criteria/count, clear cache/statuses and cancel the previous generation. The host must reconcile the engine and identity after a query change.
loadPage Load one aligned nonnegative offset with deduplication/FIFO concurrency. Validate result dimensions; errors reject, canceled/stale results do not repopulate cache.
loadRange Load inclusive source indices start through end. The requested pages must fit the cache and pending capacity before admission.
getPageState Return state for a page offset or null; error/ready bookkeeping is bounded and eviction can remove it. This is not a per-cell loaded-state API.
subscribe Observe page state changes; returns unsubscribe. Observer exceptions are isolated in a bounded queue; engine refresh is host-owned.
takeObserverErrors Drain up to the last ten isolated page observer errors. This does not retry failed loads.
cancel Invalidate the request generation and signal pending controllers without clearing completed cache/count. Safe cleanup after disposal; loaders must settle/timeout.
reset Async: clear cache/statuses and cancel generation, retaining query with the supplied count. Live: change stream, clear pending changes and mark stale; retain old data until a matching snapshot.
destroy Idempotent disposal of owned cache/queues/observers. Data access and active loads require a live source; cleanup/status probes follow their specific contract. The host owns external transport resources.
getRowCount Synchronous row count of this source/view. Engine projection is a separate layer.
getRow Optional DataSource compatibility slot; not implemented by this read-only factory and undefined at runtime.
addColumns Optional DataSource compatibility slot; not implemented by this read-only factory and undefined at runtime.
spliceRows Optional DataSource compatibility slot; not implemented by this read-only factory and undefined at runtime.
getRowId Read the ID using this source/view index. Async positional identity belongs to one query; the host must manage dataset revisions.
getValue Read a raw shallow value using this source/view index and key. Missing fields return undefined; async unloaded rows also return undefined, so inspect page state separately.
setValue Optional DataSource compatibility slot; not implemented by this read-only factory and undefined at runtime.
setValues Optional DataSource compatibility slot; not implemented by this read-only factory and undefined at runtime.

createLiveDataSource source members

Use source indices here; engine selection/value APIs use visible indices.

streamId: string
sequence: number
stale: boolean
pendingCellCount: number
reset: (next: string) => void
disconnect: () => void
replaceSnapshot: (snapshot: LiveSnapshot) => boolean
receive: (message: LiveUpdate) => boolean
flush: () => number
destroy: () => void
getRowCount: () => number
getRow?: ((index: number) => DataRow) | undefined
addColumns?: ((keys: readonly string[], defaults?: Readonly<Record<string, unknown>>) => void) | undefined
spliceRows?: ((splices: readonly RowSplice[]) => void) | undefined
getRowId: (index: number) => RowId
getValue: (index: number, columnKey: string) => unknown
setValue?: ((index: number, columnKey: string, value: unknown) => void) | undefined
setValues?: ((updates: readonly CellUpdate[]) => void) | undefined
Source member Behavior
streamId Current host stream identifier; messages/snapshots for another stream are ignored.
sequence Latest accepted sequence, including buffered updates not yet flushed. It is not a saved backend revision.
stale Whether a fresh snapshot is required. Read-only retained values can still exist while stale; do not treat them as current.
pendingCellCount Number of unique buffered destination cells after bounded coalescing; not the count of received messages.
reset Async: clear cache/statuses and cancel generation, retaining query with the supplied count. Live: change stream, clear pending changes and mark stale; retain old data until a matching snapshot.
disconnect Remote: abort/invalidate the active generation but retain drafts and uncertain mutation for exact retry. Live: mark the live source stale and discard buffered updates; does not itself reconnect transport or remove retained rows.
replaceSnapshot Validate a matching-stream snapshot with bounded rows, unique IDs and configured fields, then atomically replace the local cache. Reject older/wrong-stream snapshots without installing them.
receive Accept only matching-stream consecutive sequences when not stale; coalesce cells without writing them yet. Gaps, invalid destinations or capacity overflow mark stale and clear pending changes.
flush Apply buffered live changes atomically and return the number of unique updated cells. Returns zero while stale; the host refreshes the engine after flushing.
destroy Idempotent disposal of owned cache/queues/observers. Data access and active loads require a live source; cleanup/status probes follow their specific contract. The host owns external transport resources.
getRowCount Synchronous row count of this source/view. Engine projection is a separate layer.
getRow Optional DataSource compatibility slot; not implemented by this read-only factory and undefined at runtime.
addColumns Optional DataSource compatibility slot; not implemented by this read-only factory and undefined at runtime.
spliceRows Optional DataSource compatibility slot; not implemented by this read-only factory and undefined at runtime.
getRowId Read the ID using this source/view index. Async positional identity belongs to one query; the host must manage dataset revisions.
getValue Read a raw shallow value using this source/view index and key. Missing fields return undefined; async unloaded rows also return undefined, so inspect page state separately.
setValue Optional DataSource compatibility slot; not implemented by this read-only factory and undefined at runtime.
setValues Optional DataSource compatibility slot; not implemented by this read-only factory and undefined at runtime.

createRemoteDataSource source members

Use source indices here; engine selection/value APIs use visible indices.

getRowCount: () => number
getRowId: (row: number) => RowId
getValue: (row: number, key: string) => unknown
setValues: (updates: readonly CellUpdate[]) => void
setValue: (rowIndex: number, columnKey: string, value: unknown) => void
status: RemoteStatus
revision: string | null
pendingCellCount: number
lastError: unknown
getPendingChanges: () => readonly RemoteChange[]
conflict: RemoteSnapshot | null
commit: () => Promise<void>
resync: (discardPending?: boolean) => Promise<void>
reconnect: () => Promise<void>
disconnect: () => void
acceptServer: () => void
subscribe: (listener: (status: RemoteStatus) => void) => () => void
takeObserverErrors: () => unknown[]
destroy: () => void
Source member Behavior
getRowCount Synchronous row count of this source/view. Engine projection is a separate layer.
getRowId Read the ID using this source/view index. Async positional identity belongs to one query; the host must manage dataset revisions.
getValue Read a raw shallow value using this source/view index and key. Missing fields return undefined; async unloaded rows also return undefined, so inspect page state separately.
setValues Remote: bounded atomic optimistic JSON-safe staging only while ready. Local atomic batch, or an optional mapped view batch when the underlying source supports it. Direct source changes require engine refresh and remain outside engine history.
setValue Remote: stage one optimistic value only while ready. Local atomic single-value replacement, or an optional delegated view setter when the underlying source supports it. No engine permissions/history are applied by direct source writes.
status Remote lifecycle: disconnected/loading/ready/committing/conflict/destroyed. Only ready permits drafts; pending uncertain writes block new edits.
revision Remote authoritative snapshot revision; optimistic drafts do not advance it.
pendingCellCount Number of unique buffered destination cells after bounded coalescing; not the count of received messages.
lastError Most recent remote load/transport/validation rejection; a valid installed snapshot clears it.
getPendingChanges Return frozen remote draft entries keyed by stable row ID and column key. Preserve these before explicitly accepting a conflicting server snapshot.
conflict Validated remote server snapshot on conflict, or null. Draft values remain in the cache until explicit adoption.
commit Commit one immutable mutation against expectedRevision. Bounded remote concurrent calls share the promise; paged concurrent calls reject. Lost responses retain the exact request for retry. Acceptance clears drafts; paged acceptance invalidates pages without fetching them. Rejection retains correctable drafts; conflict blocks editing.
resync Load a fresh bounded remote snapshot. Unsent drafts require explicit discardPending=true; an uncertain mutation cannot be discarded. Capture engine identity first and refresh afterward.
reconnect Remote resync without discarding drafts; retry an uncertain commit first. Transport reconnection itself belongs to the host.
disconnect Remote: abort/invalidate the active generation but retain drafts and uncertain mutation for exact retry. Live: mark the live source stale and discard buffered updates; does not itself reconnect transport or remove retained rows.
acceptServer Explicitly adopt a validated conflicting remote snapshot and discard its drafts. Host refreshes engine and may reapply selected saved drafts through validation.
subscribe Observe page state changes; returns unsubscribe. Observer exceptions are isolated in a bounded queue; engine refresh is host-owned.
takeObserverErrors Drain up to the last ten isolated page observer errors. This does not retry failed loads.
destroy Idempotent disposal of owned cache/queues/observers. Data access and active loads require a live source; cleanup/status probes follow their specific contract. The host owns external transport resources.

createPagedRemoteDataSource source members

Use source indices here; engine selection/value APIs use visible indices.

query: Readonly<LocalViewOptions>
revision: string | null
status: RemoteStatus
lastError: unknown
conflict: RemoteSnapshot | null
pendingCellCount: number
getRowId: (index: number) => RowId
getValue: (index: number, key: string) => unknown
setValues: (updates: readonly CellUpdate[]) => void
setValue: (rowIndex: number, columnKey: string, value: unknown) => void
commit: () => Promise<void>
getPendingChanges: () => readonly Readonly<{ rowId: RowId; columnKey: string; previous: unknown; value: unknown; }>[]
setQuery: (next: LocalViewOptions, total?: number) => void
reset: (total?: number) => void
cancel: () => void
discardPending: () => void
acceptServer: () => void
destroy: () => void
pageSize: number
maxConcurrentLoads: number
maxPendingLoads: number
loadPage: (offset: number) => Promise<void>
loadRange: (start: number, end: number) => Promise<void>
getPageState: (offset: number) => PageState | null
subscribe: (listener: (state: PageState) => void) => () => void
takeObserverErrors: () => unknown[]
getRowCount: () => number
getRow?: ((index: number) => DataRow) | undefined
addColumns?: ((keys: readonly string[], defaults?: Readonly<Record<string, unknown>>) => void) | undefined
spliceRows?: ((splices: readonly RowSplice[]) => void) | undefined
Source member Behavior
query Immutable captured server criteria. Each load receives the snapshot for its generation; this is not local sorting of cached rows.
revision Remote authoritative snapshot revision; optimistic drafts do not advance it.
status Remote lifecycle: disconnected/loading/ready/committing/conflict/destroyed. Only ready permits drafts; pending uncertain writes block new edits.
lastError Most recent remote load/transport/validation rejection; a valid installed snapshot clears it.
conflict Validated remote server snapshot on conflict, or null. Draft values remain in the cache until explicit adoption.
pendingCellCount Number of unique buffered destination cells after bounded coalescing; not the count of received messages.
getRowId Read the ID using this source/view index. Async positional identity belongs to one query; the host must manage dataset revisions.
getValue Read a raw shallow value using this source/view index and key. Missing fields return undefined; async unloaded rows also return undefined, so inspect page state separately.
setValues Remote: bounded atomic optimistic JSON-safe staging only while ready. Local atomic batch, or an optional mapped view batch when the underlying source supports it. Direct source changes require engine refresh and remain outside engine history.
setValue Remote: stage one optimistic value only while ready. Local atomic single-value replacement, or an optional delegated view setter when the underlying source supports it. No engine permissions/history are applied by direct source writes.
commit Commit one immutable mutation against expectedRevision. Bounded remote concurrent calls share the promise; paged concurrent calls reject. Lost responses retain the exact request for retry. Acceptance clears drafts; paged acceptance invalidates pages without fetching them. Rejection retains correctable drafts; conflict blocks editing.
getPendingChanges Return frozen remote draft entries keyed by stable row ID and column key. Preserve these before explicitly accepting a conflicting server snapshot.
setQuery Validate new criteria/count, clear cache/statuses and cancel the previous generation. The host must reconcile the engine and identity after a query change.
reset Async: clear cache/statuses and cancel generation, retaining query with the supplied count. Live: change stream, clear pending changes and mark stale; retain old data until a matching snapshot.
cancel Invalidate the request generation and signal pending controllers without clearing completed cache/count. Safe cleanup after disposal; loaders must settle/timeout.
discardPending Paged remote: discard only unsent or rejected drafts and invalidate cached pages. An uncertain or conflicting mutation must be resolved first.
acceptServer Explicitly adopt a validated conflicting remote snapshot and discard its drafts. Host refreshes engine and may reapply selected saved drafts through validation.
destroy Idempotent disposal of owned cache/queues/observers. Data access and active loads require a live source; cleanup/status probes follow their specific contract. The host owns external transport resources.
pageSize Validated positive page length fixed at construction; loadPage offsets must be aligned.
maxConcurrentLoads Maximum active loader calls; a canceled loader must settle so its active slot can be released.
maxPendingLoads Maximum active plus queued loads. Duplicate pages share a promise; admission failures occur before scheduling extra work.
loadPage Load one aligned nonnegative offset with deduplication/FIFO concurrency. Validate result dimensions; errors reject, canceled/stale results do not repopulate cache.
loadRange Load inclusive source indices start through end. The requested pages must fit the cache and pending capacity before admission.
getPageState Return state for a page offset or null; error/ready bookkeeping is bounded and eviction can remove it. This is not a per-cell loaded-state API.
subscribe Observe page state changes; returns unsubscribe. Observer exceptions are isolated in a bounded queue; engine refresh is host-owned.
takeObserverErrors Drain up to the last ten isolated page observer errors. This does not retry failed loads.
getRowCount Synchronous row count of this source/view. Engine projection is a separate layer.
getRow Return a shallow row snapshot including hidden fields; nested values are caller-owned.
addColumns Validate new keys and initialize missing fields atomically while preserving existing fields/defaults. Direct use is outside engine history.
spliceRows Apply sequential row splices atomically with unique valid IDs and shallow snapshots. Capture engine IDs before external structure changes.

Exported type definitions

These declaration excerpts describe compile-time contracts, not executable examples or runtime validators. GridEngine members and GridEngineOptions are catalogued above. Unknown persisted/clipboard input still requires its validation API; never trust a TypeScript assertion as validation.

Type GridInvalidation

export type GridInvalidation =
  | { readonly type: 'cells'; readonly cells: readonly { readonly rowIndex: number; readonly columnKey: string }[] }
  | { readonly type: 'selection'; readonly changed: boolean; readonly rangeChanged: boolean }
  | { readonly type: 'layout' }
  | { readonly type: 'structure'; readonly rowMap: readonly number[]; readonly columnMap: readonly number[] };

Type GridBulkOptions

export interface GridBulkOptions {
  /** Host scheduler, for example a browser task yield. Must eventually settle. */
  readonly yieldControl: () => Promise<void>;
  readonly signal?: { readonly aborted: boolean };
  readonly onProgress?: (progress: GridBulkProgress) => void;
  /** Must change on external data, schema or permission changes during the operation. */
  readonly getRevision?: () => string;
  /** Optional off-thread TSV decoder. Results are validated before paste. */
  readonly tsvDecoder?: {
    decodeTsv(text: string, signal?: { readonly aborted: boolean }): Promise<unknown>;
  };
}

Type GridBulkProgress

export interface GridBulkProgress {
  readonly phase: 'parse' | 'prepare' | 'validate' | 'sort';
  readonly completed: number;
  readonly total: number;
}

Type GridHistoryLimits

export interface GridHistoryLimits {
  readonly maxCommands?: number;
  /** Retained value/format change records, not an estimate of JavaScript heap bytes. */
  readonly maxValueCells?: number;
}

Type PagedRemoteDataSourceOptions

export interface PagedRemoteDataSourceOptions<S> extends Pick<
  AsyncDataSourceOptions<S>,
  'rowCount' | 'pageSize' | 'maxPages' | 'maxConcurrentLoads' | 'maxPendingLoads' | 'query' | 'createAbortController'
> {
  readonly datasetId: string;
  readonly columnKeys: readonly string[];
  readonly maxPendingCells?: number;
  readonly createMutationId: () => string;
  readonly load: (request: {
    readonly offset: number;
    readonly limit: number;
    readonly signal: S;
    readonly query: Readonly<LocalViewOptions>;
    readonly expectedRevision: string | null;
  }) => Promise<RemoteSnapshot & { readonly total: number }>;
  /** Receipts contain only the dirty-row cohort. Every accepted write invalidates the page cache. */
  readonly write: (
    mutation: RemoteMutation,
    signal: S,
    query: Readonly<LocalViewOptions>,
  ) => Promise<PagedRemoteWriteResult>;
}

Type PagedRemoteWriteResult

export type PagedRemoteWriteResult = RemoteWriteResult & { readonly total: number };

Type RemoteDataSourceOptions

export interface RemoteDataSourceOptions<S> {
  readonly datasetId: string;
  readonly columnKeys: readonly string[];
  readonly maxRows?: number;
  readonly maxPendingCells?: number;
  readonly createAbortController: () => { readonly signal: S; abort(): void };
  /** Unique for the lifetime of the server's idempotency records. */
  readonly createMutationId: () => string;
  readonly load: (signal: S) => Promise<RemoteSnapshot>;
  /** Server must check the revision and apply the complete batch atomically, deduplicated by mutationId. */
  readonly write: (mutation: RemoteMutation, signal: S) => Promise<RemoteWriteResult>;
}

Type RemoteSnapshot

export interface RemoteSnapshot {
  readonly datasetId: string;
  readonly revision: string;
  readonly rows: readonly DataRow[];
}

Type RemoteDelta

export interface RemoteDelta {
  readonly datasetId: string;
  readonly baseRevision: string;
  readonly revision: string;
  /** Canonical values for every submitted cell and any server-side effects; row order is unchanged. */
  readonly cells: readonly { readonly rowId: RowId; readonly columnKey: string; readonly value: unknown }[];
}

Type RemoteChange

export interface RemoteChange {
  readonly rowId: RowId;
  readonly columnKey: string;
  readonly previous: unknown;
  readonly value: unknown;
}

Type RemoteMutation

export interface RemoteMutation {
  readonly datasetId: string;
  readonly mutationId: string;
  readonly expectedRevision: string;
  readonly changes: readonly RemoteChange[];
}

Type RemoteWriteResult

export type RemoteWriteResult =
  | { readonly mutationId: string; readonly status: 'accepted' | 'conflict'; readonly snapshot: RemoteSnapshot }
  | { readonly mutationId: string; readonly status: 'accepted'; readonly delta: RemoteDelta }
  | { readonly datasetId: string; readonly mutationId: string; readonly status: 'rejected'; readonly message: string };

Type RemoteStatus

export type RemoteStatus = 'disconnected' | 'loading' | 'ready' | 'committing' | 'conflict' | 'destroyed';

Type LiveUpdate

export interface LiveUpdate {
  readonly streamId: string;
  readonly sequence: number;
  readonly changes: readonly { readonly rowId: RowId; readonly columnKey: string; readonly value: unknown }[];
}

Type LiveSnapshot

export interface LiveSnapshot {
  readonly streamId: string;
  readonly sequence: number;
  readonly rows: readonly DataRow[];
}

Type AsyncDataSourceOptions

export interface AsyncDataSourceOptions<S> {
  readonly rowCount?: number;
  readonly pageSize?: number;
  readonly maxPages?: number;
  readonly maxConcurrentLoads?: number;
  readonly maxPendingLoads?: number;
  readonly query?: LocalViewOptions;
  readonly createAbortController: () => { readonly signal: S; abort(): void };
  readonly load: (request: {
    readonly offset: number;
    readonly limit: number;
    readonly signal: S;
    readonly query: Readonly<LocalViewOptions>;
  }) => Promise<{ readonly rows: readonly Readonly<Record<string, unknown>>[]; readonly total: number }>;
  /** Stable positional identity within one server query; query changes invalidate identity. */
  readonly getRowId?: (index: number, loadedRow?: Readonly<Record<string, unknown>>) => RowId;
}

Type PageState

export interface PageState {
  readonly offset: number;
  readonly status: 'loading' | 'ready' | 'error';
  readonly error?: unknown;
}

Type DataSource

export interface DataSource {
  getRowCount(): number;
  /** Full shallow row snapshot, including fields outside the visible columns. */
  getRow?(index: number): DataRow;
  /** Initialize missing fields atomically; existing hidden column values are retained. */
  addColumns?(keys: readonly string[], defaults?: Readonly<Record<string, unknown>>): void;
  /** Apply sequential splices atomically, preserving unique row IDs. */
  spliceRows?(splices: readonly RowSplice[]): void;
  getRowId(index: number): RowId;
  getValue(index: number, columnKey: string): unknown;
  setValue?(index: number, columnKey: string, value: unknown): void;
  /** Synchronous, atomic: either all writes succeed or none do. */
  setValues?(updates: readonly CellUpdate[]): void;
}

Type CellUpdate

export interface CellUpdate {
  rowIndex: number;
  columnKey: string;
  value: unknown;
}

Type RowId

export type RowId = string | number;

Type LocalViewOptions

export interface LocalViewOptions {
  readonly sort?: { readonly columnKey: string; readonly direction: 'asc' | 'desc' };
  readonly sorts?: readonly { readonly columnKey: string; readonly direction: 'asc' | 'desc' }[];
  readonly filters?: readonly {
    readonly columnKey: string;
    readonly query: string;
    readonly operator?: 'contains' | 'equals' | 'not-empty' | 'empty';
  }[];
}

Type DataRow

export interface DataRow {
  readonly id: RowId;
  readonly values: Readonly<Record<string, unknown>>;
}

Type RowSplice

export interface RowSplice {
  readonly index: number;
  readonly deleteCount: number;
  readonly rows: readonly DataRow[];
}

Type Column

export interface Column {
  defaultValue?: unknown;
  key: string;
  title: string;
  editable?: boolean;
  permissions?: CellPermissionPolicy;
  parse?: (text: string) => unknown;
  validate?: (value: unknown) => string | undefined;
  invalidInput?: 'reject' | 'allow';
}

Type CellSelection

export interface CellSelection {
  rowIndex: number;
  rowId: RowId;
  columnIndex: number;
  columnKey: string;
}

Type SelectionRange

export interface SelectionRange {
  startRow: number;
  endRow: number;
  startColumn: number;
  endColumn: number;
}

Type CellLockTarget

export type CellLockTarget =
  | { readonly scope: 'table' }
  | { readonly scope: 'row'; readonly rowIndex: number }
  | { readonly scope: 'column'; readonly columnIndex: number }
  | { readonly scope: 'cell'; readonly rowIndex: number; readonly columnIndex: number };

Type CellFormatTarget

export type CellFormatTarget = CellLockTarget | { readonly scope: 'range'; readonly range: Readonly<SelectionRange> };

Type CellFormat

export interface CellFormat {
  readonly background?: string;
  readonly textColor?: string;
  readonly contentFormat?: 'plain' | 'html' | 'markdown';
  readonly fontWeight?: 'normal' | 'bold';
  readonly fontStyle?: 'normal' | 'italic';
  readonly numberFormat?: NumberFormat;
}

Type CellFormatPatch

export interface CellFormatPatch {
  readonly background?: string | null;
  readonly textColor?: string | null;
  readonly contentFormat?: 'plain' | 'html' | 'markdown' | null;
  readonly fontWeight?: 'normal' | 'bold' | null;
  readonly fontStyle?: 'normal' | 'italic' | null;
  readonly numberFormat?: NumberFormat | null;
}

Type NumberFormat

export type NumberFormat = 'decimal' | 'integer' | 'percent' | 'currency';

Type PasteOptions

export interface PasteOptions {
  readonly mode?: 'all' | 'values' | 'formats';
  readonly transpose?: boolean;
  readonly skipEmpty?: boolean;
}

Type CellPermission

export interface CellPermission {
  readonly editable: boolean;
  readonly selectable: boolean;
  readonly copyable: boolean;
  readonly pasteable: boolean;
  readonly writable: boolean;
  readonly formatting: boolean;
}

Type CellPermissionPolicy

export type CellPermissionPolicy = Partial<CellPermission>;

Type CellPermissionResolver

export type CellPermissionResolver = (cell: Readonly<CellSelection>) => CellPermissionPolicy | undefined;

Type GridEvent

export type GridEvent =
  | {
      readonly type: 'visibility:change';
      readonly axis: 'row' | 'column';
      readonly indices: readonly number[];
      readonly hidden: boolean;
      readonly source: 'api' | 'undo' | 'redo';
    }
  | {
      readonly type: 'data:refresh';
      readonly previousRowCount: number;
      readonly rowCount: number;
      readonly identitiesReconciled: boolean;
    }
  | { readonly type: 'state:restore' }
  | { readonly type: 'merge:change' | 'group:change'; readonly source: 'api' | 'undo' | 'redo' }
  | {
      readonly type: 'view:change';
      readonly view: Readonly<LocalViewOptions>;
      readonly rowCount: number;
      readonly sourceRowCount: number;
    }
  | {
      readonly type: 'structure:change';
      readonly source: 'api' | 'undo' | 'redo';
      readonly request: Readonly<StructureRequest>;
      readonly rowCount: number;
      readonly columnKeys: readonly string[];
    }
  | {
      readonly type: 'cell:change';
      readonly source: GridChangeSource;
      readonly changes: readonly Readonly<CellUpdate & { rowId: RowId; previous: unknown }>[];
    }
  | {
      readonly type: 'selection:change';
      readonly selection: Readonly<CellSelection> | null;
      readonly range: Readonly<SelectionRange> | null;
      readonly ranges: readonly Readonly<SelectionRange>[];
    }
  | {
      readonly type: 'format:change';
      readonly source: 'api' | 'paste' | 'undo' | 'redo';
      readonly changes: readonly {
        readonly target: Readonly<CellFormatTarget>;
        readonly previous: Readonly<CellFormatPatch> | null;
        readonly value: Readonly<CellFormatPatch> | null;
      }[];
    }
  | { readonly type: 'lock:change'; readonly target: Readonly<CellLockTarget>; readonly locked: boolean }
  | {
      readonly type: 'freeze:change';
      readonly previousRows: number;
      readonly previousColumns: number;
      readonly rows: number;
      readonly columns: number;
    }
  | {
      readonly type: 'column:resize' | 'row:resize';
      readonly index: number;
      readonly previous: number;
      readonly size: number;
    };

Type GridChangeSource

export type GridChangeSource = 'api' | 'edit' | 'paste' | 'undo' | 'redo';

Type ViewportOptions

export interface ViewportOptions {
  width: number;
  height: number;
  scrollLeft: number;
  scrollTop: number;
}

Type ViewportLayout

export type ViewportLayout = ReturnType<typeof createViewport>;

Type ViewportRegion

export interface ViewportRegion {
  readonly clip: ViewportRect;
  readonly rows: Readonly<{ start: number; end: number }>;
  readonly columns: Readonly<{ start: number; end: number }>;
  readonly offsetX: number;
  readonly offsetY: number;
}

Type ViewportRect

export interface ViewportRect {
  readonly x: number;
  readonly y: number;
  readonly width: number;
  readonly height: number;
}

Type StructureRequest

export interface StructureRequest {
  readonly columns?: readonly Column[];
  readonly order?: readonly number[];
  readonly axis: 'row' | 'column';
  readonly kind: 'insert' | 'delete' | 'move';
  readonly indices: readonly number[];
  readonly beforeIndex: number;
  readonly count: number;
}

Type ClipboardBlock

export interface ClipboardBlock {
  readonly row: number;
  readonly column: number;
  readonly values: readonly (readonly string[])[];
  readonly formats?: readonly (readonly CellFormat[])[];
}

Type RowGroup

export interface RowGroup {
  readonly id: string;
  readonly startRow: number;
  readonly endRow: number;
  readonly collapsed: boolean;
}

Type LayoutRequest

export type LayoutRequest =
  | { readonly kind: 'merge' | 'unmerge'; readonly range: Readonly<SelectionRange> }
  | { readonly kind: 'group' | 'ungroup' | 'collapse' | 'expand'; readonly group: Readonly<RowGroup> };

Type GridConfiguration

export interface GridConfiguration {
  readonly version: 1;
  readonly columns: readonly { readonly key: string; readonly width: number }[];
  readonly frozenRows: number;
  readonly frozenColumns: number;
  readonly view: LocalViewOptions;
}

Type GridState

export interface GridState {
  readonly version: 1;
  readonly configuration: GridConfiguration;
  readonly rowIds: readonly RowId[];
  readonly rowHeights: readonly (readonly [number, number])[];
  readonly manualRows: readonly number[];
  readonly hiddenRows?: readonly number[];
  readonly hiddenColumns?: readonly number[];
  readonly ranges: readonly SelectionRange[];
  readonly selection: Readonly<CellSelection> | null;
  readonly anchor: Readonly<CellSelection> | null;
  readonly activeParts?: number;
  readonly displayAnchor?: Readonly<{ row: number; col: number }> | null;
  readonly merges: readonly SelectionRange[];
  readonly groups: readonly RowGroup[];
  readonly locks: readonly CellLockTarget[];
  readonly formats: readonly { readonly target: CellFormatTarget; readonly patch: CellFormatPatch }[];
}
变更内容
  • r1 — Generated source API signatures and construction options.
  • r2 — Complete behavioral contracts for every engine member, all public exports and source interface signatures.
  • r3 — Complete behavioral contracts for every engine member, all public exports and source interface signatures.
  • r4 — Complete behavioral contracts for every engine member, all public exports and source interface signatures.
  • r5 — Complete behavioral contracts for every engine member, all public exports and source interface signatures.
  • r6 — Complete behavioral contracts for every engine member, all public exports and source interface signatures.
  • r7 — Complete behavioral contracts for every engine member, all public exports and source interface signatures.
  • r8 — Complete behavioral contracts for every engine member, all public exports and source interface signatures.
  • r9 — Complete behavioral contracts for every engine member, all public exports and source interface signatures.
  • r10 — Complete behavioral contracts for every engine member, all public exports and source interface signatures.
  • r11 — Complete behavioral contracts for every engine member, all public exports and source interface signatures.
  • r12 — Complete behavioral contracts for every engine member, all public exports and source interface signatures.
  • r13 — Complete behavioral contracts for every engine member, all public exports and source interface signatures.
下载 Markdown
文档版本