← All packages

API reference

@searsuite/sear-domain-matrix

Sparse matrix storage, structural row and column operations, dimensions, and serialization.

17 exportsderived from source

classColumnShapeDimensionsCSRMatrixsource ↗
class ColumnShapeDimensionsCSRMatrix extends DimensionsCSRMatrix

Specialized subclass of DimensionsCSRMatrix for tracking column widths.

constructorconstructor
ColumnShapeDimensionsCSRMatrix(...args: [data: { data: number[]; indices: number[]; indptr: number[] }, shape: [number, number]]): ColumnShapeDimensionsCSRMatrix

Constructs a DimensionsCSRMatrix instance.

args: [data: { data: number[]; indices: number[]; indptr: number[] }, shape: [number, number]]

Same parameters as CSRMatrix constructor

propertyname
name: string

Stable matrix name used in diagnostics and serialized metadata.

Inherited members 39

Inherited from DimensionsCSRMatrix.

classCSRMatrixsource ↗
class CSRMatrix<T> extends SparseMatrix<T>

A Compressed Sparse Row (CSR) matrix implementation.

constructorconstructor
CSRMatrix<T>(data?: { data: T[]; indices: number[]; indptr: number[] }, shape?: [number, number]): CSRMatrix<T>

Constructs a CSRMatrix instance.

data: { data: T[]; indices: number[]; indptr: number[] }

The data for the matrix.

shape: [number, number]

The shape of the matrix as [numRows, numCols].

propertyname
name: string

The name of the matrix state.

methodaddColumn
addColumn(targetIndex: number, col: T | null[]): CSRMatrix<T>

Adds a new column to the matrix at the specified index.

ReturnsThe updated matrix instance.

ThrowsIf the length of the column does not match the number of rows in the matrix.

targetIndex: number

The index where the new column should be inserted.

col: T | null[]

An array representing the column to be added. The length of this array must match the number of rows in the matrix.

methodaddItem
addItem(row: number, col: number, value: T): CSRMatrix<T>

Adds an item to the matrix at the specified row and column.

ReturnsThe current instance for chaining.

row: number

The row index.

col: number

The column index.

value: T

The value to add.

methodaddRow
addRow(targetIndex: number, row: T | null[]): CSRMatrix<T>

Adds a row to the matrix at the specified index.

ReturnsThe current instance for chaining.

ThrowsWill throw an error if the length of the row does not match the number of columns.

targetIndex: number

The index at which to add the row.

row: T | null[]

The row to add.

methodclone
clone(): this

Creates an independent copy of this value and its mutable data.

methodcloneCommittedView
cloneCommittedView(detachExtra?: (value: unknown): unknown): this

Detaches subclass-private slots while sharing already frozen sparse storage.

detachExtra: (value: unknown): unknown
methodcloneDetached
cloneDetached(cloneValue: (value: T): T): this

Copies stored values for a detached snapshot without probing empty cells.

cloneValue: (value: T): T
methodcloneForStaging
cloneForStaging(cloneValue?: <Value>(value: Value): Value): this

Copies visible sparse state without invoking subclass constructors or clone hooks.

cloneValue: <Value>(value: Value): Value
methoddeleteColumns
deleteColumns(targetIndex: number, numDeleteColumns?: number): CSRMatrix<T>

Deletes one or more columns from the matrix starting at the specified index.

ReturnsThe updated matrix instance.

ThrowsIf the range of columns to be deleted exceeds the current number of columns.

targetIndex: number

The index of the first column to be deleted.

numDeleteColumns: number

The number of columns to delete. Defaults to 1.

methoddeleteRows
deleteRows(targetIndex: number, numDeleteRows?: number): CSRMatrix<T>

Deletes rows from the matrix starting at the specified index.

ReturnsThe current instance for chaining.

ThrowsWill throw an error if the number of rows to delete is out of bounds.

targetIndex: number

The index at which to start deleting rows.

numDeleteRows: number

The number of rows to delete.

methoddispatch
dispatch(operations: MatrixOTOperation<T>[]): CSRMatrix<T>

