Modules and their relationships
SearSuite separates portable contracts, editor composition, optional features, and host integration across these package families:
sear-foundation-*defines dependency injection, platform, geometry, error, and shared utility contracts.sear-domain-*defines document data, sparse matrices, operations, and protocols independently of a host interface.sear-render-*defines scene, input, and drawing contracts for visual editors.sear-assembly-*constructs editor runtimes and coordinates plugins, commands, and lifecycle.sear-plugin-*contributes optional state, commands, and extension points.- Host application selects an assembly and plugins, then supplies UI, platform adapters, and transport.
Design principles
Document state has explicit owners. Assemblies connect selected plugins and host adapters through contracts, while the core editor remains independent of individual optional features.
One mutation path
A typed command is a request to change editor state with a defined input contract. Each feature owns its command
definition, which gives the command a stable identifier and specifies the types of its input and result. Application
code and input handlers run these commands through editor.commands.run(...).
For example, to select cell D3 (zero-based coordinates [2, 3]) and then read the selection:
import { GetSelection, SelectRangeCommand } from '@searsuite/sear-plugin-selection';
editor.commands.run(SelectRangeCommand, { anchor: [2, 3], focus: [2, 3] });
const selection = editor.queries.run(GetSelection, undefined);SelectRangeCommand requires an anchor and a focus. SheetSelectionPlugin handles the command and prepares the
selection change. The Sheet kernel commits the prepared operations together; rendering and observations then receive
the committed result. GetSelection reads the current selection through a separate query.
One owner per state
Every independently stateful plugin defines its state and the operations that change it. The runtime coordinates commits across owners without requiring a shared schema for all plugin state. The same ownership contract applies to built-in and third-party plugins.
Adapt through contracts
SearSuite is designed for cross-platform implementations by separating editor behavior from platform-specific services. In the current TypeScript implementation, reusable packages depend on platform-neutral interfaces, and assemblies connect concrete host adapters when an editor is created. The visual editor currently runs in Web browsers, while the headless assembly runs on Node.js. A cross-platform Rust implementation is under development and will require adapters for each target platform.
Queries, observations, and services
The editor facade separates current-state reads, subscriptions, and service lookup. These contracts prevent hosts and plugins from depending on another owner's storage, event source, or service construction:
- Queries read the editor's current state synchronously without changing it. After selecting D3,
editor.queries.run(GetSelection, undefined)returns a snapshot of the selected range. If the selection later moves to E4, that earlier result still describes D3; run the query again to get the new selection. Some queries return a read-only reader instead of a snapshot. For example,ReadSheetCellFormatQueryreturns a reader whosegetItem(2, 3)method reads D3's current cell format each time it is called. Queries do not notify callers when state changes; use observations for updates. - Observations let application code receive changes without repeatedly querying the editor. Each observation
defines the type of value its listener receives. For example, when subscribing to
SheetZoomObservation, the listener receives anumberrepresenting the zoom level. Because this is a state observation, it receives the current zoom level immediately and then receives later changes. An event observation, such asDataValidationWarningObservation, delivers only warnings emitted after subscription; it has no current value to send immediately.subscribe()returns a function that stops the subscription. State observations also providegetSnapshot()to read the current value without subscribing. - Services provide access to editor-local services and extension values through typed tokens. Optional services
can be shared without extending the editor facade or exposing its DI container. The facade provides a read-only lookup:
getreturnsundefinedfor an absent capability, whilerequirethrows. Returned values follow their own contracts and may expose operations.
await editor.commands.run(commandDefinition, commandInput);
const result = editor.queries.run(queryDefinition, queryInput);
const dispose = editor.observations.subscribe(observationDefinition, listener);
const service = editor.services.get(serviceDefinition);
Foundation
Foundation packages provide small, reusable contracts and values shared by domain, rendering, assembly, and plugins. They do not depend on a particular editor or host platform.
sear-foundation-di gives each editor its own dependency container. For example, when two spreadsheets are open side
by side, each registers its own RenderContext (the drawing service). Rendering code resolves the instance belonging
to its editor.
sear-foundation-platform defines the Platform interface for operations that depend on the host environment. For
example, when scrolling requires another render frame, the editor calls platform.requestAnimationFrame(...).
The Browser package uses the browser's animation frame API, while the Server package's NodePlatform uses a timer.
sear-foundation-rect defines points and rectangles in grid coordinates. For example, new Rect([[2, 3], [4, 4]])
describes D3:E5 using zero-based [row, column] coordinates. Selection and document operations can use this region
without depending on how the grid is drawn.
Other foundation packages provide A1-style range parsing, observation contracts, error types, and shared utilities. Assemblies connect the required contracts to concrete implementations when creating an editor.
Domain
sear-domain-* defines structured document data, sparse matrices, operations, and protocols. These packages specify
state representations and change semantics independently of rendering, host adapters, and optional features.
For example, this standalone Domain example changes D3 from 10 to 20, then reverses the change:
const cells = new CSRMatrix<number>(
undefined, // Use the default empty sparse storage.
[10, 10], // Set the matrix size to 10 rows and 10 columns.
);
cells.addItem(2, 3, 10); // D3 initially contains 10.
const operation = {
p: [2, 3],
uc: { prev: 10, value: 20 },
};
MatrixOT.apply(cells, [operation]);
cells.getItem(2, 3); // 20
MatrixOT.apply(cells, MatrixOT.invert([operation]));
cells.getItem(2, 3); // 10The matrix stores D3's value, while the operation records its position and the values before and after the change. This example describes data and change semantics without choosing a rendering backend or host platform.
In a running editor, application code issues a command; the editor applies the corresponding Domain operation within a transaction.
State has one owner
Independently evolving plugins retain separate state contracts. Changes to one plugin's schema or transactions do not require corresponding changes to unrelated plugins. A shared schema for all plugin state would couple those otherwise independent changes.
A state-owning plugin registers its state and mutation commands. It may also contribute field projections, queries,
observations, visual readers, export codecs, or OT definitions. DataEngine manages registered data and projections;
collaboration and persistence require explicit owner contributions.
State and field projection
For example, SheetCellMergePlugin stores each merged range in its own sparse matrix. Only the range's top-left cell
stores its end-row and end-column coordinates. The plugin publishes this matrix as a named DataEngine field.
export interface SheetCellMerge {
readonly endRow: number;
readonly endColumn: number;
}
registerState() {
return {
key: this.key,
state: this.getState(),
dataEngine: {
dataView: [{
viewKey: SheetDataFieldNamespace,
fieldKey: SheetCellMergeFieldKey,
select: (state: SheetCellMergePluginState) =>
state.cellMerges,
}],
},
};
}Commands and query
MergeCellsCommand and UnmergeCellsCommand change the plugin's matrix through transactions. Before merging,
AnalyzeMergeCellsQuery reports which existing cell contents would be retained or discarded.
export const MergeCellsCommand =
defineSheetCommand<SheetMergeInput>('range.mergeCells');
export const UnmergeCellsCommand =
defineSheetCommand<SheetRangeInput>('range.unmergeCells');
export const AnalyzeMergeCellsQuery = defineSheetQuery<
SheetRangeInput,
SheetMergeAnalysis | null
>('range.analyzeMergeCells');
commands.register(MergeCellsCommand, (input) =>
createSheetCellMergeCommand(
MergeCellsCommand.id, 'merge', input, dataSource,
),
);
queries.register(AnalyzeMergeCellsQuery, (input) =>
analyzeMergeCells(input, dataSource),
);Rendering and observations
SheetCellMergeRender reads the published merge field to determine each merged region's bounds. It obtains the
region's visual properties from the shared visual-reader registry. SheetCellMergePlugin does not register its own
visual reader or observation; the contributions listed above are optional.
const merges = readSheetCellMerges(dataEngine);
merges.forEachStored((value, row, column) => {
if (value === null) return;
const visual = this.cellVisualReaders.readVisual({
rowIndex: row,
columnIndex: column,
});
});Persistence
The plugin's document-state codec captures, serializes, and restores its merge matrix. Publishing the matrix through
DataEngine alone would not make it part of exported document state.
static readonly documentState = {
key: 'sheet.cellMerges',
capture: (state: SheetCellMergePluginState) => ({
cellMerges: state.cellMerges.clone(),
}),
codec: {
key: 'sheet.cellMerges',
serialize: (state: SheetCellMergePluginState) =>
serializeSparseMatrix(state.cellMerges),
deserialize: (payload: unknown, path: string) => ({
cellMerges: deserializeSparseMatrix<
SheetCellMerge | null,
CellMergeMatrix
>(payload, CellMergeMatrix, path),
}),
},
};Collaboration and OT
The plugin separately declares the OT definition for its transactions and marks them as collaborative. Its
apply() method applies merge operations to its matrix and adjusts merged ranges when rows or columns change.
readonly transactionOT = {
ownerId: 'sheet.cellMerge',
definition: MatrixTransactionOT,
relations: [MatrixTransactionOTRelation],
collaborative: true,
};Runtime data falls into four categories:
Document state contains editor or Workbook content eligible for export.
SheetDocumentStateincludes cell data and plugin-owned fields such as merged ranges. These are two of its fields:interface SheetDocumentState { sheetData: SheetMatrix; cellMerges: CellMergeMatrix; }Session state contains contributor-keyed local values retained across editor remounts.
A session snapshot can retain a Sheet's viewport position and zoom while switching between Sheets. These values are not exported as document content:
const sessionState: SheetSessionState = { 'sheet.viewport': { x: 240, y: 120 }, 'sheet.zoom': 1.25, };Derived state contains computed values, indexes, layout caches, and render projections.
SheetCellFillPluginstores a cell's fill color in document state. Its visual reader produces thefillproperty that the renderer needs; that render property is read from the stored value rather than saved separately:const plugin = this; registry.register({ id: 'sheet.cell-fill', properties: ['fill'], read({ rowIndex, columnIndex }) { const fill = plugin.getState().cellFills.getItem(rowIndex, columnIndex); return fill == null ? {} : { fill }; }, });Host state contains transport, credentials, dialogs, application UI, and product policy.
The application owns these concerns and supplies concrete adapters when it creates the editor:
adapters: { ...WebSheetAdapterDefaults, collabTransport: WebSocketTransport, toolbar: SearWebToolbar, }
Sparse storage represents defaults by absence. A missing alignment or row size uses the current configuration; rendering that default does not create a persisted entry.
The Sheet model
The base Sheet matrix stores cell content. Other plugins own independent state, including dimensions, formatting, merged ranges, formulas, and selection. An assembly composes the selected owners in one editor-local runtime. Structural commands coordinate their typed operations while ownership remains with each plugin.
CellTypeCatalog associates each persisted cell type with its behavior, including commit strategies, display text,
render registrations, and clipboard codecs. The following excerpt from BooleanCellTypeDefinition shows how Boolean
input is committed, displayed, and rendered:
class BooleanCellTypeDefinition extends CellTypeDefinition {
readonly type = CellType.Boolean;
override createCommitStrategies() {
return [new BooleanCellCommitStrategy()];
}
override createDisplayTextProvider() {
return {
cellType: this.type,
getDisplayText: (cell) =>
typeof cell.value === 'boolean'
? (cell.value ? 'TRUE' : 'FALSE')
: '',
};
}
override createRenderer() {
return defineCellRenderer(this.type, BooleanCell);
}
}
catalog.register(new BooleanCellTypeDefinition());Registering the definition installs its contributions into the corresponding registries. Provider registries expose formula source, calculated values, images, and links as separate projections.
SheetCellVisualReaderRegistry combines visual properties supplied by feature owners for a particular cell. Each
reader declares the properties it provides; conflicting base-property registrations are rejected.
For example, the fill plugin reads its stored color and contributes fill:
const plugin = this;
registry.register({
id: 'sheet.cell-fill',
properties: ['fill'],
read({ rowIndex, columnIndex }) {
const fill = plugin.getState().cellFills.getItem(rowIndex, columnIndex);
return fill == null ? {} : { fill };
},
});Grid and merged-cell renderers call readVisual() to receive fill together with properties supplied by other
plugins, such as alignment:
const visual = cellVisualReaders.readVisual({
rowIndex: row,
columnIndex: column,
});
const properties = visual.properties;Portable operations and protocols
Matrix OT and Rect OT describe changes independently of a view. The collaboration domain manages revisions, pending operations, acknowledgements, catch-up, ordering, and rebasing. Unknown operation families are rejected explicitly.
For example, the cell-fill command creates a Matrix OT operation with both the new and previous value. The previous value lets the same operation family reverse the change:
const operation = createUpdateCellOTOperation([1, 1], '#00a870', null);
const inverse = MatrixOT.invert([operation]);
// Applying inverse restores the previous (empty) fill at B2.
Render
sear-render-* defines scene, drawing, input, and viewport contracts for visual editors. Host adapters implement
platform-specific painting and event handling against those contracts.
RenderContext exposes immediate drawing operations using platform-neutral values. Each visual host implements this
interface with its own rendering backend. Retained scene nodes, cell render registries, dirty-region strategies, hit
testing, cursor policy, input routing, and scrolling are separate concerns with their own contracts.
For example, a render strategy uses the same RenderContext calls regardless of the host's drawing backend:
context.setFillStyle('#00a870');
context.beginPath();
context.rect(x, y, width, height);
context.fill();TextShaper returns glyph, cluster, caret-stop, and advance data using UTF-16 offsets. Native text-system values
remain inside their adapters. Each editor composition root registers one text shaper.
const shaped = textShaper.shape({ text: 'Hello', font: '14px sans-serif' });
const width = shaped.width;
const caretPositions = shaped.caretStops;Platform abstracts timers, event registration, resize observation, host-view offsets, identifiers, and warnings.
Reusable render packages depend on that contract rather than host globals, allowing different hosts to use the same
transaction and plugin layers.
For example, the scroll controller schedules its next frame with platform.requestAnimationFrame() rather than
calling a host-specific timer directly.
this.returnFrame = this.platform.requestAnimationFrame(this.runReturnFrame.bind(this));
Assembly
sear-assembly-* composes Sheet and Workbook runtimes from document state, selected plugins, and host adapters.
Each assembly owns command dispatch, service wiring, and editor lifecycle. Plugin-owned state remains with its
contributor inside the isolated editor runtime.
Editor facades
createSheetEditor() assembles a single Sheet from document state, selected plugins, a viewport session, and
rendering and input adapters. Its facade exposes commands, queries, observations, and runtime services.
createSheetKernelEditor() from sear-assembly-sheet-kernel composes the same business contracts without a scene
or native input adapters. The Headless assembly uses that independent runtime directly. Visual assembly adds
view extensions and subscribes to committed state; local painting does not create a document transaction.
createWorkbookEditor() owns Workbook structure and mounts a Sheet editor for the active Sheet. Its facade exposes
commands, observations, and services. Structural reads use document; access to the mounted Sheet uses
sheets. Each editor facade provides destroy() for runtime teardown.
import {
createSheetEditor, type SheetEditorAdapters,
} from './index';
import { createEmptySheetDocumentState } from '@searsuite/sear-assembly-sheet-state';
import { SelectRangeCommand } from '@searsuite/sear-plugin-selection';
function openSheet(adapters: SheetEditorAdapters) {
const editor = createSheetEditor({ adapters, sheetState: createEmptySheetDocumentState(20, 10) });
editor.commands.run(SelectRangeCommand, { anchor: [0, 0], focus: [0, 0] });
return editor;
}The host retains the returned editor until its view is unmounted, then calls destroy(). The
Canvas demo in the sibling searsuite-website/source/demo/canvas.ts repository
provides a complete Web adapter configuration.
Workbook composition
WorkbookDocumentState stores stable Sheet identities, names, order, visibility, and per-Sheet document state.
WorkbookSessionState stores the active Sheet identity, detached editor sessions, and local plugin values. Internal
references use stable sheetId values; display names can change independently.
Only the active Sheet editor remains mounted after a switch. The Workbook first captures the current Sheet's document
and local session state. It then creates the destination Sheet editor from its saved state and destroys the previous
editor after the replacement succeeds. Returning to a Sheet restores its captured session, including viewport and
selection, without adding those local values to WorkbookDocumentState.
For example, a host switches Sheets by stable identity and then reads the newly mounted Sheet editor:
workbook.commands.run(ActivateWorkbookSheetCommand, { sheetId: 'sheet-2' });
const activeSheet = workbook.sheets.getActiveEditor();Workbook and Sheet plugins are configured separately. Workbook-owned services, including the formula-function
registry and Sheet-keyed collaboration channels, survive Sheet remounts. Structural operations use staged Workbook
transactions and history separate from content edits in the mounted Sheet.
A Workbook rename, for example, runs through workbook.commands, while a fill change runs through the active Sheet's
commands:
workbook.commands.run(RenameWorkbookSheetCommand, { sheetId: 'sheet-2', name: 'Results' });
activeSheet.commands.run(SetRangeCellFillCommand, {
anchor: [0, 0], focus: [0, 0], fill: '#00a870',
});
Plugins
Plugins carry editor features: each feature owns its state and behavior and contributes commands or other extension
points through a plugin. sear-plugin-* packages provide these contributions, and built-in and third-party plugins
participate in the same lifecycle and registration contracts. For example, SheetCellFillPlugin owns fill colors,
the command that changes them, and the visual reader that exposes them to rendering.
Registration and ownership
Registration follows explicit lifecycle phases. Plugins may contribute state, commands, queries, observations, runtime services, session adapters, visual readers, and document-state codecs. The assembly orders these contributions and releases acquired resources in reverse order on failure or teardown.
State registration establishes ownership, and commands define mutations. Queries provide on-demand reads; observations publish state and event streams; service tokens expose editor-local services and extension values. Session adapters capture local remount state. Collaborative state owners also contribute versioned OT definitions and a durable export codec.
For example, SheetCellFillPlugin publishes its matrix as a field and registers its own mutation command:
registerState() {
return {
key: this.key,
state: this.getState(),
dataEngine: { dataView: [{
viewKey: SheetDataFieldNamespace,
fieldKey: SheetCellFillFieldKey,
select: (state: SheetCellFillPluginState) => state.cellFills,
}] },
};
}
registerCommands(commands: SheetCommandBus) {
const plugin = this;
registerSheetCellFillCommand(commands, {
target: this.key,
getRowCount: () => plugin.getState().cellFills.shape[0],
getColumnCount: () => plugin.getState().cellFills.shape[1],
readCellFill: (row, column) => plugin.getState().cellFills.getItem(row, column),
});
}Package placement follows dependency direction:
- Domain packages define portable values and protocols.
- Plugin packages own optional stateful behavior.
- Host adapters implement platform-specific conversion.
- Assembly packages coordinate composition and lifecycle.
Finite feature values have one canonical enum-like contract. Consumers import that definition instead of maintaining independent value lists or literal unions.
History, collaboration, and export
History records successful commits. Sheet history uses each transaction owner's registered OT definition to invert its operations; Workbook history records structural transactions separately. Undo and redo update their stacks only after inverse or replay operations succeed.
For example, the cell-fill command records the previous fill alongside the new fill. SheetHistoryPlugin uses
SheetCellFillPlugin's Matrix OT definition to produce the reverse operation for undo:
const forward = createUpdateCellOTOperation([1, 1], '#00a870', null);
const inverse = MatrixTransactionOT.invert([forward]);
// inverse[0].uc is { value: null, prev: '#00a870' }.Collaborative transaction owners declare a stable identifier, versioned encode/decode/invert functions, and the required pairwise transform relations. Editor plugins connect committed transactions to host transport. Revision tracking and rebasing remain in the collaboration domain.
SheetCellFillPlugin marks the same operation family as collaborative. It reuses the shared Matrix OT definition,
which provides versioned encoding, decoding, and inversion, and the Matrix relation for concurrent changes:
readonly transactionOT = {
ownerId: 'sheet.cellFill',
definition: MatrixTransactionOT,
relations: [MatrixTransactionOTRelation],
collaborative: true,
};The relevant methods of the shared MatrixTransactionOT definition are:
export const MatrixTransactionOT = Object.freeze({
id: 'sear.matrix',
version: 1,
isOperation: isMatrixOperation,
encode: encodeOperations,
decode(payload: unknown) {
return decodeOperations(payload, isMatrixOperation, 'sear.matrix@1');
},
invert(operations: readonly MatrixOTOperation<unknown>[]) {
return MatrixOT.invert([...operations]);
},
});The plugin supplies its owner identity and operation family; the shared definition reverses its Matrix OT changes. The relation transforms concurrent Matrix OT operation lists before they are applied.
Durable export uses owner-provided codecs registered by stateful plugins. Runtime snapshot commands capture state for in-memory remounting; persisted files require explicit versioned codecs. Third-party plugins use the same export registry as built-in plugins.
For example, the cell-fill plugin captures its matrix and defines how exported fill data is serialized and restored:
static readonly documentState = {
key: 'sheet.cellFills',
capture: (state: SheetCellFillPluginState) => ({ cellFills: state.cellFills.clone() }),
codec: {
key: 'sheet.cellFills',
serialize: (state: SheetCellFillPluginState) => serializeSparseMatrix(state.cellFills),
deserialize: (payload: unknown, path: string) => ({
cellFills: deserializeSparseMatrix<SheetCellFill | null, CellFillMatrix>(payload, CellFillMatrix, path),
}),
},
};
Host application
A host application selects the editor assembly and plugins, supplies concrete platform adapters, and owns the surrounding interface and transport. Browser, headless, desktop, and other hosts can use the same domain and editor contracts.
A visual host provides a render context, text shaper, input and viewport adapters, and an implementation of
Platform for timers, events, and environment services. Dialogs, credentials, persistence, file downloads, and
collaboration transport remain host responsibilities. Reusable packages access them through abstract contracts.
For example, the browser Canvas host supplies concrete implementations when creating the editor:
adapters: {
...WebSheetAdapterDefaults,
platform: BrowserPlatform,
createRenderContexts() {
const renderContext = new WebCanvasRenderContext(canvas, false, new BrowserPlatform());
return {
renderContext,
offScreenRenderContext: renderContext.cloneNode(),
hitRenderContext: renderContext.createHitNode(),
};
},
scroller: WebScroller,
textInput: WebTextInput,
keyboardRouter: WebKeyboardRouter,
collabTransport: WebSocketTransport,
}The npm Workbook example illustrates host assembly with Web adapters. Headless assembly does not require visual host adapters.