@searsuite/sear-domain-matrix
Sparse matrix storage, structural row and column operations, dimensions, and serialization.
Sparse matrix storage
- classColumnShapeDimensionsCSRMatrix
-
class ColumnShapeDimensionsCSRMatrix extends DimensionsCSRMatrixSpecialized subclass of DimensionsCSRMatrix for tracking column widths.
constructor ColumnShapeDimensionsCSRMatrix(...args: [data: { data: number[]; indices: number[]; indptr: number[] }, shape: [number, number]]): ColumnShapeDimensionsCSRMatrixConstructs a DimensionsCSRMatrix instance.
argsSame parameters as CSRMatrix constructor
property name: stringStable matrix name used in diagnostics and serialized metadata.
Inherited members 39
Inherited from DimensionsCSRMatrix.
- ndim
- nnz
- shape
- addColumn
- addItem
- addListener
- addRow
- clone
- cloneCommittedView
- cloneDetached
- cloneForStaging
- deleteColumns
- deleteRows
- dispatch
- dot
- forEach
- forEachStored
- forEachStoredInRange
- forEachStoredInRow
- fromDense
- getCol
- getDefaultValue
- getDimensionLeftBoundaryByIndex
- getDimensionRightBoundaryByIndex
- getDimensionsMap
- getItem
- getLeftBoundaryColIndexByDimension
- getRightBoundaryColIndexByDimension
- getRow
- lockMutations
- multiply
- removeItem
- removeListener
- setDefaultValue
- sum
- swapColumn
- swapRow
- toArray
- transpose
- classCSRMatrix
-
class CSRMatrix<T> extends SparseMatrix<T>A Compressed Sparse Row (CSR) matrix implementation.
constructor CSRMatrix<T>(data?: { data: T[]; indices: number[]; indptr: number[] }, shape?: [number, number]): CSRMatrix<T>Constructs a CSRMatrix instance.
dataThe data for the matrix.
shapeThe shape of the matrix as [numRows, numCols].
property name: stringThe name of the matrix state.
method 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.
targetIndexThe index where the new column should be inserted.
colAn array representing the column to be added. The length of this array must match the number of rows in the matrix.
method 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.
rowThe row index.
colThe column index.
valueThe value to add.
method 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.
targetIndexThe index at which to add the row.
rowThe row to add.
method clone(): thisCreates an independent copy of this value and its mutable data.
method cloneCommittedView(detachExtra?: (value: unknown): unknown): thisDetaches subclass-private slots while sharing already frozen sparse storage.
method cloneDetached(cloneValue: (value: T): T): thisCopies stored values for a detached snapshot without probing empty cells.
method cloneForStaging(cloneValue?: <Value>(value: Value): Value): thisCopies visible sparse state without invoking subclass constructors or clone hooks.
method 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.
targetIndexThe index of the first column to be deleted.
numDeleteColumnsThe number of columns to delete. Defaults to 1.
method 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.
targetIndexThe index at which to start deleting rows.
numDeleteRowsThe number of rows to delete.
method dispatch(operations: MatrixOTOperation<T>[]): CSRMatrix<T>Applies a set of matrix operations to the current matrix.
ReturnsThe updated matrix instance.
operationsAn array of operations to be applied to the matrix.
method forEachStored(callback: (value: T, row: number, col: number): void): voidVisits 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).
method forEachStoredInRange(startRow: number, startColumn: number, endRow: number, endColumn: number, callback: (value: T, row: number, column: number): void): voidVisits stored entries in an inclusive rectangle, skipping empty CSR rows and out-of-range columns.
method forEachStoredInRow(row: number, callback: (value: T, col: number): void): voidVisits the CSR segment for one row in O(stored entries in that row).
method fromDense(denseArray: T | null[][]): CSRMatrix<T>Converts a dense array to a CSRMatrix.
ReturnsThe current instance for chaining.
denseArrayThe dense array to convert.
method getItem(row: number, col: number): T | nullRetrieves an item from the matrix at the specified row and column.
ReturnsThe item at the specified position or null if not present.
rowThe row index.
colThe column index.
method lockMutations(): voidPrevents writes to a committed matrix while leaving clones mutable for transaction staging.
method removeItem(row: number, col: number): CSRMatrix<T> | undefinedRemoves an item from the matrix at the specified row and column.
ReturnsThe current instance for chaining.
rowThe row index.
colThe column index.
method swapColumn(targetIndex: number, sourceIndex: number): CSRMatrix<T>Swaps two columns in the matrix at the specified indices.
ReturnsThe updated matrix instance.
targetIndexThe index of the first column to be swapped.
sourceIndexThe index of the second column to be swapped.
method swapRow(targetIndex: number, sourceIndex: number): CSRMatrix<T>Swaps two rows in the matrix.
ReturnsThe current instance for chaining.
targetIndexThe index of the target row.
sourceIndexThe index of the source row.
method toArray(): T[][]Converts the matrix to a 2D array representation.
ReturnsA 2D array representing the matrix, with each element initialized to
nullif 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 rowsconstructor DimensionsCSRMatrix(...args: [data: { data: number[]; indices: number[]; indptr: number[] }, shape: [number, number]]): DimensionsCSRMatrixConstructs a DimensionsCSRMatrix instance.
argsSame parameters as CSRMatrix constructor
method addColumn(targetIndex: number, column: number | null[]): thisInserts a column while omitting values equal to the configured default dimension.
method addItem(row: number, col: number, value: number): thisStores a non-default dimension override, or removes the sparse entry when restoring the default.
ReturnsThis matrix after the sparse update.
rowMatrix row receiving the dimension value.
colMatrix column receiving the dimension value.
valueRequested dimension size.
method addRow(targetIndex: number, row: number | null[]): thisInserts a row while omitting values equal to the configured default dimension.
method getDimensionLeftBoundaryByIndex(colIndex: number): numberGets 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)colIndexThe column index (0-based)
method getDimensionRightBoundaryByIndex(colIndex: number): numberGets 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)colIndexThe column index (0-based)
method 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
Exampleconst matrix = new DimensionsCSRMatrix(...); const map = matrix.getDimensionsMap(); // [10, 30, 60]method getLeftBoundaryColIndexByDimension(dimension: number): numberFinds 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)dimensionThe cumulative dimension value to search for
method getRightBoundaryColIndexByDimension(dimension: number): numberFinds 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)dimensionThe cumulative dimension value to search for
method setDefaultValue(value: number): voidSets the dimension fallback and removes matching entries so only overrides remain stored.
valueDefault row height or column width returned for absent entries.
Inherited members 31
Inherited from CSRMatrix.
- name
- ndim
- nnz
- shape
- addListener
- clone
- cloneCommittedView
- cloneDetached
- cloneForStaging
- deleteColumns
- deleteRows
- dispatch
- dot
- forEach
- forEachStored
- forEachStoredInRange
- forEachStoredInRow
- fromDense
- getCol
- getDefaultValue
- getItem
- getRow
- lockMutations
- multiply
- removeItem
- removeListener
- sum
- swapColumn
- swapRow
- toArray
- transpose
- classMatrixSerializationError
-
class MatrixSerializationError extends SearErrorError thrown when a persisted sparse matrix payload cannot be decoded.
constructor MatrixSerializationError(code: "SEAR_MATRIX_SERIALIZATION_INVALID_FORMAT", message: string, details?: SearErrorDetails): MatrixSerializationErrorproperty readonly code: "SEAR_MATRIX_SERIALIZATION_INVALID_FORMAT"Stable machine-readable error code.
Inherited members 9
Inherited from SearError.
- classRowShapeDimensionsCSRMatrix
-
class RowShapeDimensionsCSRMatrix extends DimensionsCSRMatrixSpecialized subclass of DimensionsCSRMatrix for tracking row heights.
constructor RowShapeDimensionsCSRMatrix(...args: [data: { data: number[]; indices: number[]; indptr: number[] }, shape: [number, number]]): RowShapeDimensionsCSRMatrixConstructs a DimensionsCSRMatrix instance.
argsSame parameters as CSRMatrix constructor
property name: stringStable matrix name used in diagnostics and serialized metadata.
Inherited members 39
Inherited from DimensionsCSRMatrix.
- ndim
- nnz
- shape
- addColumn
- addItem
- addListener
- addRow
- clone
- cloneCommittedView
- cloneDetached
- cloneForStaging
- deleteColumns
- deleteRows
- dispatch
- dot
- forEach
- forEachStored
- forEachStoredInRange
- forEachStoredInRow
- fromDense
- getCol
- getDefaultValue
- getDimensionLeftBoundaryByIndex
- getDimensionRightBoundaryByIndex
- getDimensionsMap
- getItem
- getLeftBoundaryColIndexByDimension
- getRightBoundaryColIndexByDimension
- getRow
- lockMutations
- multiply
- removeItem
- removeListener
- setDefaultValue
- sum
- swapColumn
- swapRow
- toArray
- transpose
- 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:
- The actual cell data (sheetData)
- Row dimension information (row heights for rendering)
- 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.
Exampleconst state: ISheetState<string> = { sheetData: new CSRMatrix<string>(...), rowSizes: new RowShapeDimensionsCSRMatrix(...), columnSizes: new ColumnShapeDimensionsCSRMatrix(...) };property columnSizes: ColumnShapeDimensionsCSRMatrixMatrix 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
property rowSizes: RowShapeDimensionsCSRMatrixMatrix 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
property 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
- interfaceSerializedSparseMatrix
-
interface SerializedSparseMatrix<TValue>Sparse matrix payload used by package-level serializers.
property readonly defaultValue?: TValueOptional sparse fallback value returned by the runtime matrix for absent entries.
property readonly entries: readonly SerializedSparseMatrixEntry<TValue>[]Stored non-default entries.
property readonly shape: readonly [number, number]Matrix shape as
[rows, columns]. - interfaceSerializedSparseMatrixEntry
-
interface SerializedSparseMatrixEntry<TValue>Sparse matrix entry stored independently from the runtime CSR implementation.
property readonly col: numberZero-based column coordinate.
property readonly row: numberZero-based row coordinate.
property readonly value: TValuePersisted 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): TMatrixDeserializes 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): booleanTests for explicit destination entries not already owned by the source range.
No matching API entries.