Applies a set of matrix operations to the current matrix.

ReturnsThe updated matrix instance.

operations: MatrixOTOperation<T>[]

An array of operations to be applied to the matrix.

methodforEachStored
forEachStored(callback: (value: T, row: number, col: number): void): void

Visits the entries encoded in CSR storage without probing empty cells.

This is the appropriate traversal for startup indexes and import-time processors. Its complexity is O(rows + number of stored entries), instead of O(rows × columns).

callback: (value: T, row: number, col: number): void
methodforEachStoredInRange
forEachStoredInRange(startRow: number, startColumn: number, endRow: number, endColumn: number, callback: (value: T, row: number, column: number): void): void

Visits stored entries in an inclusive rectangle, skipping empty CSR rows and out-of-range columns.

startRow: number
startColumn: number
endRow: number
endColumn: number
callback: (value: T, row: number, column: number): void
methodforEachStoredInRow
forEachStoredInRow(row: number, callback: (value: T, col: number): void): void

Visits the CSR segment for one row in O(stored entries in that row).

row: number
callback: (value: T, col: number): void
methodfromDense
fromDense(denseArray: T | null[][]): CSRMatrix<T>

Converts a dense array to a CSRMatrix.

ReturnsThe current instance for chaining.

denseArray: T | null[][]

The dense array to convert.

methodgetItem
getItem(row: number, col: number): T | null

Retrieves an item from the matrix at the specified row and column.

ReturnsThe item at the specified position or null if not present.

row: number

The row index.

col: number

The column index.

methodlockMutations
lockMutations(): void

Prevents writes to a committed matrix while leaving clones mutable for transaction staging.

methodremoveItem
removeItem(row: number, col: number): CSRMatrix<T> | undefined

Removes an item from the matrix at the specified row and column.

ReturnsThe current instance for chaining.

row: number

The row index.

col: number

The column index.

methodswapColumn
swapColumn(targetIndex: number, sourceIndex: number): CSRMatrix<T>

Swaps two columns in the matrix at the specified indices.

ReturnsThe updated matrix instance.

targetIndex: number

The index of the first column to be swapped.

sourceIndex: number

The index of the second column to be swapped.

methodswapRow
swapRow(targetIndex: number, sourceIndex: number): CSRMatrix<T>

Swaps two rows in the matrix.

ReturnsThe current instance for chaining.

targetIndex: number

The index of the target row.

sourceIndex: number

The index of the source row.

methodtoArray
toArray(): T[][]

Converts the matrix to a 2D array representation.

ReturnsA 2D array representing the matrix, with each element initialized to null if not set.

Inherited members 14
  • ndim
  • nnz
  • shape
  • addListener
  • dot
  • forEach
  • getCol
  • getDefaultValue
  • getRow
  • multiply
  • removeListener
  • setDefaultValue
  • sum
  • transpose
classDimensionsCSRMatrixsource ↗
class DimensionsCSRMatrix extends CSRMatrix<number>

DimensionsCSRMatrix - Dimension-Aware Sparse Matrix Implementation

Extends CSRMatrix to add dimension tracking capabilities, specifically designed for handling row and column sizing information (e.g., row heights and column widths in a spreadsheet).

Key Features:

  • Caches cumulative dimension values for efficient lookups
  • Provides boundary calculations based on dimension coordinates
  • Binary search for efficient index-to-dimension and dimension-to-index conversions
  • Automatic cache invalidation on matrix modifications

Use Cases:

  • Tracking row heights in a spreadsheet
  • Tracking column widths in a spreadsheet
  • Managing element sizes in responsive layouts
  • Dimension-based collision detection in rendering engines
Example
// Create a matrix to track row heights
const rowHeights = new DimensionsCSRMatrix(
  { data: [30, 25, 40], indices: [0, 0, 0], indptr: [0, 1, 2, 3] },
  [3, 1]
);

// Get cumulative position for efficient rendering
const top = rowHeights.getDimensionLeftBoundaryByIndex(2); // Sum of first 2 rows
constructorconstructor
DimensionsCSRMatrix(...args: [data: { data: number[]; indices: number[]; indptr: number[] }, shape: [number, number]]): DimensionsCSRMatrix

