← All packages

@searsuite/sear-domain-matrix

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

Sparse matrix storage

classCSRMatrix
class CSRMatrix<T> extends SparseMatrix<T>

A Compressed Sparse Row (CSR) matrix implementation.

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

Constructs a CSRMatrix instance.

data

The data for the matrix.

shape

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

propertyname: string

The name of the matrix state.

methodaddColumn(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

The index where the new column should be inserted.

col

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

methodaddItem(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

The row index.

col

The column index.

value

The value to add.

methodaddRow(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

The index at which to add the row.

row

The row to add.

methodclone(): this

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

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

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

methodcloneDetached(cloneValue: (value: T): T): this

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

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

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

methoddeleteColumns(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

The index of the first column to be deleted.

numDeleteColumns

The number of columns to delete. Defaults to 1.

methoddeleteRows(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

The index at which to start deleting rows.

numDeleteRows

The number of rows to delete.

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

Applies a set of matrix operations to the current matrix.

ReturnsThe updated matrix instance.

operations

An array of operations to be applied to the matrix.

methodforEachStored(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).

methodforEachStoredInRange(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.

methodforEachStoredInRow(row: number, callback: (value: T, col: number): void): void

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

methodfromDense(denseArray: T | null[][]): CSRMatrix<T>

Converts a dense array to a CSRMatrix.

ReturnsThe current instance for chaining.

denseArray

The dense array to convert.

methodgetItem(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

The row index.

col

The column index.

methodlockMutations(): void

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

methodremoveItem(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

The row index.

col

The column index.

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

Swaps two columns in the matrix at the specified indices.

ReturnsThe updated matrix instance.

targetIndex

The index of the first column to be swapped.

sourceIndex

The index of the second column to be swapped.

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

Swaps two rows in the matrix.

ReturnsThe current instance for chaining.

targetIndex

The index of the target row.

sourceIndex

The index of the source row.

methodtoArray(): 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
classDimensionsCSRMatrix
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
constructorDimensionsCSRMatrix(...args: [data: { data: number[]; indices: number[]; indptr: number[] }, shape: [number, number]]): DimensionsCSRMatrix

Constructs a DimensionsCSRMatrix instance.

args

Same parameters as CSRMatrix constructor

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

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

methodaddItem(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

Matrix row receiving the dimension value.

col

Matrix column receiving the dimension value.

value

Requested dimension size.

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

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

methodgetDimensionLeftBoundaryByIndex(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

The column index (0-based)

methodgetDimensionRightBoundaryByIndex(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

The column index (0-based)

methodgetDimensionsMap(): 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(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

The cumulative dimension value to search for

methodgetRightBoundaryColIndexByDimension(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

The cumulative dimension value to search for

methodsetDefaultValue(value: number): void

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

value

Default row height or column width returned for absent entries.

Inherited members 31

Inherited from CSRMatrix.

classMatrixSerializationError
class MatrixSerializationError extends SearError

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

Inherited members 9

Inherited from SearError.

interfaceISheetState
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: 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: 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: 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

interfaceSerializedSparseMatrix
interface SerializedSparseMatrix<TValue>

Sparse matrix payload used by package-level serializers.

propertyreadonly defaultValue?: TValue

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

propertyreadonly entries: readonly SerializedSparseMatrixEntry<TValue>[]

Stored non-default entries.

propertyreadonly shape: readonly [number, number]

Matrix shape as [rows, columns].

interfaceSerializedSparseMatrixEntry
interface SerializedSparseMatrixEntry<TValue>

Sparse matrix entry stored independently from the runtime CSR implementation.

propertyreadonly col: number

Zero-based column coordinate.

propertyreadonly row: number

Zero-based row coordinate.

propertyreadonly value: TValue

Persisted value at the coordinate.

typeMatrixSerializationErrorCode
type MatrixSerializationErrorCode = typeof MatrixSerializationErrorCode[keyof typeof MatrixSerializationErrorCode] MatrixSerializationErrorCode: { invalidFormat: "SEAR_MATRIX_SERIALIZATION_INVALID_FORMAT" }

Machine-readable matrix serialization error code type.

functiondeserializeSparseMatrix
deserializeSparseMatrix<TValue, TMatrix>(payload: unknown, MatrixClass: SparseMatrixFactory<TMatrix, TValue>, path: string): TMatrix

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

functionserializeSparseMatrix
serializeSparseMatrix<TValue>(matrix: RuntimeSparseMatrix<TValue>): SerializedSparseMatrix<TValue>

Serializes a sparse runtime matrix without depending on CSR internals.

variableMatrixSerializationErrorCodeValue
MatrixSerializationErrorCodeValue: { invalidFormat: "SEAR_MATRIX_SERIALIZATION_INVALID_FORMAT" }

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

Move and reorder ranges

interfaceMatrixMoveRange

Inclusive bounds used by matrix range movement.

functioncreateMatrixRangeMoveOperations
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.

functioncreateMatrixRangeReorderOperations
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.

functionhasMatrixRangeMoveConflict
hasMatrixRangeMoveConflict<T>(matrix: CSRMatrix<T>, source: MatrixMoveRange, destination: MatrixMoveRange): boolean

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