Constructs a DimensionsCSRMatrix instance.

args: [data: { data: number[]; indices: number[]; indptr: number[] }, shape: [number, number]]

Same parameters as CSRMatrix constructor

methodaddColumn
addColumn(targetIndex: number, column: number | null[]): this

Inserts a column while omitting values equal to the configured default dimension.

targetIndex: number
column: number | null[]
methodaddItem
addItem(row: number, col: number, value: number): this

Stores a non-default dimension override, or removes the sparse entry when restoring the default.

ReturnsThis matrix after the sparse update.

row: number

Matrix row receiving the dimension value.

col: number

Matrix column receiving the dimension value.

value: number

Requested dimension size.

methodaddRow
addRow(targetIndex: number, row: number | null[]): this

Inserts a row while omitting values equal to the configured default dimension.

targetIndex: number
row: number | null[]
methodgetDimensionLeftBoundaryByIndex
getDimensionLeftBoundaryByIndex(colIndex: number): number

Gets the left boundary (start position) of a dimension at the specified column index.

For a column at index i, returns the cumulative sum of all dimensions 0..i-1. For column 0, always returns 0 (no preceding dimensions).

Useful for determining where an element starts on a axis.

ReturnsThe left/start boundary position of this column

ThrowsError if colIndex is out of bounds Time Complexity: O(1) after getDimensionsMap() is called once

Example
// If column widths are [100, 150, 200]
const left = matrix.getDimensionLeftBoundaryByIndex(2); // Returns 250 (100 + 150)
colIndex: number

The column index (0-based)

methodgetDimensionRightBoundaryByIndex
getDimensionRightBoundaryByIndex(colIndex: number): number

Gets the right boundary (end position) of a dimension at the specified column index.

For a column at index i, returns the cumulative sum of all dimensions 0..i. This represents the end position of the element.

Useful for determining where an element ends on a axis.

ReturnsThe right/end boundary position of this column

ThrowsError if colIndex is out of bounds Time Complexity: O(1) after getDimensionsMap() is called once

Example
// If column widths are [100, 150, 200]
const right = matrix.getDimensionRightBoundaryByIndex(1); // Returns 250 (100 + 150)
colIndex: number

The column index (0-based)

methodgetDimensionsMap
getDimensionsMap(): number[]

Computes and returns the cumulative dimension map.

The dimensions map stores the cumulative sum of all dimension values up to each column. For example, if dimensions are [10, 20, 30], the map is [10, 30, 60]. This allows O(1) lookups of boundaries without recalculating sums.

Result is cached until the matrix is modified. Cache is automatically invalidated when rows/columns are added, deleted, or modified.

ReturnsArray where element i contains the sum of dimensions 0..i Time Complexity: O(rows * cols) on first call or after modification, O(1) for cached result

Example
const matrix = new DimensionsCSRMatrix(...);
const map = matrix.getDimensionsMap(); // [10, 30, 60]
methodgetLeftBoundaryColIndexByDimension
getLeftBoundaryColIndexByDimension(dimension: number): number

Finds the column index where a given cumulative dimension coordinate falls.

Uses binary search to efficiently locate which column contains the given dimension value. This is the inverse operation of getDimensionLeftBoundaryByIndex.

Useful for: finding which cell/column is at a specific position (e.g., mouse click location).

ReturnsThe column index where this dimension falls

ThrowsError if the dimension value is outside the valid range Time Complexity: O(log cols)

Example
// If column widths are [100, 150, 200] with cumulative [100, 250, 450]
const col = matrix.getLeftBoundaryColIndexByDimension(200); // Returns 1 (in column 1)
dimension: number

The cumulative dimension value to search for

methodgetRightBoundaryColIndexByDimension
getRightBoundaryColIndexByDimension(dimension: number): number

Finds the column index at a given cumulative dimension coordinate using binary search.

Returns the rightmost column index where the cumulative dimension is <= the input value. This method finds the exact column boundary for a given position.

Useful for: precise collision detection, element positioning in grids.

ReturnsThe column index at this dimension coordinate

ThrowsError if the dimension value is outside the valid range Time Complexity: O(log cols)

Example
// If column widths are [100, 150, 200] with cumulative [100, 250, 450]
const col = matrix.getRightBoundaryColIndexByDimension(250); // Returns 1 (column 1 ends at 250)
dimension: number

The cumulative dimension value to search for

methodsetDefaultValue
setDefaultValue(value: number): void

Sets the dimension fallback and removes matching entries so only overrides remain stored.

value: number

Default row height or column width returned for absent entries.

Inherited members 31

Inherited from CSRMatrix.

classMatrixSerializationErrorsource ↗
class MatrixSerializationError extends SearError

Error thrown when a persisted sparse matrix payload cannot be decoded.

constructorconstructor
MatrixSerializationError(code: "SEAR_MATRIX_SERIALIZATION_INVALID_FORMAT", message: string, details?: SearErrorDetails): MatrixSerializationError

Creates a MatrixSerializationError instance.

code: "SEAR_MATRIX_SERIALIZATION_INVALID_FORMAT"
message: string
details: SearErrorDetails
propertycode
readonly code: "SEAR_MATRIX_SERIALIZATION_INVALID_FORMAT"

Stable machine-readable error code.

Inherited members 9

Inherited from SearError.

classRowShapeDimensionsCSRMatrixsource ↗
class RowShapeDimensionsCSRMatrix extends DimensionsCSRMatrix

Specialized subclass of DimensionsCSRMatrix for tracking row heights.

constructorconstructor
RowShapeDimensionsCSRMatrix(...args: [data: { data: number[]; indices: number[]; indptr: number[] }, shape: [number, number]]): RowShapeDimensionsCSRMatrix

Constructs a DimensionsCSRMatrix instance.

args: [data: { data: number[]; indices: number[]; indptr: number[] }, shape: [number, number]]

Same parameters as CSRMatrix constructor

propertyname
name: string

Stable matrix name used in diagnostics and serialized metadata.

Inherited members 39

Inherited from DimensionsCSRMatrix.

interfaceISheetStatesource ↗
interface ISheetState<T>

ISheetState - Interface defining the complete state of a spreadsheet-like data structure

Represents the full state of a sheet/table with both data and layout information. This interface combines three matrices:

  1. The actual cell data (sheetData)
  2. Row dimension information (row heights for rendering)
  3. Column dimension information (column widths for rendering)

Used primarily in spreadsheet applications where you need to manage both cell content and the visual layout (dimensions) of rows and columns.

Example
const state: ISheetState<string> = {
  sheetData: new CSRMatrix<string>(...),
  rowSizes: new RowShapeDimensionsCSRMatrix(...),
  columnSizes: new ColumnShapeDimensionsCSRMatrix(...)
};
propertycolumnSizes
columnSizes: ColumnShapeDimensionsCSRMatrix

Matrix storing column dimension values (typically column widths in pixels). Single row matrix with numCols entries, one width per column. Use getDimensionLeftBoundaryByIndex/getDimensionRightBoundaryByIndex for layout calculations.

Example: ColumnShapeDimensionsCSRMatrix with values [100, 150, 200] means

  • Column 0 has width 100, positioned at x: 0-100
  • Column 1 has width 150, positioned at x: 100-250
  • Column 2 has width 200, positioned at x: 250-450
propertyrowSizes
rowSizes: RowShapeDimensionsCSRMatrix

Matrix storing row dimension values (typically row heights in pixels). Single column matrix with numRows entries, one height per row. Use getDimensionLeftBoundaryByIndex/getDimensionRightBoundaryByIndex for layout calculations.

Example: RowShapeDimensionsCSRMatrix with values [30, 25, 40] means

  • Row 0 has height 30, positioned at y: 0-30
  • Row 1 has height 25, positioned at y: 30-55
  • Row 2 has height 40, positioned at y: 55-95
propertysheetData
sheetData: CSRMatrix<T>

The main data matrix containing all cell values in the sheet. Uses CSR format for efficient storage of sparse data. Access: sheetData.getItem(row, col) to get a specific cell value

interfaceMatrixMoveRangesource ↗
interface MatrixMoveRange

Inclusive bounds used by matrix range movement.

propertyend
readonly end: readonly [number, number]
propertystart
readonly start: readonly [number, number]
interfaceSerializedSparseMatrixsource ↗
interface SerializedSparseMatrix<TValue>

Sparse matrix payload used by package-level serializers.

propertydefaultValue
readonly defaultValue?: TValue

Optional sparse fallback value returned by the runtime matrix for absent entries.

propertyentries
readonly entries: readonly SerializedSparseMatrixEntry<TValue>[]

Stored non-default entries.

propertyshape
readonly shape: readonly [number, number]

Matrix shape as [rows, columns].

interfaceSerializedSparseMatrixEntrysource ↗
interface SerializedSparseMatrixEntry<TValue>

Sparse matrix entry stored independently from the runtime CSR implementation.

propertycol
readonly col: number

Zero-based column coordinate.

propertyrow
readonly row: number

Zero-based row coordinate.

propertyvalue
readonly value: TValue

Persisted value at the coordinate.

typeMatrixSerializationErrorCodesource ↗
type MatrixSerializationErrorCode = typeof MatrixSerializationErrorCode[keyof typeof MatrixSerializationErrorCode]

Machine-readable matrix serialization error code type.

variableMatrixSerializationErrorCodesource ↗
MatrixSerializationErrorCode: { invalidFormat: "SEAR_MATRIX_SERIALIZATION_INVALID_FORMAT" }

Stable machine-readable error codes owned by matrix serialization helpers.

functioncreateMatrixRangeMoveOperationssource ↗
createMatrixRangeMoveOperations<T>(matrix: CSRMatrix<T>, source: MatrixMoveRange, destination: MatrixMoveRange, mapValue?: (value: NonNullable<T>, row: number, column: number): T): UpdateCellOTOperation<T | null>[]

Plans final per-coordinate values from the original matrix, including overlapping ranges.

matrix: CSRMatrix<T>
source: MatrixMoveRange
destination: MatrixMoveRange
mapValue: (value: NonNullable<T>, row: number, column: number): T
functioncreateMatrixRangeReorderOperationssource ↗
createMatrixRangeReorderOperations<T>(matrix: CSRMatrix<T>, range: { end: readonly [number, number]; start: readonly [number, number] }, destinationOf: (row: number): number): UpdateCellOTOperation<T | null>[]

Reorders only stored cells and clears vacated coordinates from the original snapshot.

matrix: CSRMatrix<T>
range: { end: readonly [number, number]; start: readonly [number, number] }
destinationOf: (row: number): number
functiondeserializeSparseMatrixsource ↗
deserializeSparseMatrix<TValue, TMatrix>(payload: unknown, MatrixClass: SparseMatrixFactory<TMatrix, TValue>, path: string): TMatrix

Deserializes a generic sparse matrix payload into the requested runtime matrix class.

payload: unknown
MatrixClass: SparseMatrixFactory<TMatrix, TValue>
path: string
functionhasMatrixRangeMoveConflictsource ↗
hasMatrixRangeMoveConflict<T>(matrix: CSRMatrix<T>, source: MatrixMoveRange, destination: MatrixMoveRange): boolean

Tests for explicit destination entries not already owned by the source range.

matrix: CSRMatrix<T>
source: MatrixMoveRange
destination: MatrixMoveRange
functionserializeSparseMatrixsource ↗
serializeSparseMatrix<TValue>(matrix: RuntimeSparseMatrix<TValue>): SerializedSparseMatrix<TValue>

Serializes a sparse runtime matrix without depending on CSR internals.

matrix: RuntimeSparseMatrix<TValue>
variableMatrixSerializationErrorCodeValuesource ↗
MatrixSerializationErrorCodeValue: { invalidFormat: "SEAR_MATRIX_SERIALIZATION_INVALID_FORMAT" }

Stable machine-readable error codes owned by matrix serialization helpers.