# Mog API — Complete Reference > Auto-generated from @mog-sdk/node@0.5.1. > Machine-readable spec: https://sheetmog.ai/api-spec.json ## Workbook ### Sub-APIs - `wb.sheets` → WorkbookSheets - `wb.slicers` → WorkbookSlicers - `wb.slicerStyles` → WorkbookSlicerStyles - `wb.timelineStyles` → WorkbookTimelineStyles - `wb.pivotTableStyles` → WorkbookPivotTableStyles - `wb.functions` → WorkbookFunctions - `wb.names` → WorkbookNames - `wb.scenarios` → WorkbookScenarios - `wb.history` → WorkbookHistory - `wb.tableStyles` → WorkbookTableStyles - `wb.cellStyles` → WorkbookCellStyles - `wb.properties` → WorkbookProperties - `wb.protection` → WorkbookProtection - `wb.security` → WorkbookSecurity - `wb.notifications` → WorkbookNotifications - `wb.theme` → WorkbookTheme - `wb.viewport` → WorkbookViewport - `wb.changes` → WorkbookChanges - `wb.links` → WorkbookLinks ### Methods #### markClean ```typescript markClean(): void; ``` Reset the dirty flag (call after a successful save). #### getSheet ```typescript getSheet(name: string): Promise; ``` Get a sheet by name (case-insensitive). ASYNC — resolves name via Rust. This is the primary sheet accessor for agents, LLMs, and app code. For internal code that already has a SheetId, use `getSheetById()`. #### getSheetById ```typescript getSheetById(sheetId: SheetId): Worksheet; ``` Get a sheet by internal SheetId. SYNC — no IPC needed. Throws KernelError if not found. #### findSheet ```typescript findSheet(name: string): Promise; ``` Find a worksheet by name (case-insensitive), returning null if not found. Non-throwing alternative to {@link getSheet}. @param name - Sheet name (case-insensitive) @returns The worksheet, or null if no sheet with that name exists #### getSheetByIndex ```typescript getSheetByIndex(index: number): Promise; ``` Get a sheet by 0-based index. ASYNC — resolves index via Rust. #### getOrCreateSheet ```typescript getOrCreateSheet(name: string): Promise<{ sheet: Worksheet; created: boolean; }>; ``` Get a sheet by name, creating it if it doesn't exist. @param name - Sheet name (case-insensitive lookup) @returns The sheet and whether it was newly created #### getSheets ```typescript getSheets(): Promise; ``` Get all worksheets in display order. ASYNC — resolves each sheet by name. #### getSheetCount ```typescript getSheetCount(): Promise; ``` Get the count of sheets. Convenience wrapper around sheetCount property. #### getSheetNames ```typescript getSheetNames(): Promise; ``` Get all sheet names in display order. Convenience wrapper around sheetNames property. #### undoGroup ```typescript undoGroup(fn: (wb: Workbook) => Promise): Promise; ``` Execute a group of operations as a single undo step. NOT transactional: if an operation throws, prior writes in the group remain committed. Each mutation within the group still triggers its own recalc pass. #### batch ```typescript batch(label: string, fn: (wb: Workbook) => Promise): Promise; ``` Execute a group of operations as a single undo step with a label. Like `undoGroup`, but attaches a human-readable label to the undo entry (e.g. "Import data"). NOT transactional: partial writes remain committed if fn throws. Each mutation still triggers its own recalc pass. #### createCheckpoint ```typescript createCheckpoint(label?: string): string; ``` Create a named checkpoint (version snapshot). Returns the checkpoint ID. #### restoreCheckpoint ```typescript restoreCheckpoint(id: string): Promise; ``` Restore the workbook to a previously saved checkpoint. #### listCheckpoints ```typescript listCheckpoints(): CheckpointInfo[]; ``` List all saved checkpoints. #### calculate ```typescript calculate(options?: CalculateOptions): Promise; ``` Trigger recalculation of formulas. For circular references (common in financial models — debt schedules, tax shields), enable iterative calculation: await wb.calculate({ iterative: { maxIterations: 100, maxChange: 0.001 } }); Returns convergence metadata (hasCircularRefs, converged, iterations, maxDelta) plus `recomputedCount` — the number of formula cells recomputed during this call. @param options - Calculation options. #### getCalculationMode ```typescript getCalculationMode(): Promise<'auto' | 'autoNoTable' | 'manual'>; ``` Get the current calculation mode (auto/manual/autoNoTable). Convenience accessor — equivalent to `(await getSettings()).calculationSettings.calcMode`. #### setCalculationMode ```typescript setCalculationMode(mode: 'auto' | 'autoNoTable' | 'manual'): Promise; ``` Set the calculation mode. Convenience mutator — patches `calculationSettings.calcMode`. #### getIterativeCalculation ```typescript getIterativeCalculation(): Promise; ``` Get whether iterative calculation is enabled for circular references. Convenience accessor — equivalent to `(await getSettings()).calculationSettings.enableIterativeCalculation`. #### getUsePrecisionAsDisplayed ```typescript getUsePrecisionAsDisplayed(): Promise; ``` Whether to use displayed precision instead of full (15-digit) precision. Convenience accessor — inverted from `calculationSettings.fullPrecision`. #### setUsePrecisionAsDisplayed ```typescript setUsePrecisionAsDisplayed(value: boolean): Promise; ``` Set whether to use displayed precision. Convenience mutator — inverts and patches `calculationSettings.fullPrecision`. #### on ```typescript on(event: string, handler: (event: unknown) => void): CallableDisposable; ``` Subscribe to an arbitrary event string. Handler receives unknown payload. #### executeCode ```typescript executeCode(code: string, options?: ExecuteOptions): Promise; ``` Execute TypeScript/JavaScript code in the spreadsheet sandbox. #### getWorkbookSnapshot ```typescript getWorkbookSnapshot(): Promise; ``` Get a summary snapshot of the entire workbook. #### getFunctionCatalog ```typescript getFunctionCatalog(): FunctionInfo[]; ``` Get the catalog of all available spreadsheet functions. #### getFunctionInfo ```typescript getFunctionInfo(name: string): FunctionInfo | null; ``` Get detailed info about a specific function. #### describeRanges ```typescript describeRanges(requests: SheetRangeRequest[], includeStyle?: boolean): Promise; ``` Describe multiple ranges across multiple sheets in a single IPC call. Each entry returns the same LLM-formatted output as ws.describeRange(). #### toXlsx ```typescript toXlsx(): Promise; ``` Export the workbook as XLSX binary data. #### insertWorksheets ```typescript insertWorksheets(data: string | Uint8Array, options?: InsertWorksheetOptions): Promise; ``` Import sheets from XLSX data. Accepts base64-encoded string or raw Uint8Array. Returns the names of the inserted sheets (may be deduped if names collide). #### save ```typescript save(path: string): Promise; ``` Save the workbook to a file path or buffer. Marks the workbook as clean. #### captureScreenshot ```typescript captureScreenshot(sheet: Worksheet | string, range: string, options?: ScreenshotOptions): Promise; ``` Capture a PNG screenshot of a cell range. @param sheet - Sheet name (e.g. "Sheet1") or Worksheet instance @param range - A1-notation cell range (e.g. "A1:G10") @param options - Rendering options (DPR, headers, gridlines, max dimensions) @returns PNG image as a Buffer #### copyRangeFrom ```typescript copyRangeFrom(source: Workbook, fromRange: string, toRange: string, options?: { fromSheet?: string | Worksheet; toSheet?: string | Worksheet; }): Promise; ``` Copy a range from another workbook into this workbook. #### indexToAddress ```typescript indexToAddress(row: number, col: number): string; ``` Convert row/col to A1 address: (0, 0) -> "A1" #### addressToIndex ```typescript addressToIndex(address: string): { row: number; col: number; }; ``` Convert A1 address to row/col: "A1" -> { row: 0, col: 0 } #### union ```typescript union(...ranges: string[]): string; ``` Combine multiple range addresses into a single comma-separated address. Equivalent to spreadsheet special-cell typeApplication.union(). #### getCultureInfo ```typescript getCultureInfo(): Promise; ``` Get full CultureInfo for the workbook's current culture setting. Resolves the `culture` IETF tag (e.g. 'de-DE') into a complete CultureInfo with number/date/currency formatting details. #### getDecimalSeparator ```typescript getDecimalSeparator(): Promise; ``` Get the decimal separator for the current culture (e.g. '.' or ','). #### getThousandsSeparator ```typescript getThousandsSeparator(): Promise; ``` Get the thousands separator for the current culture (e.g. ',' or '.'). #### searchAllSheets ```typescript searchAllSheets(patterns: string[], options?: SearchOptions): Promise>; ``` Search all sheets for cells matching regex patterns (single IPC call). #### getChartDataPointTrack ```typescript getChartDataPointTrack(): Promise; ``` Get whether chart data points track cell movement. Workbook chart data point tracking.. #### setChartDataPointTrack ```typescript setChartDataPointTrack(value: boolean): Promise; ``` Set whether chart data points track cell movement. #### getSettings ```typescript getSettings(): Promise; ``` Get workbook-level settings. #### setSettings ```typescript setSettings(updates: Partial): Promise; ``` Update workbook-level settings. #### getCustomLists ```typescript getCustomLists(): Promise; ``` Get workbook-level custom fill/sort lists. Returns the complete catalog: immutable built-in lists followed by workbook-scoped user-defined lists. #### addCustomList ```typescript addCustomList(input: WorkbookCustomListInput): Promise; ``` Add a user-defined custom fill/sort list. #### updateCustomList ```typescript updateCustomList(id: string, updates: WorkbookCustomListUpdate): Promise; ``` Update a user-defined custom fill/sort list. Returns false when the list does not exist or is built-in. #### deleteCustomList ```typescript deleteCustomList(id: string): Promise; ``` Delete a user-defined custom fill/sort list. Returns false when the list does not exist or is built-in. #### setCustomLists ```typescript setCustomLists(lists: readonly WorkbookCustomListInput[]): Promise; ``` Replace all user-defined custom fill/sort lists. Built-in lists are code-owned and are never persisted through this method. #### getCustomSetting ```typescript getCustomSetting(key: string): Promise; ``` Get a custom setting value by key. Returns null if not found. #### setCustomSetting ```typescript setCustomSetting(key: string, value: string): Promise; ``` Set a custom setting value. #### deleteCustomSetting ```typescript deleteCustomSetting(key: string): Promise; ``` Delete a custom setting by key. #### listCustomSettings ```typescript listCustomSettings(): Promise>; ``` List all custom settings as key-value pairs. #### getCustomSettingCount ```typescript getCustomSettingCount(): Promise; ``` Get the number of custom settings. #### close ```typescript close(closeBehavior?: 'save' | 'skipSave'): Promise; ``` Close the workbook with optional save behavior. @param closeBehavior - 'save' exports snapshot before disposing, 'skipSave' disposes immediately (default: 'skipSave') #### dispose ```typescript dispose(): void; ``` Dispose of the workbook and release resources. If this workbook was created via `DocumentHandle.workbook()`, disposing also cleans up the underlying DocumentHandle (and vice versa). #### [Symbol.asyncDispose] ```typescript [Symbol.asyncDispose](): Promise; ``` Async dispose for TC39 Explicit Resource Management. @example ```typescript await using wb = await createWorkbook(); ``` #### getActiveCell ```typescript getActiveCell(): { sheetId: string; row: number; col: number; address: string; } | null; ``` Active cell. Returns null in headless/no-UI contexts. #### getSelectedRanges ```typescript getSelectedRanges(): string[]; ``` Currently selected range(s) as A1 address strings. Returns [] in headless. #### getSelectedRange ```typescript getSelectedRange(): string | null; ``` Primary selected range. Returns null in headless. #### getActiveChart ```typescript getActiveChart(): string | null; ``` Active chart object ID, or null. #### getActiveShape ```typescript getActiveShape(): string | null; ``` Active shape object ID, or null. #### getActiveSlicer ```typescript getActiveSlicer(): string | null; ``` Active slicer object ID, or null. #### setActivePrincipal ```typescript setActivePrincipal(principal: string[] | AccessPrincipal | null): Promise; ``` Set the active principal for this session. Pass `null` (or an empty tag list) to clear. Semantics tied to document state, not session state: when the document has no policies, this is effectively a no-op for access decisions (the gated delegate's fast path skips the principal entirely). Once any policy exists, `null` means anonymous — a caller that never set a principal is denied, not owner. Accepts either a flat tag list or an `AccessPrincipal` envelope for symmetry with `explainAccess` / `getEffectiveAccess`. #### activePrincipal ```typescript activePrincipal(): Promise; ``` Current active principal, or `null` if none is set. #### securityActive ```typescript securityActive(): Promise; ``` Whether access-control enforcement is currently active on this document. `false` when the policy set is empty. SDKs use this to warn users who set a principal on a doc that has no policies ("you set a principal but nothing will be enforced"). #### makePrincipal ```typescript makePrincipal(tags: string[]): Promise; ``` Canonicalize a tag list through the engine's intern pool and return the canonical (sorted + deduped) form. Primary purpose is to pre-warm the pool so the next `setActivePrincipal` with the same tag set hits an existing slab — matrix-cache pointer identity stays sound on the first call post-swap. ## Worksheet ### Sub-APIs - `ws.cells` → WorksheetCellsAccessor - `ws.whatIf` → WorksheetWhatIf - `ws.smartArt` → WorksheetSmartArt - `ws.changes` → WorksheetChanges - `ws.formats` → WorksheetFormats - `ws.layout` → WorksheetLayout - `ws.view` → WorksheetView - `ws.structure` → WorksheetStructure - `ws.charts` → WorksheetCharts - `ws.objects` → WorksheetObjectCollection - `ws.shapes` → WorksheetShapeCollection - `ws.pictures` → WorksheetPictureCollection - `ws.textBoxes` → WorksheetTextBoxCollection - `ws.drawings` → WorksheetDrawingCollection - `ws.equations` → WorksheetEquationCollection - `ws.wordArt` → WorksheetWordArtCollection - `ws.connectors` → WorksheetConnectorCollection - `ws.filters` → WorksheetFilters - `ws.formControls` → WorksheetFormControls - `ws.conditionalFormats` → WorksheetConditionalFormatting - `ws.validations` → WorksheetValidation - `ws.tables` → WorksheetTables - `ws.pivots` → WorksheetPivots - `ws.slicers` → WorksheetSlicers - `ws.sparklines` → WorksheetSparklines - `ws.comments` → WorksheetComments - `ws.customProperties` → WorksheetCustomProperties - `ws.hyperlinks` → WorksheetHyperlinks - `ws.outline` → WorksheetOutline - `ws.protection` → WorksheetProtection - `ws.print` → WorksheetPrint - `ws.settings` → WorksheetSettings - `ws.bindings` → WorksheetBindings - `ws.names` → WorksheetNames - `ws.styles` → WorksheetStyles ### Methods #### getName ```typescript getName(): Promise; ``` Get the sheet name. Async — reads from Rust via IPC (cached after first call). #### setName ```typescript setName(name: string): Promise; ``` Set the sheet name. #### getIndex ```typescript getIndex(): number; ``` Get the 0-based sheet index. #### getSheetId ```typescript getSheetId(): SheetId; ``` Get the internal sheet ID. @deprecated Use the `sheetId` property instead. #### setCell ```typescript setCell(address: string, value: CellValuePrimitive | Date, options?: CellWriteOptions): Promise; ``` Set a cell value by A1 address. String values starting with "=" are treated as formulas (e.g. "=SUM(B1:B10)"). Use `options.asFormula` to force formula interpretation without the "=" prefix. Use `options.literal` to store strings starting with "=" as literal text. Date values are automatically converted via setDateValue(). #### setDateValue ```typescript setDateValue(row: number, col: number, year: number, month: number, day: number): Promise; ``` Set a calendar date in a cell, automatically applying a date format. Four input forms (in order of preference for unambiguous semantics): 1. **Calendar parts** — `setDateValue(row, col, year, month, day)` / `setDateValue(addr, year, month, day)`. No `Date`, no timezone — the calendar value is the input. 2. **ISO calendar string** — `setDateValue(row, col, '2026-03-01')` / `setDateValue(addr, '2026-03-01')`. No `Date`, no timezone. 3. **`Date` instant** — `setDateValue(row, col, date)` / `setDateValue(addr, date)`. Resolved against the session's `userTimezone` (set when the workbook was created). 4. **`Date` instant with explicit override** — `setDateValue(row, col, date, { tz })` / `setDateValue(addr, date, { tz })`. Use when a `Date` should be interpreted in a frame other than the session default. @see plans/active/ux/datetime/round-1/session-user-timezone.md #### setTimeValue ```typescript setTimeValue(row: number, col: number, hours: number, minutes: number, seconds: number): Promise; ``` Set a time-of-day in a cell, automatically applying a time format. Three input forms: 1. **Time parts** — `setTimeValue(row, col, hours, minutes, seconds)` / `setTimeValue(addr, hours, minutes, seconds)`. 2. **`Date` instant** — `setTimeValue(row, col, date)` / `setTimeValue(addr, date)`. Resolved against the session's `userTimezone`. 3. **`Date` instant with explicit override** — `setTimeValue(row, col, date, { tz })`. #### getCell ```typescript getCell(address: string): Promise; ``` Get cell data by A1 address. #### getRange ```typescript getRange(range: string): Promise; ``` Get a 2D array of cell data for a range (A1 notation). #### getRanges ```typescript getRanges(addresses: string): Promise; ``` Get cell data for multiple ranges at once (spreadsheet special-cell typeWorksheet.getRanges equivalent). @param addresses - Comma-separated A1-style range addresses (e.g. "A1:B5,D1:E5,G1") @returns Array of 2D cell data arrays, one per address #### setRange ```typescript setRange(range: string, values: (CellValuePrimitive | Date)[][]): Promise; ``` Set a 2D array of values into a range (A1 notation). String values starting with "=" are treated as formulas. #### setArrayFormula ```typescript setArrayFormula(range: CellRange, formula: string): Promise; ``` Enter a CSE (`Ctrl+Shift+Enter`) array formula on the given range. The formula is stored only on the top-left anchor; covered cells are projections of the array result and read-only. Editing any covered cell via `setCell` is rejected by Rust compute-core with `ComputeError::PartialArrayWrite`. Tearing down the array formula is `clear` / `setCell(anchor, null)` on the anchor. Distinct from a regular `setCell` of an array-returning formula: dynamic-array spills allow blocker-literal writes into spill members (raise `#SPILL!`), CSE rejects all partial writes. #### clearData ```typescript clearData(range: string): Promise; ``` Clear all cell data (values and formulas) in a range (A1 notation, e.g. "A1:C3"). #### clear ```typescript clear(range: string, applyTo?: ClearApplyTo): Promise; ``` Unified clear with mode selection (spreadsheet special-cell typeRange.clear equivalent). @param range - A1 range string (e.g. "A1:C3") @param applyTo - What to clear: 'all' (default), 'contents', 'formats', 'hyperlinks' #### clearOrResetContents ```typescript clearOrResetContents(range: string): Promise; ``` Clear cell contents with form control awareness (spreadsheet special-cell typeclearOrResetContents equivalent). For cells linked to form controls: resets the control to its default value (checkbox -> unchecked/false, comboBox -> first item/empty). For all other cells: clears contents normally (same as clear(range, 'contents')). @param range - A1 range string (e.g. "A1:C3") #### getControl ```typescript getControl(address: string): Promise; ``` Get the cell control (e.g., checkbox) for a cell by A1 address. Returns undefined if the cell does not contain a control. #### setControl ```typescript setControl(address: string, control: CellControl | undefined): Promise; ``` Set or clear a cell control by A1 address. Pass undefined to remove the control and revert to a plain cell. #### getValue ```typescript getValue(address: string): Promise; ``` Get the computed value of a cell by A1 address. Returns null for empty cells. Error cells are returned as display strings (e.g. "#DIV/0!"). #### getData ```typescript getData(): Promise; ``` Get all cell values in the used range as a 2D array. Returns [] if sheet is empty. #### getValues ```typescript getValues(range: string): Promise; ``` Get cell values for a range as a 2D array. Returns primitive values only (no formatting, formulas, or metadata). Empty cells are null. This is the most common read pattern for SDK/LLM consumers. @param range - A1-style range string (e.g. "A1:C10") @returns 2D array of cell values #### evaluate ```typescript evaluate(expression: string): Promise; ``` Evaluate a formula expression in the context of this sheet without writing it to any cell. The expression should not include the leading `=`. @example const total = await ws.evaluate("SUM(A1:A10)"); @param expression - Formula expression string (e.g. "SUM(A1:A10)") @returns The computed result value #### validateFormulaSyntax ```typescript validateFormulaSyntax(formula: string): Promise; ``` Validate a formula expression in the context of this sheet without writing it to any cell. Returns `null` when the formula is syntactically valid. Unlike {@link evaluate}, this is a raw commit-time syntax check: it does not normalize or auto-correct incomplete input before parsing. #### getFormula ```typescript getFormula(address: string): Promise; ``` Get the formula of a cell by A1 address (null if not a formula cell). #### getFormulas ```typescript getFormulas(range: string): Promise<(string | null)[][]>; ``` Get formulas for a range. Returns 2D array: formula string or null per cell. #### getFormulasR1C1 ```typescript getFormulasR1C1(range: string): Promise<(string | null)[][]>; ``` Get formulas for a range in R1C1 notation. Returns 2D array: R1C1 formula string or null per cell. References are converted relative to each cell's position: - `$A$1` (absolute) becomes `R1C1` - `A1` relative to cell B2 becomes `R[-1]C[-1]` - `$A1` relative to cell B2 becomes `R[-1]C1` (mixed) @param range - A1-style range string (e.g. "A1:C10") #### getFormulaArray ```typescript getFormulaArray(address: string): Promise; ``` Get the array formula for a cell that is part of a dynamic array spill. If the cell is the source of a dynamic array (e.g., =SEQUENCE(5)), returns the formula. If the cell is a spill member (projected from a source), returns the source cell's formula. Returns null if the cell is not part of an array. @param address - A1-style cell address @returns The array formula string, or null if not an array cell #### getRawCellData ```typescript getRawCellData(address: string, includeFormula?: boolean): Promise; ``` Get raw cell data (value, formula, format, borders, etc.) by A1 address. #### getRawRangeData ```typescript getRawRangeData(range: string | CellRange, options?: { includeFormula?: boolean; }): Promise; ``` Get raw data for a range as a 2D array (A1 notation or CellRange). #### getRangeWithIdentity ```typescript getRangeWithIdentity(range: string | CellRange): Promise; ``` Get all non-empty cells in a range with stable CellId identity. Returns a flat array of cells (not a 2D grid) — only cells with data are included. Each cell includes its CellId, position, computed value, formula text (if formula cell), and pre-formatted display string. Used by operations that need identity-aware cell data (find-replace, clipboard, cell relocation). #### describe ```typescript describe(address?: string): Promise; ``` Get a human-readable description of a cell or the entire used range. With address: returns compact cell string — "Revenue | =SUM(B2:B10) | [bold]" Without address: returns describeRange() over the used range (or empty string if sheet is empty) #### describeRange ```typescript describeRange(range: string | CellRange, includeStyle?: boolean): Promise; ``` Get a tabular description of a range with formula abbreviation. #### summarize ```typescript summarize(options?: SummaryOptions): Promise; ``` Get a sheet overview summary for agent context. #### getUsedRange ```typescript getUsedRange(): Promise; ``` Get the used range, or null if the sheet is empty. #### getCurrentRegion ```typescript getCurrentRegion(row: number, col: number): Promise; ``` Get the contiguous data region around a cell (Excel's Ctrl+Shift+* / CurrentRegion). #### findDataEdge ```typescript findDataEdge(row: number, col: number, direction: 'up' | 'down' | 'left' | 'right'): Promise<{ row: number; col: number; }>; ``` Find the data edge in a direction (Excel's Ctrl+Arrow). Single bridge call to Rust. #### findLastRow ```typescript findLastRow(col: number): Promise<{ lastDataRow: number | null; lastFormatRow: number | null; }>; ``` Find the last populated row in a column. Returns data and formatting edges. #### findLastColumn ```typescript findLastColumn(row: number): Promise<{ lastDataCol: number | null; lastFormatCol: number | null; }>; ``` Find the last populated column in a row. Returns data and formatting edges. #### findCells ```typescript findCells(predicate: (cell: CellData) => boolean, range?: string): Promise; ``` Find all cells matching a predicate. Returns A1 addresses. Searches entire sheet or optionally within a range. #### findByValue ```typescript findByValue(value: CellValue, range?: string): Promise; ``` Find all cells with a specific value. Returns A1 addresses. Searches entire sheet or optionally within a range. #### findByFormula ```typescript findByFormula(pattern: RegExp, range?: string): Promise; ``` Find all cells whose formula matches a regex pattern. Returns A1 addresses. Searches entire sheet or optionally within a range. #### regexSearch ```typescript regexSearch(patterns: string[], options?: SearchOptions): Promise; ``` Search cells using regex patterns. #### signCheck ```typescript signCheck(range?: string, options?: SignCheckOptions): Promise; ``` Detect cells whose numeric sign disagrees with their neighbors. Returns anomalies sorted by severity — the agent decides which are real errors. #### findInRange ```typescript findInRange(range: string, text: string, options?: FindInRangeOptions): Promise; ``` Find the first cell matching text within a range (spreadsheet special-cell typeRange.find equivalent). @param range - A1 range string to search within @param text - Text or regex pattern to search for @param options - Search options (matchCase, entireCell) @returns The first matching SearchResult, or null if no match found #### replaceAll ```typescript replaceAll(range: string, text: string, replacement: string, options?: FindInRangeOptions): Promise; ``` Find and replace all occurrences within a range (spreadsheet special-cell typeRange.replaceAll equivalent). @param range - A1 range string to search within @param text - Text to find @param replacement - Replacement text @param options - Search options (matchCase, entireCell) @returns Number of replacements made #### getExtendedRange ```typescript getExtendedRange(range: string, direction: 'up' | 'down' | 'left' | 'right', activeCell?: { row: number; col: number; }): Promise; ``` Get the extended range in a direction (spreadsheet special-cell typeRange.getExtendedRange / Ctrl+Shift+Arrow). From the active cell (default: top-left of range), finds the data edge in the given direction and returns a range extending from the original range to that edge. @param range - A1 range string (current selection) @param direction - Direction to extend @param activeCell - Optional active cell override (default: top-left of range) @returns Extended range as CellRange #### isEntireColumn ```typescript isEntireColumn(range: string | CellRange): boolean; ``` Check if a range represents entire column(s) (e.g., "A:C"). @param range - A1 range string or CellRange object @returns True if the range represents entire column(s) #### isEntireRow ```typescript isEntireRow(range: string | CellRange): boolean; ``` Check if a range represents entire row(s) (e.g., "1:5"). @param range - A1 range string or CellRange object @returns True if the range represents entire row(s) #### getVisibleView ```typescript getVisibleView(range: string): Promise; ``` Get only the visible (non-hidden) rows from a range (visible range-view equivalent). Filters out rows hidden by AutoFilter or manual hide operations. Returns cell values for visible rows only, along with the absolute row indices. @param range - A1 range string (e.g., "A1:Z100") @returns Visible rows' values and their indices #### getSpecialCells ```typescript getSpecialCells(cellType: CellType, valueType?: CellValueType): Promise; ``` Find cells matching a special cell type (spreadsheet special-cell typeRange.getSpecialCells equivalent). Returns addresses of cells matching the specified type within the used range. Optionally filter by value type when cellType is `Constants` or `Formulas`. @param cellType - The type of cells to find @param valueType - Optional value type filter (only for Constants/Formulas) @returns Array of matching cell addresses #### getValueForEditing ```typescript getValueForEditing(row: number, col: number, editText?: string): Promise; ``` Get the edit-mode string representation of a cell value. Used by formula bar and in-cell editing. For formula cells, returns the formula string (e.g. "=SUM(A1:A10)"). For date/time cells, returns pre-computed edit text if available. For value cells, returns the raw value as a string. @param row - Row index (0-based) @param col - Column index (0-based) @param editText - Optional pre-computed edit text (for date/time cells) @returns The string to display in edit mode #### getDisplayValue ```typescript getDisplayValue(address: string): Promise; ``` Get the display value (formatted string) for a cell by A1 address. #### getDisplayValues ```typescript getDisplayValues(range: string): Promise; ``` Get the formatted display values for a range as a 2D array. Returns the same formatted strings shown in each cell (number formats applied, dates formatted, etc.). This is the range counterpart to `getDisplayValue()`. @param range - A1-style range string (e.g. "A1:C10") @returns 2D array of formatted display strings #### getValueTypes ```typescript getValueTypes(range: string | CellRange): Promise; ``` Get per-cell value type classification for a range (spreadsheet special-cell typeRange.valueTypes equivalent). @param range - A1 range string or CellRange object @returns 2D array of RangeValueType enums #### getNumberFormatCategories ```typescript getNumberFormatCategories(range: string | CellRange): Promise; ``` Get per-cell number format category for a range (spreadsheet special-cell typeRange.numberFormatCategories equivalent). @param range - A1 range string or CellRange object @returns 2D array of NumberFormatCategory enums #### sortRange ```typescript sortRange(range: string, options: SortOptions): Promise; ``` Sort a range by the specified options (A1 notation). #### sortByColor ```typescript sortByColor(range: string | CellRange, opts: SortByColorOptions): Promise; ``` Sort a range by cell or font color, putting matched-color rows on top or bottom. Convenience wrapper over {@link sortRange} with a single color-keyed criterion. Excel/ECMA-376 vocabulary: `'fill'` is the cell background fill, `'font'` is the cell font color. Compares the resolved per-cell effective format. @param range - A1-style range string or CellRange object @param opts - Color sort options (column, color type, target color, top/bottom position) #### autoFill ```typescript autoFill(sourceRange: string, targetRange: string, fillMode?: AutoFillMode): Promise; ``` Autofill from source range into target range. @param sourceRange - Source range in A1 notation (e.g., "A1:A3") @param targetRange - Target range to fill into (e.g., "A4:A10") @param fillMode - Fill behavior. Default: 'auto' (detect pattern). #### fillSeries ```typescript fillSeries(range: string, options: FillSeriesOptions): Promise; ``` Fill a range with a series (Edit > Fill > Series dialog equivalent). More explicit than autoFill — caller specifies exact series parameters. The range contains BOTH source cells (first row/col) and target cells (rest). The kernel splits them based on direction. @param range - Range in A1 notation containing source + target cells @param options - Series parameters (type, step, stop, direction, etc.) #### moveTo ```typescript moveTo(sourceRange: string, targetRow: number, targetCol: number): Promise; ``` Move (relocate) cells from a source range to a target position. Moves cell values, formulas, and formatting. Formula references within the moved range are adjusted to the new position. The source range is cleared after the move. @param sourceRange - Source range in A1 notation (e.g., "A1:B10") @param targetRow - Destination top-left row (0-based) @param targetCol - Destination top-left column (0-based) #### copyFrom ```typescript copyFrom(sourceRange: string, targetRange: string, options?: CopyFromOptions): Promise; ``` Copy cells from a source range to a target range with optional paste-special behavior. Supports selective copy (values only, formulas only, formats only, or all), skip-blanks, and transpose. Maps to spreadsheet special-cell typeRange.copyFrom(). @param sourceRange - Source range in A1 notation (e.g., "A1:B10") @param targetRange - Target range in A1 notation (e.g., "D1:E10") @param options - Optional paste-special behavior (copyType, skipBlanks, transpose) #### setCells ```typescript setCells(cells: Array<{ addr: string; value: CellValuePrimitive | Date; }>): Promise; ``` Bulk-write scattered cell values and/or formulas in a single IPC call. Values starting with "=" are treated as formulas. Supports both A1 addressing and numeric (row, col) addressing. #### toCSV ```typescript toCSV(options?: { separator?: string; range?: string; }): Promise; ``` Export the used range as a CSV string (RFC 4180 compliant). Fields containing commas, quotes, or newlines are quoted. Double-quotes inside fields are escaped as "". Formula injection is prevented by prefixing `=`, `+`, `-`, `@` with a tab character. @param options - Optional separator (default ",") #### toJSON ```typescript toJSON(options?: { headerRow?: number | 'none'; range?: string; }): Promise[]>; ``` Export the used range as an array of row objects. By default, the first row is used as header keys. Pass `headerRow: 'none'` to use column letters (A, B, C, ...) as keys. Pass `headerRow: N` to use a specific 0-based row as headers. @param options - Optional header row configuration and range #### getDependents ```typescript getDependents(address: string): Promise; ``` Get cells that depend on this cell by A1 address. #### getPrecedents ```typescript getPrecedents(address: string): Promise; ``` Get cells that this cell depends on by A1 address. #### enableCalculation ```typescript enableCalculation: boolean; ``` Per-sheet toggle that controls whether formulas on this sheet are recalculated. When `false`, formulas retain their last computed value but do not recalculate when dependencies change. Defaults to `true`. #### calculate ```typescript calculate(markAllDirty?: boolean): Promise; ``` Force recalculation of this sheet. @param markAllDirty - If `true`, marks all formula cells on this sheet as dirty before recalculating (equivalent to a full sheet recalc). Defaults to `false`, which recalculates only cells already marked dirty. #### getSelectionAggregates ```typescript getSelectionAggregates(ranges: CellRange[]): Promise; ``` Get aggregates (SUM, COUNT, AVG, MIN, MAX) for selected ranges. #### formatValues ```typescript formatValues(entries: FormatEntry[]): Promise; ``` Batch-format values using number format codes. Returns formatted strings. #### getVisibility ```typescript getVisibility(): Promise<'visible' | 'hidden' | 'veryHidden'>; ``` Get the visibility state of the sheet ('visible', 'hidden', or 'veryHidden'). #### setVisibility ```typescript setVisibility(state: 'visible' | 'hidden' | 'veryHidden'): Promise; ``` Set the visibility state of the sheet. #### getNext ```typescript getNext(visibleOnly?: boolean): Promise; ``` Returns the next worksheet. If `visibleOnly` is true, skips hidden sheets. Throws if no next sheet exists. #### getNextOrNull ```typescript getNextOrNull(visibleOnly?: boolean): Promise; ``` Returns the next worksheet, or null if none exists. If `visibleOnly` is true, skips hidden sheets. #### getPrevious ```typescript getPrevious(visibleOnly?: boolean): Promise; ``` Returns the previous worksheet. If `visibleOnly` is true, skips hidden sheets. Throws if no previous sheet exists. #### getPreviousOrNull ```typescript getPreviousOrNull(visibleOnly?: boolean): Promise; ``` Returns the previous worksheet, or null if none exists. If `visibleOnly` is true, skips hidden sheets. #### on ```typescript on(event: string, handler: (event: unknown) => void): CallableDisposable; ``` #### refreshActiveCellData ```typescript refreshActiveCellData(row: number, col: number): Promise; ``` Refresh the active-cell metadata cache (Stream C fix). Call this when the active cell changes (selection move) so the viewport reader's `getActiveCellData()` returns up-to-date metadata — including `isCseAnchor` — and the formula bar can immediately display `{=…}` braces for CSE array formula cells. Looks up the cellId at the given position and calls the compute bridge's `refreshActiveCell`. Safe to call speculatively; no-ops if the cell has no id (empty cell). #### refreshActiveCellEditSource ```typescript refreshActiveCellEditSource(row: number, col: number): Promise; ``` Refresh the active-cell edit-source read model for the given cell. This is infrastructure for edit-entry hot paths. It is intentionally scoped to the active cell rather than exposing arbitrary synchronous cell reads. #### getActiveCellEditSource ```typescript getActiveCellEditSource(row: number, col: number): ActiveCellEditSource | null; ``` Synchronously read the active-cell edit-source cache when it matches the requested cell and is fresh. Returns null for stale/missing/different-cell data so callers can fall back to one Rust-owned edit-source query. #### setBoundsReader ```typescript setBoundsReader(reader: IObjectBoundsReader): void; ``` Inject the bounds reader (from the renderer's SceneGraphBoundsReader) so that floating-object handles can resolve pixel bounds via `handle.getBounds()`. Calling this invalidates cached typed collections so they pick up the new reader on their next access. ## WorkbookSheets ### Methods #### add ```typescript add(name?: string, index?: number): Promise; ``` Add a new sheet to the workbook. @param name - Optional sheet name. Defaults to "SheetN". @param index - Optional 0-based position to insert the sheet. @returns The created Worksheet. #### remove ```typescript remove(target: number | string): Promise; ``` Remove a sheet by index or name. Throws if attempting to remove the last sheet. @param target - 0-based index or sheet name. #### move ```typescript move(target: number | string, toIndex: number): Promise; ``` Move a sheet to a new position. @param target - 0-based index or sheet name to move. @param toIndex - Target 0-based index. #### rename ```typescript rename(target: number | string, newName: string): Promise; ``` Rename a sheet. @param target - 0-based index or current sheet name. @param newName - The new name for the sheet. #### setActive ```typescript setActive(target: number | string): void | Promise; ``` Set the active sheet. @param target - 0-based index or sheet name. #### copy ```typescript copy(source: number | string, newName?: string, index?: number): Promise; ``` Copy a sheet within the workbook. @param source - 0-based index or name of the sheet to copy. @param newName - Optional name for the copy. Defaults to "SheetName (Copy)". @param index - Optional 0-based position for the copy. @returns The newly created Worksheet. #### hide ```typescript hide(target: number | string): Promise; ``` Hide a sheet. Throws if attempting to hide the last visible sheet. @param target - 0-based index or sheet name. #### show ```typescript show(target: number | string): Promise; ``` Show (unhide) a sheet. @param target - 0-based index or sheet name. #### setSelectedIds ```typescript setSelectedIds(sheetIds: string[]): Promise; ``` Set which sheets are selected (multi-sheet selection for collaboration). @param sheetIds - Array of sheet IDs to mark as selected. #### on ```typescript on(event: string, handler: (event: unknown) => void): CallableDisposable; ``` ## WorkbookSlicers Sub-API for workbook-scoped slicer operations. ### Methods #### list ```typescript list(): Promise; ``` List all slicers across all sheets in the workbook. @returns Array of slicer summary information #### get ```typescript get(slicerId: string): Promise; ``` Get a slicer by ID from any sheet. @param slicerId - ID of the slicer @returns Full slicer state, or null if not found #### getItemAt ```typescript getItemAt(index: number): Promise; ``` Get a slicer by its zero-based index in the list. @param index - Zero-based index of the slicer @returns Slicer summary information, or null if index is out of range #### getItems ```typescript getItems(slicerId: string): Promise; ``` Get the items (values) available in a slicer by ID. @param slicerId - ID of the slicer @returns Array of slicer items with selection state #### getItem ```typescript getItem(slicerId: string, key: CellValue): Promise; ``` Get a slicer item by its string key. @param slicerId - ID of the slicer @param key - The value to look up (matched via string coercion) @returns The matching slicer item @throws KernelError if no item matches the key #### getItemOrNullObject ```typescript getItemOrNullObject(slicerId: string, key: CellValue): Promise; ``` Get a slicer item by its string key, or null if not found. @param slicerId - ID of the slicer @param key - The value to look up (matched via string coercion) @returns The matching slicer item, or null if not found #### remove ```typescript remove(slicerId: string): Promise; ``` Remove a slicer by ID from any sheet. @param slicerId - ID of the slicer to remove #### getCount ```typescript getCount(): Promise; ``` Get the total count of slicers across all sheets. @returns Number of slicers in the workbook ## WorkbookSlicerStyles ### Methods #### getDefault ```typescript getDefault(): Promise; ``` Get the workbook's default slicer style preset. Returns 'light1' if not explicitly set. #### setDefault ```typescript setDefault(style: string | null): Promise; ``` Set the workbook's default slicer style preset. Pass null to reset to 'light1'. #### getCount ```typescript getCount(): Promise; ``` Get the number of built-in slicer styles. #### getItem ```typescript getItem(name: string): Promise; ``` Get a specific slicer style by name. Returns null if not found. #### list ```typescript list(): Promise; ``` List all built-in slicer styles. #### add ```typescript add(name: string, style: SlicerCustomStyle, makeUniqueName?: boolean): Promise; ``` Add a new custom named slicer style. @param name - Desired style name. @param style - Custom style definition. @param makeUniqueName - When true, auto-appends a suffix if the name collides. Default: false. @returns The final name assigned to the style (may differ from `name` when `makeUniqueName` is true). #### get ```typescript get(name: string): Promise; ``` Get a custom named slicer style by name, or null if not found. #### remove ```typescript remove(name: string): Promise; ``` Remove a custom named slicer style. @param name - The name of the style to remove. #### duplicate ```typescript duplicate(name: string): Promise; ``` Duplicate an existing named slicer style. @param name - The name of the style to duplicate. @returns The name of the newly created copy. ## WorkbookTimelineStyles ### Methods #### getDefault ```typescript getDefault(): Promise; ``` Get the workbook's default timeline style preset. Returns 'light1' if not explicitly set. #### setDefault ```typescript setDefault(style: string | null): Promise; ``` Set the workbook's default timeline style preset. Pass null to reset to 'light1'. #### getCount ```typescript getCount(): Promise; ``` Get the number of built-in timeline styles. #### getItem ```typescript getItem(name: string): Promise; ``` Get a specific timeline style by name. Returns null if not found. #### list ```typescript list(): Promise; ``` List all built-in timeline styles. #### add ```typescript add(name: string, style: SlicerCustomStyle, makeUniqueName?: boolean): Promise; ``` Add a new custom named timeline style. @param name - Desired style name. @param style - Custom style definition. @param makeUniqueName - When true, auto-appends a suffix if the name collides. Default: false. @returns The final name assigned to the style (may differ from `name` when `makeUniqueName` is true). #### get ```typescript get(name: string): Promise; ``` Get a custom named timeline style by name, or null if not found. #### remove ```typescript remove(name: string): Promise; ``` Remove a custom named timeline style. @param name - The name of the style to remove. #### duplicate ```typescript duplicate(name: string): Promise; ``` Duplicate an existing named timeline style. @param name - The name of the style to duplicate. @returns The name of the newly created copy. ## WorkbookPivotTableStyles ### Methods #### getDefault ```typescript getDefault(): Promise; ``` Get the workbook's default pivot table style preset. Returns 'PivotStyleLight16' if not explicitly set. #### setDefault ```typescript setDefault(style: string | null): Promise; ``` Set the workbook's default pivot table style preset. Pass null to reset to 'PivotStyleLight16'. #### getCount ```typescript getCount(): Promise; ``` Get the count of built-in pivot table styles. #### getItem ```typescript getItem(name: string): Promise; ``` Get a pivot table style by name, or null if not found. #### list ```typescript list(): Promise; ``` List all built-in pivot table styles. ## WorkbookFunctions ### Methods #### invoke ```typescript invoke(functionName: string, ...args: unknown[]): Promise; ``` Invoke any spreadsheet function by name with arbitrary arguments. @param functionName - The function name (e.g. 'VLOOKUP', 'SUM'). @param args - Arguments: cell/range refs as strings, literals as values. @returns The evaluated result. #### vlookup ```typescript vlookup( lookupValue: CellValue, tableArray: string, colIndex: number, rangeLookup?: boolean, ): Promise; ``` VLOOKUP function. @param lookupValue - The value to search for. @param tableArray - The range reference (e.g. "A1:C10"). @param colIndex - Column index (1-based) to return. @param rangeLookup - Whether to use approximate match (default: false). #### sum ```typescript sum(...ranges: string[]): Promise; ``` SUM function. #### average ```typescript average(...ranges: string[]): Promise; ``` AVERAGE function. #### count ```typescript count(...ranges: string[]): Promise; ``` COUNT function. #### max ```typescript max(...ranges: string[]): Promise; ``` MAX function. #### min ```typescript min(...ranges: string[]): Promise; ``` MIN function. #### concatenate ```typescript concatenate(...values: CellValue[]): Promise; ``` CONCATENATE function. ## WorkbookNames ### Methods #### add ```typescript add(name: string, reference: string, comment?: string): Promise; ``` Define a new named range. @param name - The name to define. @param reference - A1-style reference (e.g. "Sheet1!$A$1:$B$10"). May omit leading "=". @param comment - Optional descriptive comment. #### has ```typescript has(name: string, scope?: string): Promise; ``` Check if a named range exists. @param name - The name to check. @param scope - Optional sheet name scope. Omit for workbook-scoped names. @returns True if the named range exists. #### getCount ```typescript getCount(): Promise; ``` Get the total number of named ranges in the workbook. @returns The count of named ranges. #### get ```typescript get(name: string, scope?: string): Promise; ``` Get a named range by name. @param name - The name to look up. @param scope - Optional sheet name scope. Omit for workbook-scoped names. @returns The named range info, or null if not found. #### getRange ```typescript getRange(name: string, scope?: string): Promise; ``` Get the parsed sheet reference for a named range. Returns the sheet name and range portion for names that refer to a simple sheet!range reference. Returns null if the name is not found or if the reference is not a simple sheet!range format (e.g., a formula). @param name - The name to look up. @param scope - Optional sheet name scope. Omit for workbook-scoped names. @returns The parsed reference, or null if not found or not a simple range. #### remove ```typescript remove(name: string, scope?: string): Promise; ``` Remove a named range. @param name - The name to remove. @param scope - Optional sheet name scope. Omit for workbook-scoped names. #### update ```typescript update(name: string, updates: NamedRangeUpdateOptions): Promise; ``` Update an existing named range. @param name - The current name to update. @param updates - Fields to change (name, reference, comment). #### clear ```typescript clear(): Promise; ``` Remove all named ranges from the workbook. #### list ```typescript list(): Promise; ``` List all named ranges in the workbook. @returns Array of named range info objects. #### createFromSelection ```typescript createFromSelection( sheet: string | SheetId, range: CellRange, options: CreateNamesFromSelectionOptions, ): Promise; ``` Create named ranges from row/column labels in a selection. Scans edges of the selection for label text and creates names referring to the corresponding data cells. @param sheet - Sheet containing the selection (name or SheetId). @param range - The cell range to scan for labels. @param options - Which edges to scan (top, left, bottom, right). @returns Counts of successfully created and skipped names. #### getValue ```typescript getValue(name: string, scope?: string): Promise; ``` Get the computed value of a named item as a display-formatted string. For single-cell references, returns the formatted cell value. For range references, returns the raw A1 reference string. @param name - The named item to evaluate. @param scope - Optional sheet name scope for resolution precedence. @returns The display value, or null if the name doesn't exist. #### getType ```typescript getType(name: string, scope?: string): Promise; ``` Get the API type of a named item's resolved value. @param name - The named item to inspect. @param scope - Optional sheet name scope for resolution precedence. @returns The type string, or null if the name doesn't exist. #### getArrayValues ```typescript getArrayValues(name: string, scope?: string): Promise; ``` Get the 2D array of resolved values for a named range. For single-cell references, returns a 1×1 array. For multi-cell ranges, returns the full grid. @param name - The named item to evaluate. @param scope - Optional sheet name scope for resolution precedence. @returns The 2D value array, or null if the name doesn't exist or isn't a range. #### getArrayTypes ```typescript getArrayTypes(name: string, scope?: string): Promise; ``` Get the 2D array of type classifications for each cell in a named range. @param name - The named item to evaluate. @param scope - Optional sheet name scope for resolution precedence. @returns The 2D type array, or null if the name doesn't exist or isn't a range. #### getValueAsJson ```typescript getValueAsJson(name: string, scope?: string): Promise; ``` Get the raw typed value of a named item as a JSON-compatible value. For single-cell references, returns the cell's typed value (string, number, boolean, null, or error). For range references, returns the first cell's value. For constants, returns the constant as a string. @param name - The named item to evaluate. @param scope - Optional sheet name scope for resolution precedence. @returns The typed value, or null if the name doesn't exist. #### recalculateDependents ```typescript recalculateDependents(name: string, sheetId: SheetId, origin?: string): void; ``` Recalculate all formulas that depend on a given named range. Called after a name is created, updated, or deleted so that dependent cells reflect the new definition (or show #NAME? errors). @param name - The name that changed (case-insensitive). @param sheetId - Current active sheet for relative reference resolution. @param origin - Transaction origin (default: 'user'). ## WorkbookScenarios ### Methods #### add ```typescript add(config: ScenarioConfig): Promise; ``` Add a what-if scenario. @param config - Scenario configuration (name, changing cells, values). @returns The newly created scenario's ID. #### list ```typescript list(): Promise; ``` List all scenarios in the workbook. @returns Array of all saved scenarios. #### getActiveScenarioId ```typescript getActiveScenarioId(): Promise; ``` Return the session-scoped active scenario id, if a scenario is currently applied. #### getActiveScenarioState ```typescript getActiveScenarioState(): Promise; ``` Return session-scoped active scenario state. This is not persisted in workbook storage. #### apply ```typescript apply(id: string): Promise; ``` Apply a scenario's values to the worksheet. @param id - The scenario ID to apply. @returns Result including cells updated count and original values for restore. #### restore ```typescript restore(baselineIdOrOriginals: string | OriginalCellValue[]): Promise; ``` Restore original values from a prior apply() call and deactivate the scenario. @param baselineIdOrOriginals - The Rust session baseline ID returned by apply(). Legacy original-value arrays are accepted by the current kernel wrapper but are ignored; restore is owned by the Rust session baseline. #### update ```typescript update(scenarioId: string, config: Partial): Promise; ``` Update an existing scenario's configuration. @param scenarioId - The scenario ID to update. @param config - Partial configuration with fields to change. #### remove ```typescript remove(id: string): Promise; ``` Remove a scenario. @param id - The scenario ID to remove. ## WorkbookHistory ### Methods #### undo ```typescript undo(): Promise; ``` Undo the last operation. #### redo ```typescript redo(): Promise; ``` Redo the last undone operation. #### canUndo ```typescript canUndo(): boolean; ``` Check if undo is available. Synchronous (uses cached state). #### canRedo ```typescript canRedo(): boolean; ``` Check if redo is available. Synchronous (uses cached state). #### list ```typescript list(): UndoHistoryEntry[]; ``` Get the undo history entries. Synchronous. #### goToIndex ```typescript goToIndex(index: number): Promise; ``` Undo to a specific index in the history. Performs multiple undo operations to reach the target state. @param index - Index in the history (0 = most recent operation) #### getState ```typescript getState(): Promise; ``` Get the full undo/redo state from the compute engine. Returns depth counts used by CheckpointManager to track checkpoint state. #### subscribe ```typescript subscribe(listener: (event: UndoStateChangeEvent) => void): CallableDisposable; ``` Subscribe to undo/redo state changes. Called whenever the undo stack changes (push, undo, redo, clear). @returns Unsubscribe function #### setNextDescription ```typescript setNextDescription(description: string): void; ``` Set the description for the next undo step. Call immediately before a mutation to label the undo entry. ## WorkbookTableStyles ### Methods #### list ```typescript list(): Promise; ``` Get all table styles (built-in + custom) with a `readOnly` flag. #### add ```typescript add(name: string, style: TableStyleConfig): Promise; ``` Create a custom table style. Returns the style name/ID. #### update ```typescript update(name: string, style: Partial): Promise; ``` Update a custom table style. #### remove ```typescript remove(name: string): Promise; ``` Remove a custom table style. #### getDefault ```typescript getDefault(): Promise; ``` Get the default table style ID applied to new tables. #### setDefault ```typescript setDefault(name: string | undefined): Promise; ``` Set the default table style ID for new tables. Pass undefined to reset. #### duplicate ```typescript duplicate(name: string, newName: string): Promise; ``` Duplicate an existing table style. Returns the new style info. ## WorkbookCellStyles ### Methods #### get ```typescript get(styleId: string): Promise; ``` Get a cell format (style) by its style ID. Returns the format, or null if not found. #### getStyle ```typescript getStyle(styleId: string): Promise; ``` Get a full cell style by ID. Returns null if not found. #### list ```typescript list(options?: CellStyleListOptions): Promise; ``` List cell styles. Defaults to built-in + custom styles. #### getCatalog ```typescript getCatalog(options?: Pick): Promise; ``` Get ordered style catalog data for gallery-style consumers. #### add ```typescript add(name: string, format: CellFormat): Promise; ``` Create a new custom cell style. #### update ```typescript update( styleId: string, updates: Partial>, ): Promise; ``` Update a custom cell style. Returns the updated style, or null if not found. #### remove ```typescript remove(styleId: string): Promise; ``` Delete a custom cell style. Returns true if deleted. ## WorkbookProperties WorkbookProperties -- Document properties sub-API interface. Provides methods to read and write document metadata (title, author, keywords, etc.) and custom document properties. ### Methods #### getDocumentProperties ```typescript getDocumentProperties(): Promise; ``` Get all document properties (author, title, keywords, etc.). #### setDocumentProperties ```typescript setDocumentProperties(props: Partial): Promise; ``` Update document properties (partial merge). #### getCustomProperty ```typescript getCustomProperty(key: string): Promise; ``` Get a custom document property by key. #### setCustomProperty ```typescript setCustomProperty(key: string, value: string): Promise; ``` Set a custom document property. #### removeCustomProperty ```typescript removeCustomProperty(key: string): Promise; ``` Remove a custom document property. #### listCustomProperties ```typescript listCustomProperties(): Promise>; ``` List all custom document properties. ## WorkbookProtection ### Methods #### isProtected ```typescript isProtected(): Promise; ``` Check if the workbook structure is currently protected. #### getOptions ```typescript getOptions(): Promise; ``` Get the current protection options, or null if the workbook is not protected. #### protect ```typescript protect(password?: string, options?: Partial): Promise; ``` Protect workbook structure with optional password and options. #### unprotect ```typescript unprotect(password?: string): Promise; ``` Unprotect the workbook. Returns true if successful (password matches). ## WorkbookSecurity ### Methods #### addPolicy ```typescript addPolicy(policy: Omit): Promise; ``` Add a new access policy. Rust enforces capability attenuation: the caller's effective workbook level must be >= the granted level. @returns The assigned PolicyId #### removePolicy ```typescript removePolicy(id: PolicyId): Promise; ``` Remove a policy by ID. Idempotent at the store layer. #### updatePolicy ```typescript updatePolicy(id: PolicyId, updates: Partial>): Promise; ``` Update fields on an existing policy. Attenuation re-runs when `level` is patched. #### getPolicies ```typescript getPolicies(): Promise; ``` Get all policies currently on the document, in stable id-sorted order. #### getEffectiveAccess ```typescript getEffectiveAccess(principal: AccessPrincipal, target: AccessTarget): Promise; ``` Get the effective access level for a principal at a target. #### explainAccess ```typescript explainAccess(principal: AccessPrincipal, target: AccessTarget): Promise; ``` Explain why a principal has a given access level at a target. Returns the winning policy, reason, candidates, and any warnings. #### applyTemplate ```typescript applyTemplate(templateId: string, options: Record): Promise; ``` Apply a named template, generating policies. The `templateId` is the Rust tagged-enum variant name (e.g. `protect_workbook`, `protect_sheet`, `agent_structure`); `options` merges into the wire payload under the same keys the Rust `Template` variant expects. @returns The PolicyIds of the generated policies. #### removeTemplate ```typescript removeTemplate(templateId: string): Promise; ``` Remove all policies generated by a template. ## WorkbookNotifications Workbook-level notifications sub-API. Provides toast/notification operations without requiring apps to import from `@mog-sdk/kernel/services/notifications`. ### Methods #### getAll ```typescript getAll(): Notification[]; ``` Get all active notifications #### subscribe ```typescript subscribe(listener: (notifications: Notification[]) => void): CallableDisposable; ``` Subscribe to notification changes. Returns CallableDisposable — call directly or .dispose() to unsubscribe. #### notify ```typescript notify(message: string, options?: NotificationOptions): NotificationId; ``` Show a notification. Returns the notification ID. #### info ```typescript info(message: string, options?: Omit): NotificationId; ``` Show an info notification. Returns the notification ID. #### success ```typescript success(message: string, options?: Omit): NotificationId; ``` Show a success notification. Returns the notification ID. #### warning ```typescript warning(message: string, options?: Omit): NotificationId; ``` Show a warning notification. Returns the notification ID. #### error ```typescript error(message: string, options?: Omit): NotificationId; ``` Show an error notification. Returns the notification ID. #### dismiss ```typescript dismiss(id: NotificationId): void; ``` Dismiss a notification by ID #### dismissAll ```typescript dismissAll(): void; ``` Dismiss all notifications ## WorkbookTheme ### Methods #### getWorkbookTheme ```typescript getWorkbookTheme(): Promise; ``` Get the workbook's OOXML theme definition (color palette + fonts). Reads from Rust via bridge — async. #### setWorkbookTheme ```typescript setWorkbookTheme(theme: ThemeDefinition): Promise; ``` Set the workbook's OOXML theme definition. Writes to Rust via bridge — async. Triggers viewport palette invalidation so subsequent renders pick up the new theme colors. #### getChromeTheme ```typescript getChromeTheme(): ChromeTheme; ``` Get the current chrome theme (canvas UI shell colors). Synchronous — TS-only, no Rust involvement. #### setChromeTheme ```typescript setChromeTheme(theme: Partial): void; ``` Set chrome theme with partial merge semantics. Merges the partial input with the **current** theme (not defaults). Triggers canvas layer re-render and CSS variable update. To reset to defaults, pass `DEFAULT_CHROME_THEME` explicitly. ## WorkbookViewport Viewport management sub-API on the Workbook. Consumer-scoped: createRegion() returns a handle with per-viewport refresh, prefetch, and lifecycle management. ### Methods #### createRegion ```typescript createRegion(sheetId: string, bounds: ViewportBounds, viewportId?: string): ViewportRegion; ``` Create a tracked viewport region. Returns a handle — dispose when done. #### resetSheetRegions ```typescript resetSheetRegions(sheetId: string): void; ``` Reset all regions for a sheet (e.g., on sheet switch). #### setRenderScheduler ```typescript setRenderScheduler(scheduler: RenderScheduler | null): void; ``` Inject (or clear) the render scheduler for "Write = Invalidate" integration. When set, mutation patches applied to viewport buffers automatically trigger a render frame via the scheduler. #### subscribe ```typescript subscribe(cb: (event: ViewportChangeEvent) => void): () => void; ``` Subscribe to viewport state change events from all viewport coordinators. Events are emitted synchronously after each state change. Returns an unsubscribe function. #### setShowFormulas ```typescript setShowFormulas(value: boolean): void; ``` Set the show-formulas mode. When true, Rust substitutes formula strings into the display text field of viewport cells that have formulas. Invalidates all prefetch bounds so the next viewport refresh fetches fresh data with the correct display mode. ## WorkbookChanges Sub-API for opt-in workbook-level change tracking. ### Methods #### track ```typescript track(options?: WorkbookTrackOptions): WorkbookChangeTracker; ``` Create a change tracker that accumulates cell-level change records across all sheets from this point forward. @param options - Optional origin filters and limit @returns A WorkbookChangeTracker handle — call collect() to drain, close() when done ## WorkbookLinks ### Methods #### list ```typescript list(): readonly PersistedWorkbookLinkRecord[]; ``` #### get ```typescript get(linkId: LinkId): PersistedWorkbookLinkRecord | null; ``` #### add ```typescript add(input: CreateWorkbookLinkInput): PersistedWorkbookLinkRecord; ``` #### create ```typescript create(input: CreateWorkbookLinkInput): PersistedWorkbookLinkRecord; ``` #### retarget ```typescript retarget(linkId: LinkId, input: RetargetWorkbookLinkInput): PersistedWorkbookLinkRecord; ``` #### update ```typescript update(linkId: LinkId, input: UpdateWorkbookLinkInput): PersistedWorkbookLinkRecord; ``` #### break ```typescript break(linkId: LinkId, options?: BreakWorkbookLinkOptions): boolean; ``` #### delete ```typescript delete(linkId: LinkId): boolean; ``` #### getStatus ```typescript getStatus(linkId: LinkId): LinkStatusView; ``` #### refresh ```typescript refresh(linkId: LinkId): Promise; ``` #### watchStatus ```typescript watchStatus(linkId: LinkId, handler: (status: LinkStatusView) => void): () => void; ``` ## WorksheetCellsAccessor Sub-API for typed per-cell readback by A1 address. Surfaced on {@link Worksheet.cells}. ### Methods #### get ```typescript get(addr: string): Promise; ``` Read a typed cell record by A1 address (e.g. `"B2"`). **Async.** Backed by the kernel's domain-layer `CellReads.getData`, which goes through the compute bridge (CellId lookup + `getActiveCell`, with spill-member and materialized-cell fallbacks). A sync read off the viewport buffer was considered and rejected: the viewport only covers the rendered window, so a sync `get` would silently return `undefined` for off-screen cells and surprise callers. Returns `undefined` when the cell is outside the sheet bounds. Empty in-bounds cells return a record with `value === null` and `valueType === RangeValueType.Empty` — deliberately divergent from `getCell`'s `{value: null}` shape so the discriminant tag is always present (callers don't need a separate "is this in-bounds" check). ## WorksheetWhatIf Sub-API for What-If analysis operations. ### Methods #### goalSeek ```typescript goalSeek(targetCell: string, targetValue: number, changingCell: string): Promise; ``` Find the input value that makes a formula produce a target result (Excel's "Goal Seek" equivalent). Use this to back-solve for an unknown assumption — e.g., find the discount rate that produces a specific NPV, or the growth rate needed to hit a revenue target. Example — find WACC that yields NPV = 0: ``` // B1 = WACC assumption, B5 = =NPV(B1, C10:C20) const result = await ws.whatIf.goalSeek('B5', 0, 'B1'); if (result.found) { await ws.cells.setCellValue('B1', result.solutionValue); } ``` The method is read-only — the changing cell is restored after evaluation. Call setCellValue() yourself to apply the solution. @param targetCell - A1 address of the cell containing the formula to evaluate @param targetValue - The desired result value @param changingCell - A1 address of the input cell to vary @returns GoalSeekResult with solutionValue if found #### dataTable ```typescript dataTable( formulaCell: string, options: { rowInputCell?: string | null; colInputCell?: string | null; rowValues: (string | number | boolean | null)[]; colValues: (string | number | boolean | null)[]; }, ): Promise; ``` Compute a sensitivity/scenario table by evaluating a formula with different input values (Excel's "What-If Data Table" equivalent). Use this for DCF sensitivity tables, LBO return grids, or any two-dimensional parameter sweep. One-variable table: provide either `rowInputCell` or `colInputCell`. Two-variable table: provide both. Example — 2D sensitivity grid (WACC x Terminal Growth Rate): ``` // B1 = WACC assumption (e.g. 0.10) // B2 = Terminal growth rate (e.g. 0.025) // B3 = =NPV(B1, C10:C20) + terminal_value (the formula to sweep) const result = await ws.whatIf.dataTable('B3', { rowInputCell: 'B1', colInputCell: 'B2', rowValues: [0.08, 0.09, 0.10, 0.11, 0.12], colValues: [0.015, 0.020, 0.025, 0.030, 0.035], }); // result.results is a 5x5 grid of NPV values // Write to sheet: iterate result.results and call setCells() ``` Input cells must already contain a value before calling this method. The method is read-only — input cells are restored after evaluation. @param formulaCell - A1 address of the cell containing the formula to evaluate @param options - Input cells and substitution values @returns 2D grid of computed results (DataTableResult) #### createDataTable ```typescript createDataTable(options: CreateDataTableOptions): Promise; ``` Create a persistent two-variable Data Table over the selected table range. Unlike `dataTable()`, this is a write operation. It stores the Data Table region as workbook metadata so recalculation, readback, and future XLSX export use the same compute-owned authority. ## WorksheetSmartArt ### Methods #### add ```typescript add(config: SmartArtConfig): Promise; ``` Add a diagram to the sheet. Returns the created floating object. #### get ```typescript get(objectId: string): Promise; ``` Get a diagram by object ID, or null if not found. #### has ```typescript has(objectId: string): Promise; ``` Check if a diagram exists by object ID. #### getCount ```typescript getCount(): Promise; ``` Get the total number of diagrams on this sheet. #### remove ```typescript remove(objectId: string): Promise; ``` Remove a diagram by object ID. #### list ```typescript list(): Promise; ``` List all diagrams on the sheet. #### clear ```typescript clear(): Promise; ``` Remove all diagrams from the sheet. #### duplicate ```typescript duplicate(objectId: string): Promise; ``` Duplicate a diagram. Returns the new object ID. #### addNode ```typescript addNode( objectId: string, text: string, position: NodePosition, referenceNodeId: NodeId | null, ): Promise; ``` Add a node to a diagram. Returns the new node ID. #### removeNode ```typescript removeNode(objectId: string, nodeId: NodeId): Promise; ``` Remove a node from a diagram. #### updateNode ```typescript updateNode( objectId: string, nodeId: NodeId, updates: Partial, ): Promise; ``` Update a node's properties. #### moveNode ```typescript moveNode(objectId: string, nodeId: NodeId, direction: NodeMoveDirection): Promise; ``` Move a node in the hierarchy. #### getNode ```typescript getNode( objectId: string, nodeId: NodeId, ): Promise; ``` Get a node by ID. #### getDiagram ```typescript getDiagram(objectId: string): Promise; ``` @deprecated Use `get(objectId)` instead. Will be removed in a future release. #### getDiagramsOnSheet ```typescript getDiagramsOnSheet(): Promise; ``` @deprecated Use `list()` instead. Will be removed in a future release. #### changeLayout ```typescript changeLayout(objectId: string, newLayoutId: string): Promise; ``` Change the diagram layout. #### changeQuickStyle ```typescript changeQuickStyle(objectId: string, quickStyleId: string): Promise; ``` Change the quick style. #### changeColorTheme ```typescript changeColorTheme(objectId: string, colorThemeId: string): Promise; ``` Change the color theme. #### getComputedLayout ```typescript getComputedLayout( objectId: string, ): Promise; ``` Get the computed layout for a diagram. Returns cached result if valid. #### invalidateLayout ```typescript invalidateLayout(objectId: string): void; ``` Invalidate the cached layout for a diagram. #### invalidateAllLayouts ```typescript invalidateAllLayouts(): void; ``` Invalidate all cached layouts. ## WorksheetChanges Sub-API for opt-in change tracking on a worksheet. ### Methods #### track ```typescript track(options?: ChangeTrackOptions): ChangeTracker; ``` Create a change tracker that accumulates cell-level change records from this point forward. @param options - Optional scope and origin filters @returns A ChangeTracker handle — call collect() to drain, close() when done ## WorksheetFormats Sub-API for cell formatting operations on a worksheet. ### Methods #### set ```typescript set(address: string, format: CellFormat): Promise; ``` Set format for a single cell. @param address - A1-style cell address (e.g. "A1", "B3") @param format - Format properties to apply @example // Bold red currency await ws.formats.set('A1', { bold: true, fontColor: '#ff0000', numberFormat: '$#,##0.00' }); // Date format await ws.formats.set('B1', { numberFormat: 'YYYY-MM-DD' }); // Header style await ws.formats.set('A1', { bold: true, fontSize: 14, backgroundColor: '#4472c4', fontColor: '#ffffff' }); #### setRange ```typescript setRange(range: string, format: CellFormat): Promise; ``` Set format for a contiguous range. @param range - A1-style range string (e.g. "A1:B2") @param format - Format properties to apply @example // Currency column await ws.formats.setRange('B2:B100', { numberFormat: '$#,##0.00' }); // Header row with borders await ws.formats.setRange('A1:F1', { bold: true, backgroundColor: '#4472c4', fontColor: '#ffffff', borders: { bottom: { style: 'medium', color: '#2f5496' } } }); #### setRanges ```typescript setRanges(ranges: CellRange[], format: CellFormat): Promise; ``` Set format for multiple ranges, with full row/column optimization. @param ranges - Array of range objects @param format - Format properties to apply #### hasExplicit ```typescript hasExplicit(address: string): Promise; ``` Check if a cell has explicit formatting applied (not just inherited from row/column/sheet). Returns true if the cell has any non-default explicit format properties set directly on it. Returns false if the cell only inherits formatting from the row, column, or sheet cascade. @param address - A1-style cell address @returns True if the cell has explicit formatting #### clearCell ```typescript clearCell(address: string): Promise; ``` Clear format from a single cell, resetting it to default. @param address - A1-style cell address #### clear ```typescript clear(): Promise; ``` Clear all cell formats in the worksheet, resetting to defaults. #### clearRange ```typescript clearRange(range: string): Promise; ``` Clear all format properties from cells in a contiguous range. Unlike `setRange(range, {})` which merges (and leaves existing properties untouched), this removes all explicit formatting, resetting cells to the inherited cascade. @param range - A1-style range string (e.g. "A1:B2") #### clearRanges ```typescript clearRanges(ranges: CellRange[]): Promise; ``` Clear all format properties from cells in multiple ranges. @param ranges - Array of range objects #### get ```typescript get(address: string): Promise; ``` Get the fully-resolved format of a single cell. Returns a dense CellFormat with all fields present (null for unset properties, never undefined). Includes the full cascade (default → col → row → table → cell → CF) with theme colors resolved to hex. @param address - A1-style cell address @returns The resolved cell format (always an object, never null) #### getDisplayedCellProperties ```typescript getDisplayedCellProperties(address: string): Promise; ``` Get the fully-resolved displayed format of a single cell. Includes the full 6-layer cascade (default → col → row → table → cell → CF) with theme colors resolved to hex. Unlike `get()`, this includes the conditional formatting overlay. @param address - A1-style cell address @returns The displayed cell format with CF applied #### getDisplayedRangeProperties ```typescript getDisplayedRangeProperties(range: string | CellRange): Promise; ``` Get displayed formats for a rectangular range. Each element includes the full 6-layer cascade with CF overlay. Maximum 10,000 cells per call. @param range - A1-style range string (e.g. "A1:C3") @returns 2D array of displayed cell formats #### adjustIndent ```typescript adjustIndent(address: string, amount: number): Promise; ``` Adjust the indent level of a cell by a relative amount. @param address - A1-style cell address @param amount - Relative indent change (positive to increase, negative to decrease) #### clearFill ```typescript clearFill(address: string): Promise; ``` Clear only fill properties of a cell (backgroundColor, patternType, patternForegroundColor, gradientFill). Unlike `clearCell()`, this preserves font, alignment, borders, and other formatting. @param address - A1-style cell address #### clearFillForRanges ```typescript clearFillForRanges(ranges: CellRange[]): Promise; ``` Clear only fill properties for multiple ranges. Preserves font, alignment, borders, and other formatting via read-modify-write. #### getNumberFormatCategory ```typescript getNumberFormatCategory(address: string): Promise; ``` Get the auto-derived number format category for a cell based on its format code. @param address - A1-style cell address @returns The detected NumberFormatType category #### getNumberFormatLocal ```typescript getNumberFormatLocal(address: string): Promise; ``` Get the locale-aware number format for a cell (spreadsheet special-cell typeRange.numberFormatLocal equivalent). Resolves the `[$-LCID]` token in the stored format code and transforms separators to match the locale's conventions. For example, a cell with format `[$-407]#,##0.00` returns `#.##0,00` (German conventions). If no LCID token is present, returns the raw format code unchanged. @param address - A1-style cell address @returns The locale-resolved format string #### setNumberFormatLocal ```typescript setNumberFormatLocal(address: string, localFormat: string, locale: string): Promise; ``` Set the locale-aware number format for a cell (spreadsheet special-cell typeRange.numberFormatLocal equivalent). Encodes the locale-specific format by prepending the appropriate `[$-LCID]` token and transforming separators to internal (en-US) conventions. For example, setting `#.##0,00` with locale `de-DE` stores `[$-407]#,##0.00`. @param address - A1-style cell address @param localFormat - The locale-specific format string @param locale - BCP-47 locale tag (e.g., "de-DE", "fr-FR") #### applyPattern ```typescript applyPattern( format: CellFormat, sourceRange: CellRange | null, targetRange: CellRange, ): Promise; ``` Apply a format pattern from a source range to a target range. When the target range is larger than the source range, the source format pattern is tiled to fill the target (like Excel's Format Painter with multi-cell sources). @param format - The base format to apply (used when sourceRange is null or single-cell) @param sourceRange - Source range for pattern replication, or null for simple application @param targetRange - Target range to apply formats to #### getCellProperties ```typescript getCellProperties(range: string): Promise>>; ``` Get effective (resolved) cell formats for a rectangular range. Returns a 2D array (row-major) where each element is the fully resolved format from the 5-layer cascade (default -> col -> row -> table -> cell). Cells with no explicit format may return null. @param range - A1-style range string (e.g. "A1:C3") @returns 2D array of CellFormat (or null for cells with default format) #### setCellProperties ```typescript setCellProperties( updates: Array<{ row: number; col: number; format: Partial }>, ): Promise; ``` Set cell formats for a batch of individual cells with heterogeneous formats. Unlike setRange (which applies one format to all cells), this allows each cell to receive a different format. Formats merge with existing cell formats on a per-property basis. @param updates - Array of {row, col, format} entries #### getRowProperties ```typescript getRowProperties(rows: number[]): Promise>; ``` Get row-level formats for the specified rows. Returns a Map from row index to CellFormat (only rows with explicit formats are included; rows with no format are omitted). @param rows - Row indices (0-based) @returns Map of row index to CellFormat #### setRowProperties ```typescript setRowProperties(updates: Map>): Promise; ``` Set row-level formats for multiple rows. Formats merge with existing row formats on a per-property basis. @param updates - Map of row index to format properties #### getColumnProperties ```typescript getColumnProperties(cols: number[]): Promise>; ``` Get column-level formats for the specified columns. Returns a Map from column index to CellFormat (only columns with explicit formats are included). @param cols - Column indices (0-based) @returns Map of column index to CellFormat #### setColumnProperties ```typescript setColumnProperties(updates: Map>): Promise; ``` Set column-level formats for multiple columns. Formats merge with existing column formats on a per-property basis. @param updates - Map of column index to format properties ## WorksheetLayout Sub-API for row/column layout operations on a worksheet. ### Methods #### getRowHeight ```typescript getRowHeight(row: number): Promise; ``` Get the height of a row in pixels. @param row - Row index (0-based) @returns Row height in pixels #### setRowHeight ```typescript setRowHeight(row: number, height: number): Promise; ``` Set the height of a row. @param row - Row index (0-based) @param height - Height in pixels (must be > 0) #### getColumnWidth ```typescript getColumnWidth(col: number): Promise; ``` Get the width of a column in pixels. @param col - Column index (0-based) @returns Column width in pixels #### setColumnWidth ```typescript setColumnWidth(col: number, widthPx: number): Promise; ``` Set the width of a column in pixels. @param col - Column index (0-based) @param widthPx - Width in pixels (must be > 0) #### getColumnWidthChars ```typescript getColumnWidthChars(col: number): Promise; ``` Get the width of a column in character-width units (relative to the Normal style font's maximum digit width, matching OOXML/Excel convention). @param col - Column index (0-based) @returns Column width in character-width units #### setColumnWidthChars ```typescript setColumnWidthChars(col: number, widthChars: number): Promise; ``` Set the width of a column in character-width units (relative to the Normal style font's maximum digit width, matching OOXML/Excel convention). @param col - Column index (0-based) @param widthChars - Width in character-width units (must be > 0) #### setColumnWidths ```typescript setColumnWidths(widths: Array<[number, number]>): Promise; ``` Set multiple column widths in pixels. @param widths - Array of [columnIndex, widthPx] pairs #### setColumnWidthsChars ```typescript setColumnWidthsChars(widths: Array<[number, number]>): Promise; ``` Set multiple column widths in character-width units. @param widths - Array of [columnIndex, widthChars] pairs #### autoFitColumn ```typescript autoFitColumn(col: number): Promise; ``` Auto-fit a column width to its content. @param col - Column index (0-based) #### autoFitColumns ```typescript autoFitColumns(cols: number[]): Promise; ``` Auto-fit multiple columns to their content in a single batch call. @param cols - Array of column indices (0-based) #### autoFitRow ```typescript autoFitRow(row: number): Promise; ``` Auto-fit a row height to its content. @param row - Row index (0-based) #### autoFitRows ```typescript autoFitRows(rows: number[]): Promise; ``` Auto-fit multiple rows to their content in a single batch call. @param rows - Array of row indices (0-based) #### getRowHeightsBatch ```typescript getRowHeightsBatch(startRow: number, endRow: number): Promise>; ``` Get row heights for a range of rows. @param startRow - Start row index (0-based, inclusive) @param endRow - End row index (0-based, inclusive) @returns Array of [rowIndex, height] pairs #### getColWidthsBatch ```typescript getColWidthsBatch(startCol: number, endCol: number): Promise>; ``` Get column widths for a range of columns in pixels. @param startCol - Start column index (0-based, inclusive) @param endCol - End column index (0-based, inclusive) @returns Array of [colIndex, widthPx] pairs #### getColWidthsBatchChars ```typescript getColWidthsBatchChars(startCol: number, endCol: number): Promise>; ``` Get column widths for a range of columns in character-width units (relative to the Normal style font's maximum digit width, matching OOXML/Excel convention). @param startCol - Start column index (0-based, inclusive) @param endCol - End column index (0-based, inclusive) @returns Array of [colIndex, charWidth] pairs #### setRowVisible ```typescript setRowVisible(row: number, visible: boolean): Promise; ``` Set the visibility of a single row. @param row - Row index (0-based) @param visible - True to show, false to hide #### setColumnVisible ```typescript setColumnVisible(col: number, visible: boolean): Promise; ``` Set the visibility of a single column. @param col - Column index (0-based) @param visible - True to show, false to hide #### isRowHidden ```typescript isRowHidden(row: number): Promise; ``` Check whether a row is hidden. @param row - Row index (0-based) @returns True if the row is hidden #### isColumnHidden ```typescript isColumnHidden(col: number): Promise; ``` Check whether a column is hidden. @param col - Column index (0-based) @returns True if the column is hidden #### unhideRows ```typescript unhideRows(startRow: number, endRow: number): Promise; ``` Unhide all rows in a range. @param startRow - Start row index (0-based, inclusive) @param endRow - End row index (0-based, inclusive) #### unhideColumns ```typescript unhideColumns(startCol: number, endCol: number): Promise; ``` Unhide all columns in a range. @param startCol - Start column index (0-based, inclusive) @param endCol - End column index (0-based, inclusive) #### hideRows ```typescript hideRows(rows: number[]): Promise; ``` Hide multiple rows by index. @param rows - Array of row indices to hide (0-based) #### hideColumns ```typescript hideColumns(cols: number[]): Promise; ``` Hide multiple columns by index. @param cols - Array of column indices to hide (0-based) #### getHiddenRowsBitmap ```typescript getHiddenRowsBitmap(): Promise>; ``` Get the set of all hidden row indices. @returns Set of hidden row indices #### getHiddenColumnsBitmap ```typescript getHiddenColumnsBitmap(): Promise>; ``` Get the set of all hidden column indices. @returns Set of hidden column indices #### resetRowHeight ```typescript resetRowHeight(row: number): Promise; ``` Reset a row's height to the sheet default. @param row - Row index (0-based) #### resetColumnWidth ```typescript resetColumnWidth(col: number): Promise; ``` Reset a column's width to the sheet default. @param col - Column index (0-based) #### getRowPosition ```typescript getRowPosition(row: number): Promise; ``` Get the pixel offset of a row's top edge from the worksheet origin. @param row - Row index (0-based) @returns Pixel offset from the top of the worksheet #### getColPosition ```typescript getColPosition(col: number): Promise; ``` Get the pixel offset of a column's left edge from the worksheet origin. @param col - Column index (0-based) @returns Pixel offset from the left of the worksheet #### getRangePosition ```typescript getRangePosition(range: CellRange): Promise; ``` Get the pixel bounds of a range (top, left, height, width). Returns range pixel bounds in a single call. @param range - The cell range to measure @returns Pixel bounds relative to the worksheet origin ## WorksheetView Sub-API for worksheet view and display operations. ### Methods #### freezeRows ```typescript freezeRows(count: number): Promise; ``` Freeze the top N rows. Preserves any existing column freeze. @param count - Number of rows to freeze (0 to unfreeze rows) #### freezeColumns ```typescript freezeColumns(count: number): Promise; ``` Freeze the left N columns. Preserves any existing row freeze. @param count - Number of columns to freeze (0 to unfreeze columns) #### freezePanes ```typescript freezePanes(rows: number, cols: number): Promise; ``` Freeze rows and columns simultaneously. This is the atomic form of Freeze Panes. The first unfrozen cell is at (rows, cols): for example, freezePanes(1, 1) freezes row 0 and column 0. @param rows - Number of top rows to freeze (0 to freeze no rows) @param cols - Number of left columns to freeze (0 to freeze no columns) #### unfreeze ```typescript unfreeze(): Promise; ``` Remove all frozen panes (both rows and columns). #### getFrozenPanes ```typescript getFrozenPanes(): Promise<{ rows: number; cols: number }>; ``` Get the current frozen panes configuration. @returns Object with the number of frozen rows and columns #### freezeAt ```typescript freezeAt(range: string): Promise; ``` Freeze rows and columns simultaneously using a range reference. The top-left cell of the range becomes the first unfrozen cell. For example, freezeAt("B3") freezes 2 rows and 1 column. @param range - A cell reference (e.g., "B3") indicating the split point #### getSplitConfig ```typescript getSplitConfig(): Promise; ``` Get the current split view configuration. @returns The split configuration, or null if the view is not split #### setSplitConfig ```typescript setSplitConfig(config: SplitViewportConfig | null): Promise; ``` Set or clear the split view configuration. @param config - Split configuration to apply, or null to remove split #### setGridlines ```typescript setGridlines(show: boolean): Promise; ``` Show or hide gridlines. @param show - True to show gridlines, false to hide #### setHeadings ```typescript setHeadings(show: boolean): Promise; ``` Show or hide row/column headings. @param show - True to show headings, false to hide #### getViewOptions ```typescript getViewOptions(): Promise; ``` Get the current view options (gridlines, headings). @returns Current view options #### setShowFormulas ```typescript setShowFormulas(show: boolean): Promise; ``` Show formula source text in cells instead of calculated display values. This is a persisted per-sheet view option. @param show - True to show formulas, false to show calculated values #### getTabColor ```typescript getTabColor(): Promise; ``` Get the tab color of this worksheet. @returns The tab color as a hex string, or null if no color is set #### setTabColor ```typescript setTabColor(color: string | null): Promise; ``` Set or clear the tab color for this worksheet. @param color - Hex color string, or null to clear #### getScrollPosition ```typescript getScrollPosition(): Promise; ``` Get the persistent scroll position (cell-level) for this sheet. #### setScrollPosition ```typescript setScrollPosition(topRow: number, leftCol: number): Promise; ``` Set the persistent scroll position (cell-level) for this sheet. ## WorksheetStructure ### Methods #### insertRows ```typescript insertRows(index: number, count: number): Promise; ``` Insert rows starting at the given 0-based index. #### deleteRows ```typescript deleteRows(index: number, count: number): Promise; ``` Delete rows starting at the given 0-based index. #### insertColumns ```typescript insertColumns(index: number, count: number): Promise; ``` Insert columns starting at the given 0-based index. #### deleteColumns ```typescript deleteColumns(index: number, count: number): Promise; ``` Delete columns starting at the given 0-based index. #### insertCellsWithShift ```typescript insertCellsWithShift( startRow: number, startCol: number, endRow: number, endCol: number, direction: 'right' | 'down', ): Promise; ``` Insert cells by shifting existing cells in the specified direction. #### deleteCellsWithShift ```typescript deleteCellsWithShift( startRow: number, startCol: number, endRow: number, endCol: number, direction: 'left' | 'up', ): Promise; ``` Delete cells by shifting remaining cells in the specified direction. #### getRowCount ```typescript getRowCount(): Promise; ``` Get the number of rows with data. #### getColumnCount ```typescript getColumnCount(): Promise; ``` Get the number of columns with data. #### textToColumns ```typescript textToColumns( range: string | CellRange, options: TextToColumnsOptions, ): Promise; ``` Split text in a column into multiple columns. #### removeDuplicates ```typescript removeDuplicates( range: string | CellRange, columns: number[], hasHeaders?: boolean, ): Promise; ``` Remove duplicate rows in a range. #### merge ```typescript merge(range: string): Promise; ``` Merge cells by A1 range. #### unmerge ```typescript unmerge(range: string): Promise; ``` Unmerge cells by A1 range. #### getMergedRegions ```typescript getMergedRegions(): Promise; ``` Get all merged regions in the sheet. #### getMergeAtCell ```typescript getMergeAtCell(address: string): Promise; ``` Get the merge containing a cell by A1 address, or null if not merged. ## WorksheetCharts ### Methods #### add ```typescript add(config: ChartConfig): Promise; ``` Add a chart to the sheet. Returns the created chart. #### get ```typescript get(chartId: string): Promise; ``` Get a chart by ID, or null if not found. #### update ```typescript update(chartId: string, updates: Partial): Promise; ``` Update a chart's configuration. #### remove ```typescript remove(chartId: string): Promise; ``` Remove a chart by ID. #### list ```typescript list(): Promise; ``` List all charts in the sheet. #### clear ```typescript clear(): Promise; ``` Remove all charts from the sheet. #### duplicate ```typescript duplicate(chartId: string): Promise; ``` Duplicate a chart, offsetting the copy by 2 rows. Returns the new chart ID. #### exportImage ```typescript exportImage(chartId: string, options?: ImageExportOptions): Promise; ``` Export a chart as an image. Note: This is a stub — actual rendering requires a canvas context. The bridge integration will be wired in Wave 4. #### setDataRange ```typescript setDataRange(chartId: string, range: string): Promise; ``` Set a chart's data range (A1 notation). #### setType ```typescript setType(chartId: string, type: ChartType, subType?: string): Promise; ``` Set a chart's type and optional sub-type. #### has ```typescript has(chartId: string): Promise; ``` Check if a chart exists by ID. #### getCount ```typescript getCount(): Promise; ``` Get the total number of charts on this sheet. #### getByName ```typescript getByName(name: string): Promise; ``` Find a chart by its name, or null if not found. #### bringToFront ```typescript bringToFront(chartId: string): Promise; ``` Bring a chart to the front (highest z-index). #### sendToBack ```typescript sendToBack(chartId: string): Promise; ``` Send a chart to the back (lowest z-index). #### bringForward ```typescript bringForward(chartId: string): Promise; ``` Bring a chart forward by one layer. #### sendBackward ```typescript sendBackward(chartId: string): Promise; ``` Send a chart backward by one layer. #### linkToTable ```typescript linkToTable(chartId: string, tableId: string): Promise; ``` Link a chart to a table so it auto-updates with the table's data. #### unlinkFromTable ```typescript unlinkFromTable(chartId: string): Promise; ``` Unlink a chart from its source table. #### isLinkedToTable ```typescript isLinkedToTable(chartId: string): Promise; ``` Check whether a chart is linked to a table. #### addSeries ```typescript addSeries(chartId: string, config: SeriesConfig): Promise; ``` Add a data series to a chart. Returns the new series index. #### removeSeries ```typescript removeSeries(chartId: string, index: number): Promise; ``` Remove a data series by index. #### getSeries ```typescript getSeries(chartId: string, index: number): Promise; ``` Get a data series by index. #### updateSeries ```typescript updateSeries(chartId: string, index: number, updates: Partial): Promise; ``` Update a data series at the given index. #### getSeriesCount ```typescript getSeriesCount(chartId: string): Promise; ``` Get the number of data series in a chart. #### reorderSeries ```typescript reorderSeries(chartId: string, fromIndex: number, toIndex: number): Promise; ``` Reorder a series from one index to another. #### setSeriesValues ```typescript setSeriesValues(chartId: string, index: number, range: string): Promise; ``` Set the values range for a series (A1 notation). #### setSeriesCategories ```typescript setSeriesCategories(chartId: string, index: number, range: string): Promise; ``` Set the categories range for a series (A1 notation). #### getSeriesBinOptions ```typescript getSeriesBinOptions(chartId: string, seriesIndex: number): Promise; ``` Get per-series histogram bin options, or null if not set (falls back to chart-level). #### setSeriesBinOptions ```typescript setSeriesBinOptions( chartId: string, seriesIndex: number, options: HistogramConfig, ): Promise; ``` Set per-series histogram bin options (overrides chart-level histogram config). #### getSeriesBoxwhiskerOptions ```typescript getSeriesBoxwhiskerOptions(chartId: string, seriesIndex: number): Promise; ``` Get per-series box/whisker options, or null if not set (falls back to chart-level). #### setSeriesBoxwhiskerOptions ```typescript setSeriesBoxwhiskerOptions( chartId: string, seriesIndex: number, options: BoxplotConfig, ): Promise; ``` Set per-series box/whisker options (overrides chart-level boxplot config). #### formatPoint ```typescript formatPoint( chartId: string, seriesIndex: number, pointIndex: number, format: { fill?: string; border?: ChartBorder }, ): Promise; ``` Format an individual data point within a series. #### setPointDataLabel ```typescript setPointDataLabel( chartId: string, seriesIndex: number, pointIndex: number, config: DataLabelConfig, ): Promise; ``` Set the data label configuration for an individual data point. #### addTrendline ```typescript addTrendline( chartId: string, seriesIndex: number, config: TrendlineConfig, ): Promise; ``` Add a trendline to a series. Returns the new trendline index. #### removeTrendline ```typescript removeTrendline( chartId: string, seriesIndex: number, trendlineIndex: number, ): Promise; ``` Remove a trendline from a series by index. #### getTrendline ```typescript getTrendline( chartId: string, seriesIndex: number, trendlineIndex: number, ): Promise; ``` Get a trendline configuration by index, or null if not found. #### getTrendlineCount ```typescript getTrendlineCount(chartId: string, seriesIndex: number): Promise; ``` Get the number of trendlines on a series. #### getDataTable ```typescript getDataTable(chartId: string): Promise; ``` Get the chart's data table configuration, or null if none. #### getItemAt ```typescript getItemAt(index: number): Promise; ``` Get a chart by its positional index, or null if out of range. #### setBubbleSizes ```typescript setBubbleSizes(chartId: string, seriesIndex: number, range: string): Promise; ``` Set the bubble sizes range for a series (A1 notation). #### onActivated ```typescript onActivated(handler: (args: { chartId: string }) => void): CallableDisposable; ``` Register a handler for chart activation events. Returns a CallableDisposable. #### onDeactivated ```typescript onDeactivated(handler: (args: { chartId: string }) => void): CallableDisposable; ``` Register a handler for chart deactivation events. Returns a CallableDisposable. #### getAxisItem ```typescript getAxisItem( chartId: string, type: 'category' | 'value' | 'series', group: 'primary' | 'secondary', ): Promise; ``` Get an axis by spreadsheet special-cell typetype/group identifiers. #### setAxisTitle ```typescript setAxisTitle(chartId: string, axisType: 'category' | 'value', formula: string): Promise; ``` Set axis title from a formula string. #### setCategoryNames ```typescript setCategoryNames(chartId: string, range: string): Promise; ``` Set category axis labels from a cell range (A1 notation). #### getSeriesDimensionValues ```typescript getSeriesDimensionValues( chartId: string, seriesIndex: number, dimension: ChartSeriesDimension, ): Promise<(string | number)[]>; ``` Get computed values for a series dimension. #### getSeriesDimensionDataSourceString ```typescript getSeriesDimensionDataSourceString( chartId: string, seriesIndex: number, dimension: ChartSeriesDimension, ): Promise; ``` Get the range/formula string for a series dimension. #### getSeriesDimensionDataSourceType ```typescript getSeriesDimensionDataSourceType( chartId: string, seriesIndex: number, dimension: ChartSeriesDimension, ): Promise; ``` Get the data source type for a series dimension ('range' | 'literal' | 'formula'). #### getDataLabelSubstring ```typescript getDataLabelSubstring( chartId: string, seriesIndex: number, pointIndex: number, start: number, length: number, ): Promise; ``` Get a rich text substring from a data label. #### setDataLabelHeight ```typescript setDataLabelHeight( chartId: string, seriesIndex: number, pointIndex: number, value: number, ): Promise; ``` Set the height of a data label. #### setDataLabelWidth ```typescript setDataLabelWidth( chartId: string, seriesIndex: number, pointIndex: number, value: number, ): Promise; ``` Set the width of a data label. #### getDataLabelTailAnchor ```typescript getDataLabelTailAnchor( chartId: string, seriesIndex: number, pointIndex: number, ): Promise<{ row: number; col: number }>; ``` Get the tail anchor point for a data label's leader line. #### setTitleFormula ```typescript setTitleFormula(chartId: string, formula: string): Promise; ``` Set chart title from a formula string. #### getTitleSubstring ```typescript getTitleSubstring(chartId: string, start: number, length: number): Promise; ``` Get a rich text substring from the chart title. #### activate ```typescript activate(chartId: string): Promise; ``` Activate (select + focus) a chart. Emits 'chart:selected' event and scrolls chart into view. ## WorksheetObjectCollection ### Methods #### get ```typescript get(id: string): Promise; ``` Get a floating object handle by ID. Returns null if not found. #### getInfo ```typescript getInfo(id: string): Promise; ``` Get summary info (with spatial fields) for a floating object. Returns null if not found. #### list ```typescript list(): Promise; ``` List all floating objects on the sheet. #### removeMany ```typescript removeMany(ids: string[]): Promise; ``` Remove multiple floating objects. Returns count of successfully removed. #### remove ```typescript remove(id: string): Promise; ``` Remove a single floating object by ID. Returns true if removed. #### bringToFront ```typescript bringToFront(id: string): Promise; ``` Bring a floating object to the front (highest z-order). #### sendToBack ```typescript sendToBack(id: string): Promise; ``` Send a floating object to the back (lowest z-order). #### bringForward ```typescript bringForward(id: string): Promise; ``` Bring a floating object forward by one layer. #### sendBackward ```typescript sendBackward(id: string): Promise; ``` Send a floating object backward by one layer. #### update ```typescript update(objectId: string, updates: Record): Promise; ``` Update arbitrary properties of a floating object. #### convertToWordArt ```typescript convertToWordArt(objectId: string, warpPreset?: TextWarpPreset): Promise; ``` Convert a text box to decorative text by applying text-effect styling. #### convertToTextBox ```typescript convertToTextBox(objectId: string): Promise; ``` Convert decorative text back to a regular text box by removing text-effect styling. #### computeObjectBounds ```typescript computeObjectBounds(objectId: string): Promise; ``` Compute pixel bounding box for a floating object (async — uses ComputeBridge). #### computeAllObjectBounds ```typescript computeAllObjectBounds(): Promise>; ``` Batch-compute pixel bounds for all floating objects on this sheet. #### group ```typescript group(ids: string[]): Promise; ``` Group multiple floating objects. Returns the group ID. #### ungroup ```typescript ungroup(groupId: string): Promise; ``` Ungroup a floating object group. ## WorksheetShapeCollection ### Methods #### get ```typescript get(id: string): Promise; ``` #### list ```typescript list(): Promise; ``` #### add ```typescript add(config: ShapeConfig): Promise; ``` #### getItemAt ```typescript getItemAt(index: number): Promise; ``` Get a shape by zero-based index. Returns null if index is out of range. ## WorksheetPictureCollection ### Methods #### get ```typescript get(id: string): Promise; ``` #### list ```typescript list(): Promise; ``` #### add ```typescript add(config: PictureConfig): Promise; ``` ## WorksheetTextBoxCollection ### Methods #### get ```typescript get(id: string): Promise; ``` #### list ```typescript list(): Promise; ``` #### add ```typescript add(config: TextBoxConfig): Promise; ``` ## WorksheetDrawingCollection ### Methods #### get ```typescript get(id: string): Promise; ``` #### list ```typescript list(): Promise; ``` #### add ```typescript add(position: Partial, options?: CreateDrawingOptions): Promise; ``` ## WorksheetEquationCollection ### Methods #### get ```typescript get(id: string): Promise; ``` #### list ```typescript list(): Promise; ``` #### add ```typescript add(config: EquationConfig): Promise; ``` #### getDefaultStyle ```typescript getDefaultStyle(): Promise; ``` #### getDefaults ```typescript getDefaults(): Promise; ``` ## WorksheetWordArtCollection ### Methods #### get ```typescript get(id: string): Promise; ``` #### list ```typescript list(): Promise; ``` #### add ```typescript add(config: CreateWordArtInput): Promise; ``` #### getDefaultConfig ```typescript getDefaultConfig(): Promise; ``` #### getDefaults ```typescript getDefaults(): Promise; ``` ## WorksheetConnectorCollection Connector collection — get/list only. add() deferred until ConnectorConfig exists. ### Methods #### get ```typescript get(id: string): Promise; ``` #### list ```typescript list(): Promise; ``` ## WorksheetFilters Sub-API for filter operations on a worksheet. ### Methods #### add ```typescript add(range: string | CellRange): Promise; ``` Add an auto-filter to the sheet. @param range - A1-style range string (e.g. "A1:D100") or a CellRange object #### applyAdvanced ```typescript applyAdvanced(options: AdvancedFilterOptions): Promise; ``` Apply an Excel Advanced Filter. Range strings are passed to Rust as entered; parsing, validation, criteria evaluation, row visibility, copy output, and viewport patches are owned by the compute layer. #### byColor ```typescript byColor(col: number, opts: FilterByColorOptions): Promise; ``` Filter a column by cell or font color. Convenience wrapper over {@link setColumnFilter} with a color predicate — rows whose column-`col` cell does not match the requested color are hidden. When `opts.filterId` is omitted, targets the first auto-filter on the sheet. @param col - Column index (0-based, absolute) @param opts - Color filter options #### get ```typescript get(): Promise; ``` Get the current auto-filter state. @returns The filter state, or null if no auto-filter is set #### clear ```typescript clear(): Promise; ``` Clear the auto-filter from the sheet. Removes all filters, not just criteria. #### setAutoFilter ```typescript setAutoFilter(range: string): Promise; ``` @deprecated Use {@link add} instead. Set an auto-filter on the sheet by parsing an A1-style range string. @param range - A1-style range string (e.g. "A1:D100") #### clearAutoFilter ```typescript clearAutoFilter(): Promise; ``` @deprecated Use {@link clear} instead. Clear the auto-filter from the sheet. Removes all filters, not just criteria. #### getAutoFilter ```typescript getAutoFilter(): Promise; ``` @deprecated Use {@link get} instead. Get the current auto-filter state. @returns The filter state, or null if no auto-filter is set #### getForRange ```typescript getForRange(range: string): Promise<{ id: string; filterKind: 'autoFilter' | 'tableFilter' | 'advancedFilter' } | null>; ``` Get the filter overlapping a range, or null if none. @param range - A1-style range string (e.g. "A1:D100") @returns Object with filter ID if found, or null #### remove ```typescript remove(filterId: string): Promise; ``` Remove a specific filter by its ID. @param filterId - Filter ID to remove #### setColumnFilter ```typescript setColumnFilter(col: number, criteria: ColumnFilterCriteria, filterId?: string): Promise; ``` Set filter criteria for a column on an auto-filter. When `filterId` is omitted, targets the first auto-filter (convenience shorthand). When provided, targets the specified filter directly. @param col - Column index (0-based) @param criteria - Filter criteria to apply @param filterId - Optional filter ID; defaults to first auto-filter #### applyDynamicFilter ```typescript applyDynamicFilter(col: number, rule: DynamicFilterRule, filterId?: string): Promise; ``` Apply a dynamic filter rule to a column on an auto-filter. Dynamic filters are pre-defined rules resolved against live data, such as "above average", "below average", or date-relative rules like "today", "this month", etc. When `filterId` is omitted, targets the first auto-filter. @param col - Column index (0-based) @param rule - Dynamic filter rule to apply @param filterId - Optional filter ID; defaults to first auto-filter #### clearColumnFilter ```typescript clearColumnFilter(col: number, filterId?: string): Promise; ``` Clear filter criteria for a column on an auto-filter. When `filterId` is omitted, targets the first auto-filter. When provided, targets the specified filter directly. @param col - Column index (0-based) @param filterId - Optional filter ID; defaults to first auto-filter #### getUniqueValues ```typescript getUniqueValues(col: number, filterId?: string): Promise; ``` Get unique values in a column (for filter dropdowns). When `filterId` is omitted, uses the first auto-filter. @param col - Column index (0-based) @param filterId - Optional filter ID; defaults to first auto-filter @returns Array of unique values #### setCriteria ```typescript setCriteria(filterId: string, col: number, criteria: ColumnFilterCriteria): Promise; ``` @deprecated Use {@link setColumnFilter} instead. Set filter criteria for a column on a specific filter by ID (advanced). @param filterId - Filter ID @param col - Column index (0-based) @param criteria - Filter criteria to apply #### clearCriteria ```typescript clearCriteria(filterId: string, col: number): Promise; ``` @deprecated Use {@link clearColumnFilter} instead. Clear filter criteria for a column on a specific filter by ID (advanced). @param filterId - Filter ID @param col - Column index (0-based) #### clearAllCriteria ```typescript clearAllCriteria(filterId: string): Promise; ``` Clear all filter criteria for a filter. Removes filters from all columns but keeps the filter structure intact. @param filterId - Filter ID #### apply ```typescript apply(filterId: string): Promise; ``` Apply a filter (Rust evaluates criteria and updates row visibility). @param filterId - Filter ID to apply #### getInfo ```typescript getInfo(filterId: string): Promise; ``` Get detailed filter info including resolved range and column filters. @param filterId - Filter ID @returns Detailed filter info, or null if not found #### getFilterUniqueValues ```typescript getFilterUniqueValues(filterId: string, col: number): Promise; ``` @deprecated Use {@link getUniqueValues} instead. Get unique values for a filter column. @param filterId - Filter ID @param col - Column index (0-based) @returns Array of unique values #### list ```typescript list(): Promise; ``` List all filters in the sheet with full detail (resolved numeric ranges and converted column-filter criteria). @returns Array of detailed filter info objects #### isEnabled ```typescript isEnabled(): Promise; ``` Whether any auto-filter exists on the sheet. @returns true if at least one filter is present #### isDataFiltered ```typescript isDataFiltered(): Promise; ``` Whether any filter on the sheet has active criteria applied. Returns true if at least one filter has non-empty column filters, meaning some rows may be hidden. @returns true if any column filter criteria are set #### listDetails ```typescript listDetails(): Promise; ``` @deprecated Use {@link list} instead, which now returns full detail. Alias kept for backward compatibility. #### getSortState ```typescript getSortState(filterId: string): Promise; ``` Get the sort state for a filter. @param filterId - Filter ID @returns Sort state, or null if no sort state set #### setSortState ```typescript setSortState(filterId: string, state: FilterSortState): Promise; ``` Set the sort state for a filter. @param filterId - Filter ID @param state - Sort state to set ## WorksheetFormControls Form controls sub-API. Values live in linked cells. Creation/update calls mutate the production FormControlManager for the workbook and use this worksheet as the sheet scope. ### Methods #### add ```typescript add(options: AddCheckboxFormControlOptions): Promise; ``` Add a checkbox or comboBox form control on this sheet. #### addCheckbox ```typescript addCheckbox(options: WorksheetCreateCheckboxOptions): Promise; ``` Add a checkbox form control on this sheet. #### addComboBox ```typescript addComboBox(options: WorksheetCreateComboBoxOptions): Promise; ``` Add a comboBox form control on this sheet. #### list ```typescript list(): FormControl[]; ``` Get all form controls on this sheet. #### get ```typescript get(controlId: string): FormControl | undefined; ``` Get a specific form control by ID. Returns undefined if not found or not on this sheet. #### getAtPosition ```typescript getAtPosition(row: number, col: number): FormControl[]; ``` Get form controls at a specific cell position (for hit testing). #### update ```typescript update(controlId: string, updates: FormControlUpdate): FormControl | undefined; ``` Update a control on this sheet. Returns undefined if the control is absent or on another sheet. #### move ```typescript move(controlId: string, newAnchor: FormControlAnchorUpdate): Promise; ``` Move a control on this sheet to a new anchor cell. #### resize ```typescript resize(controlId: string, width: number, height: number): FormControl | undefined; ``` Resize a control on this sheet. #### remove ```typescript remove(controlId: string): boolean; ``` Remove a control from this sheet. Returns true when a control was removed. ## WorksheetConditionalFormatting Sub-API for conditional formatting operations on a worksheet. ### Methods #### add ```typescript add(ranges: (string | CellRange)[], rules: CFRuleInput[]): Promise; ``` Add a new conditional format with ranges and rules. The API assigns IDs and priorities — callers provide rule configuration only. @param ranges - Cell ranges this format applies to @param rules - Rule inputs (without id/priority) @returns The created conditional format with assigned IDs and priorities #### get ```typescript get(formatId: string): Promise; ``` Get a conditional format by its ID. @param formatId - Format ID to look up @returns The conditional format, or null if not found #### has ```typescript has(formatId: string): Promise; ``` Check if a conditional format exists by ID. @param formatId - Format ID to check @returns True if the format exists #### getCount ```typescript getCount(): Promise; ``` Get the total number of conditional formats on this sheet. @returns The count of conditional formats #### update ```typescript update(formatId: string, updates: ConditionalFormatUpdate): Promise; ``` Update an existing conditional format. Supports replacing rules, ranges, and setting stopIfTrue on all rules. @param formatId - Format ID to update @param updates - Object with optional rules, ranges, and stopIfTrue #### clearRuleStyle ```typescript clearRuleStyle(formatId: string, ruleId: string): Promise; ``` Clear the style of a specific rule within a conditional format, resetting all style properties (font, fill, border, number format) to unset. @param formatId - Format ID containing the rule @param ruleId - Rule ID within the format to clear style for #### changeRuleType ```typescript changeRuleType(formatId: string, ruleId: string, newRule: CFRuleInput): Promise; ``` Change the type and configuration of a specific rule within a conditional format, preserving its ID and priority. This is the equivalent of eight changeRuleTo*() methods, unified into one type-safe call using CFRuleInput. @param formatId - Format ID containing the rule @param ruleId - Rule ID to change @param newRule - New rule configuration (type + type-specific fields) #### getItemAt ```typescript getItemAt(index: number): Promise; ``` Get a conditional format by its index in the priority-ordered list. @param index - Zero-based index @returns The conditional format at that index, or null if out of bounds #### remove ```typescript remove(formatId: string): Promise; ``` Remove a conditional format by ID. @param formatId - Format ID to remove #### removeRule ```typescript removeRule(formatId: string, ruleId: string): Promise; ``` Remove a single rule from a conditional format. If the removed rule was the last rule in the format, the conditional format itself is removed. @param formatId - Format ID containing the rule @param ruleId - Rule ID to remove #### list ```typescript list(): Promise; ``` Get all conditional formats on the sheet. @returns Array of conditional format objects #### clear ```typescript clear(): Promise; ``` Clear all conditional formats from the sheet. #### clearInRanges ```typescript clearInRanges(ranges: (string | CellRange)[]): Promise; ``` Clear conditional formats that intersect with the given ranges. @param ranges - Ranges to clear conditional formats from #### reorder ```typescript reorder(formatIds: string[]): Promise; ``` Reorder conditional formats by format ID array (first = highest priority). @param formatIds - Array of format IDs in the desired order #### cloneForPaste ```typescript cloneForPaste( sourceSheetId: string, relativeCFs: Array<{ rules: any[]; rangeOffsets: Array<{ startRowOffset: number; startColOffset: number; endRowOffset: number; endColOffset: number; }>; }>, origin: { row: number; col: number }, isCut: boolean, ): Promise; ``` Clone conditional formats from source to target with offset. Used by format painter and paste operations. @param sourceSheetId - Source sheet ID (for cut operation reference removal) @param relativeCFs - Relative CF formats with range offsets @param origin - Target paste origin (row, col) @param isCut - Whether this is a cut operation ## WorksheetValidation Sub-API for data validation operations on a worksheet. ### Methods #### set ```typescript set(address: string, rule: ValidationRule): Promise; ``` Set a validation rule on a cell or range. @param address - A1-style cell or range address (e.g. "A1", "A1:B5") @param rule - Validation rule to apply #### remove ```typescript remove(address: string): Promise; ``` Remove validation from a cell (deletes any range schema covering the cell). @param address - A1-style cell address #### get ```typescript get(address: string): Promise; ``` Get the validation rule for a cell. @param address - A1-style cell address @returns The validation rule, or null if none #### peek ```typescript peek(address: string): ValidationRule | null | undefined; ``` Synchronously read a validation rule when this sheet's validation cache is already hydrated. Returns `undefined` when the sheet cache is cold, `null` when it is warm and no rule covers the cell, or the covering rule when one exists. #### has ```typescript has(address: string): Promise; ``` Check if a cell has a validation rule. @param address - A1-style cell address @returns True if the cell has a validation rule #### getCount ```typescript getCount(): Promise; ``` Get the total number of validation rules on this sheet. @returns The count of validation rules #### getDropdownItems ```typescript getDropdownItems(address: string): Promise; ``` Get dropdown items for a cell with list validation. @param address - A1-style cell address @returns Array of dropdown item strings #### list ```typescript list(): Promise; ``` List all validation rules on the sheet. @returns Array of validation rules #### clear ```typescript clear(range?: string): Promise; ``` Clear all validation rules from the sheet. When called with a range argument, clears only rules overlapping that range (deprecated — use {@link clearInRange} for range-scoped clearing). @param range - (Optional) A1-style range string. If omitted, removes ALL rules. #### clearInRange ```typescript clearInRange(range: string | CellRange): Promise; ``` Clear validation rules that overlap a range. @param range - A1-style range string (e.g. "A1:B5") or CellRange object #### removeById ```typescript removeById(id: string): Promise; ``` Remove a validation rule by its ID. @param id - Validation rule / range schema ID #### validate ```typescript validate(row: number, col: number, value: string): Promise; ``` Validate a candidate value for a cell against the rule covering it. Stateless — does not mutate any cell. Delegates to the compute layer, which evaluates the covering schema (including `allowBlank`, type checks, and range/list constraints). @param row - Row index (0-based) @param col - Column index (0-based) @param value - Candidate value (stringified — same form committed by the editor) @returns Validation result. `errorStyle` is "none" when no rule covers the cell. #### getErrorsInRange ```typescript getErrorsInRange( startRow: number, startCol: number, endRow: number, endCol: number, ): Promise>; ``` Get cells with validation errors in a range. @param startRow - Start row (0-based) @param startCol - Start column (0-based) @param endRow - End row (0-based) @param endCol - End column (0-based) @returns Array of {row, col} for cells with errors ## WorksheetTables Sub-API for table operations on a worksheet. ### Methods #### add ```typescript add(range: string | CellRange, options?: TableOptions): Promise; ``` Create a new table from a cell range. @param range - A1-style range string (e.g. "A1:D10") or CellRange object @param options - Optional table creation settings (name, headers, style) @returns The created table information #### get ```typescript get(name: string): Promise; ``` Get a table by name. Tables are workbook-scoped, so the name is unique across all sheets. @param name - Table name @returns Table information, or null if not found #### has ```typescript has(name: string): Promise; ``` Check if a table exists by name. @param name - Table name @returns True if the table exists #### list ```typescript list(): Promise; ``` List all tables in this worksheet. @returns Array of table information objects #### getCount ```typescript getCount(): Promise; ``` Get the total number of tables on this worksheet. @returns The count of tables #### getItemAt ```typescript getItemAt(index: number): Promise; ``` Get a table by its position in the list of tables on this worksheet. @param index - Zero-based index into the table list @returns Table information, or null if the index is out of range #### getFirst ```typescript getFirst(): Promise; ``` Get the first table on this worksheet. Convenience shortcut equivalent to `getAt(0)`. @returns Table information, or null if no tables exist #### getColumnByName ```typescript getColumnByName(tableName: string, columnName: string): Promise; ``` Look up a column in a table by its header name. @param tableName - Table name @param columnName - Column header name to search for @returns The matching column, or null if not found #### remove ```typescript remove(name: string): Promise; ``` Remove a table definition, converting it back to a plain range. Cell data is preserved; only the table metadata is removed. @param name - Table name #### clear ```typescript clear(): Promise; ``` Remove all tables from this worksheet. #### rename ```typescript rename(oldName: string, newName: string): Promise; ``` Rename a table. @param oldName - Current table name @param newName - New table name #### update ```typescript update(tableName: string, updates: TableUpdateOptions): Promise; ``` Update a table's properties. @param tableName - Table name @param updates - Key-value pairs of properties to update #### getAtCell ```typescript getAtCell(address: string): Promise; ``` Get the table at a specific cell position, if one exists. @param address - A1-style cell address (e.g. "B3") @returns Table information, or null if no table exists at that cell #### clearFilters ```typescript clearFilters(tableName: string): Promise; ``` Clear all column filters on a table. @param tableName - Table name #### setStylePreset ```typescript setStylePreset(tableName: string, preset: string): Promise; ``` Set the visual style preset for a table. @param tableName - Table name @param preset - Style preset name (e.g. "TableStyleLight1") #### resize ```typescript resize(name: string, newRange: string | CellRange): Promise; ``` Resize a table to a new range. @param name - Table name @param newRange - New A1-style range string or CellRange object #### addColumn ```typescript addColumn(name: string, columnName: string, position?: number): Promise; ``` Add a column to a table. @param name - Table name @param columnName - Name for the new column @param position - Column position (0-based index). If omitted, appends to the end. #### removeColumn ```typescript removeColumn(name: string, columnIndex: number): Promise; ``` Remove a column from a table by index. @param name - Table name @param columnIndex - Column index within the table (0-based) #### toggleTotalsRow ```typescript toggleTotalsRow(name: string): Promise; ``` @deprecated Use {@link setShowTotals} instead. Toggle the totals row visibility on a table. @param name - Table name #### toggleHeaderRow ```typescript toggleHeaderRow(name: string): Promise; ``` @deprecated Use {@link setShowHeaders} instead. Toggle the header row visibility on a table. @param name - Table name #### applyAutoExpansion ```typescript applyAutoExpansion(tableName: string): Promise; ``` Apply auto-expansion to a table, extending it to include adjacent data. @param tableName - Table name #### setCalculatedColumn ```typescript setCalculatedColumn(tableName: string, colIndex: number, formula: string): Promise; ``` Set a calculated column formula for all data cells in a table column. @param tableName - Table name @param colIndex - Column index within the table (0-based) @param formula - The formula to set (e.g. "=[@Price]*[@Quantity]") #### clearCalculatedColumn ```typescript clearCalculatedColumn(tableName: string, colIndex: number): Promise; ``` Clear the calculated column formula from a table column, replacing with empty values. @param tableName - Table name @param colIndex - Column index within the table (0-based) #### getDataBodyRange ```typescript getDataBodyRange(name: string): Promise; ``` Get the A1-notation range covering the data body of a table (excludes header and totals rows). @param name - Table name @returns A1-notation range string, or null if the table has no data body rows #### getHeaderRowRange ```typescript getHeaderRowRange(name: string): Promise; ``` Get the A1-notation range covering the header row of a table. @param name - Table name @returns A1-notation range string, or null if the table has no header row #### getTotalRowRange ```typescript getTotalRowRange(name: string): Promise; ``` Get the A1-notation range covering the totals row of a table. @param name - Table name @returns A1-notation range string, or null if the table has no totals row #### addRow ```typescript addRow(tableName: string, index?: number, values?: CellValue[]): Promise; ``` Add a data row to a table. @param tableName - Table name @param index - Row index within the data body (0-based). If omitted, appends to the end. @param values - Optional cell values for the new row #### deleteRow ```typescript deleteRow(tableName: string, index: number): Promise; ``` Delete a data row from a table. @param tableName - Table name @param index - Row index within the data body (0-based) #### deleteRows ```typescript deleteRows(tableName: string, indices: number[]): Promise; ``` Delete multiple data rows from a table by their data-body-relative indices. Rows are deleted in descending index order to avoid index shifting. @param tableName - Table name @param indices - Array of row indices within the data body (0-based) #### deleteRowsAt ```typescript deleteRowsAt(tableName: string, index: number, count?: number): Promise; ``` Delete one or more contiguous data rows from a table starting at `index`. @param tableName - Table name @param index - Starting row index within the data body (0-based) @param count - Number of rows to delete (default 1) #### getRowCount ```typescript getRowCount(tableName: string): Promise; ``` Get the number of data rows in a table (excludes header and totals rows). @param tableName - Table name @returns Number of data rows #### getRowRange ```typescript getRowRange(tableName: string, index: number): Promise; ``` Get the A1-notation range for a specific data row. @param tableName - Table name @param index - Row index within the data body (0-based) @returns A1-notation range string #### getRowValues ```typescript getRowValues(tableName: string, index: number): Promise; ``` Get the cell values of a specific data row. @param tableName - Table name @param index - Row index within the data body (0-based) @returns Array of cell values #### setRowValues ```typescript setRowValues(tableName: string, index: number, values: CellValue[]): Promise; ``` Set the cell values of a specific data row. @param tableName - Table name @param index - Row index within the data body (0-based) @param values - Cell values to set #### getColumnDataBodyRange ```typescript getColumnDataBodyRange(tableName: string, columnIndex: number): Promise; ``` Get the A1-notation range covering the data body cells of a table column. @param tableName - Table name @param columnIndex - Column index within the table (0-based) @returns A1-notation range string, or null if no data body rows #### getColumnHeaderRange ```typescript getColumnHeaderRange(tableName: string, columnIndex: number): Promise; ``` Get the A1-notation range covering the header cell of a table column. @param tableName - Table name @param columnIndex - Column index within the table (0-based) @returns A1-notation range string, or null if no header row #### getColumnRange ```typescript getColumnRange(tableName: string, columnIndex: number): Promise; ``` Get the A1-notation range covering the entire table column (header + data + totals). @param tableName - Table name @param columnIndex - Column index within the table (0-based) @returns A1-notation range string, or null if column does not exist #### getColumnTotalRange ```typescript getColumnTotalRange(tableName: string, columnIndex: number): Promise; ``` Get the A1-notation range covering the totals cell of a table column. @param tableName - Table name @param columnIndex - Column index within the table (0-based) @returns A1-notation range string, or null if no totals row #### getColumnValues ```typescript getColumnValues(tableName: string, columnIndex: number): Promise; ``` Get the cell values of a table column (data body only). @param tableName - Table name @param columnIndex - Column index within the table (0-based) @returns Array of cell values #### setColumnValues ```typescript setColumnValues(tableName: string, columnIndex: number, values: CellValue[]): Promise; ``` Set the cell values of a table column (data body only). @param tableName - Table name @param columnIndex - Column index within the table (0-based) @param values - Cell values to set #### setHighlightFirstColumn ```typescript setHighlightFirstColumn(tableName: string, value: boolean): Promise; ``` Set whether the first column is highlighted. @param tableName - Table name @param value - Whether to highlight the first column #### setHighlightLastColumn ```typescript setHighlightLastColumn(tableName: string, value: boolean): Promise; ``` Set whether the last column is highlighted. @param tableName - Table name @param value - Whether to highlight the last column #### setShowBandedColumns ```typescript setShowBandedColumns(tableName: string, value: boolean): Promise; ``` Set whether banded columns are shown. @param tableName - Table name @param value - Whether to show banded columns #### setShowBandedRows ```typescript setShowBandedRows(tableName: string, value: boolean): Promise; ``` Set whether banded rows are shown. @param tableName - Table name @param value - Whether to show banded rows #### setShowFilterButton ```typescript setShowFilterButton(tableName: string, value: boolean): Promise; ``` Set whether filter buttons are shown on the header row. @param tableName - Table name @param value - Whether to show filter buttons #### setShowHeaders ```typescript setShowHeaders(tableName: string, visible: boolean): Promise; ``` Set whether the header row is visible. @param tableName - Table name @param visible - Whether to show the header row #### setShowTotals ```typescript setShowTotals(tableName: string, visible: boolean): Promise; ``` Set whether the totals row is visible. @param tableName - Table name @param visible - Whether to show the totals row #### applyIconFilter ```typescript applyIconFilter( tableName: string, columnIndex: number, icon: { set: string; index: number }, ): Promise; ``` Apply an icon filter to a table column. Filters rows by conditional formatting icon: only rows whose evaluated CF icon matches the specified icon set and index are shown. Requires an icon set CF rule applied to the column's range. @param tableName - Table name @param columnIndex - Column index within the table (0-based) @param icon - Icon to filter by: set name (e.g. "3Arrows") and index (0-based) #### getAutoFilter ```typescript getAutoFilter(tableName: string): Promise; ``` Get the auto-filter associated with a table. @param tableName - Table name @returns Filter information, or null if the table has no associated filter #### getRows ```typescript getRows(tableName: string): Promise; ``` Get a collection-like wrapper around the table's data rows. The returned object delegates to the existing row methods on this API. The `count` property is a snapshot taken at call time and does not live-update. @param tableName - Table name @returns A TableRowCollection object ## WorksheetPivots Sub-API for pivot table operations on a worksheet. ### Methods #### add ```typescript add(config: PivotCreateConfig): Promise; ``` Create a new pivot table on this worksheet. Accepts either: - **Simple config**: `{ name, dataSource: "Sheet1!A1:D100", rowFields: ["Region"], ... }` Fields are auto-detected from source headers, placements are generated from field arrays. - **Full config**: `{ name, sourceSheetName, sourceRange, fields, placements, filters, ... }` Direct wire format — no conversion needed. @param config - Pivot table configuration @returns The created pivot table configuration (with generated id, timestamps) #### addWithSheet ```typescript addWithSheet( sheetName: string, config: PivotCreateConfig, ): Promise<{ sheetId: string; config: PivotTableConfig }>; ``` Atomically create a new sheet AND a pivot table on it. Both operations happen in a single transaction for undo atomicity. Accepts the same simple or full config formats as `add()`. @param sheetName - Name for the new sheet @param config - Pivot table configuration @returns The new sheet ID and the created pivot config #### remove ```typescript remove(name: string): Promise; ``` Remove a pivot table by name. @param name - Pivot table name #### clear ```typescript clear(): Promise; ``` Remove all pivot tables from this worksheet. #### rename ```typescript rename(name: string, newName: string): Promise; ``` Rename a pivot table by name. @param name - Pivot table name @param newName - New name for the pivot table #### list ```typescript list(): Promise; ``` List all pivot tables on this worksheet. @returns Array of pivot table summary information #### get ```typescript get(name: string): Promise; ``` Get a pivot table handle by name. @param name - Pivot table name @returns A handle for the pivot table, or null if not found #### getInfo ```typescript getInfo(name: string): Promise; ``` Get plain data information about a pivot table by name. Unlike `get()` which returns a handle with bound methods, this returns a plain data object suitable for serialization and inspection. @param name - Pivot table name @returns Pivot table info, or null if not found #### has ```typescript has(name: string): Promise; ``` Check if a pivot table exists by name. @param name - Pivot table name @returns True if the pivot table exists #### getCount ```typescript getCount(): Promise; ``` Get the total number of pivot tables on this worksheet. @returns The count of pivot tables #### addPlacement ```typescript addPlacement(pivotId: string, spec: PivotPlacementSpec): Promise; ``` #### updatePlacement ```typescript updatePlacement( pivotId: string, placementId: PlacementId, patch: PivotPlacementPatch, ): Promise; ``` #### removePlacement ```typescript removePlacement(pivotId: string, placementId: PlacementId): Promise; ``` #### movePlacement ```typescript movePlacement( pivotId: string, placementId: PlacementId, toArea: PivotFieldArea, toPosition: number, ): Promise; ``` #### renameValuePlacement ```typescript renameValuePlacement( pivotId: string, placementId: PlacementId, displayName: string | null, ): Promise; ``` #### setSortByValue ```typescript setSortByValue( pivotId: string, axisPlacementId: PlacementId, valuePlacementId: PlacementId, config: { order: SortOrder; columnKey?: string } | null, ): Promise; ``` #### addField ```typescript addField( name: string, fieldId: string, area: PivotFieldArea, options?: { position?: number; aggregateFunction?: AggregateFunction; sortOrder?: SortOrder; displayName?: string; showValuesAs?: ShowValuesAsConfig; }, ): Promise; ``` Add a field to a pivot table area, resolved by pivot name. @deprecated Legacy facade. Prefer `addPlacement(pivotId, spec)`. @param name - Pivot table name @param fieldId - Field ID to add @param area - Target area (row, column, value, or filter) @param options - Optional configuration (position, aggregateFunction, sortOrder, displayName) #### removeField ```typescript removeField(name: string, fieldId: string, area: PivotFieldArea): Promise; ``` Remove a field from a pivot table area, resolved by pivot name. @deprecated Legacy facade. Prefer `removePlacement(pivotId, placementId)`. @param name - Pivot table name @param fieldId - Field ID to remove @param area - Area to remove the field from #### moveField ```typescript moveField( name: string, fieldId: string, fromArea: PivotFieldArea, toArea: PivotFieldArea, toPosition: number, ): Promise; ``` Move a field to a different area or position, resolved by pivot name. @deprecated Legacy facade. Prefer `movePlacement(pivotId, placementId, toArea, toPosition)`. @param name - Pivot table name @param fieldId - Field ID to move @param fromArea - Source area @param toArea - Target area @param toPosition - Target position within the area #### setAggregateFunction ```typescript setAggregateFunction( pivotId: string, placementId: PlacementId, aggregateFunction: AggregateFunction, ): Promise; ``` #### setShowValuesAs ```typescript setShowValuesAs( pivotId: string, placementId: PlacementId, showValuesAs: ShowValuesAsConfig | null, ): Promise; ``` #### setSortOrder ```typescript setSortOrder( pivotId: string, placementId: PlacementId, sortOrder: SortOrder | null, ): Promise; ``` #### resetPlacement ```typescript resetPlacement(pivotId: string, placementId: PlacementId): Promise; ``` #### setAggregateFunctionLegacy ```typescript setAggregateFunctionLegacy( name: string, fieldId: string, aggregateFunction: AggregateFunction, ): Promise; ``` Set the aggregate function for a value field, resolved by pivot name. @deprecated Legacy facade. Prefer `setAggregateFunction(pivotId, placementId, aggregateFunction)`. @param name - Pivot table name @param fieldId - Field ID (must be in the 'value' area) @param aggregateFunction - New aggregation function #### setShowValuesAsLegacy ```typescript setShowValuesAsLegacy( name: string, fieldId: string, showValuesAs: ShowValuesAsConfig | null, ): Promise; ``` Set the "Show Values As" calculation for a value field. Only applies to fields in the 'value' area. Pass null to clear. @deprecated Legacy facade. Prefer `setShowValuesAs(pivotId, placementId, showValuesAs)`. @param name - Pivot table name @param fieldId - Field ID (must be in the 'value' area) @param showValuesAs - ShowValuesAs configuration, or null to clear #### setSortOrderLegacy ```typescript setSortOrderLegacy(name: string, fieldId: string, sortOrder: SortOrder): Promise; ``` Set the sort order for a row or column field, resolved by pivot name. @deprecated Legacy facade. Prefer `setSortOrder(pivotId, placementId, sortOrder)`. @param name - Pivot table name @param fieldId - Field ID (must be in 'row' or 'column' area) @param sortOrder - Sort order ('asc', 'desc', or 'none') #### setFilter ```typescript setFilter(name: string, fieldId: string, filter: Omit): Promise; ``` Set (add or update) a filter on a field, resolved by pivot name. @param name - Pivot table name @param fieldId - Field ID to filter @param filter - Filter configuration (without fieldId) #### removeFilter ```typescript removeFilter(name: string, fieldId: string): Promise; ``` Remove a filter from a field, resolved by pivot name. @param name - Pivot table name @param fieldId - Field ID whose filter should be removed #### resetField ```typescript resetField(name: string, fieldId: string): Promise; ``` Reset a field placement to defaults, resolved by pivot name. @deprecated Legacy facade. Prefer `resetPlacement(pivotId, placementId)`. @param name - Pivot table name @param fieldId - Field ID to reset #### setLayout ```typescript setLayout(name: string, layout: Partial): Promise; ``` Set layout options for a pivot table, resolved by pivot name. @param name - Pivot table name @param layout - Partial layout configuration to merge with existing #### setStyle ```typescript setStyle(name: string, style: Partial): Promise; ``` Set style options for a pivot table, resolved by pivot name. @param name - Pivot table name @param style - Partial style configuration to merge with existing #### detectFields ```typescript detectFields( sourceSheetId: string, range: { startRow: number; startCol: number; endRow: number; endCol: number }, ): Promise; ``` Detect fields from source data for pivot table creation. @param sourceSheetId - Sheet ID containing the source data @param range - Source data range @returns Array of detected pivot fields #### compute ```typescript compute(name: string, forceRefresh?: boolean): Promise; ``` Compute a pivot table result by name (uses cache if available). @param name - Pivot table name @param forceRefresh - Force recomputation ignoring cache @returns Computed pivot table result #### queryPivot ```typescript queryPivot( pivotName: string, filters?: Record, ): Promise; ``` Query a pivot table by name, returning flat records optionally filtered by dimension values. Eliminates the need to manually traverse hierarchical PivotTableResult trees. @param pivotName - Pivot table name @param filters - Optional dimension filters: field name → value or array of values to include @returns Flat query result, or null if pivot not found or not computable #### refresh ```typescript refresh(name: string): Promise; ``` Refresh a pivot table by name (recompute without cache). @param name - Pivot table name #### refreshAll ```typescript refreshAll(): Promise; ``` Refresh all pivot tables on this worksheet. #### getDrillDownData ```typescript getDrillDownData(name: string, rowKey: string, columnKey: string): Promise; ``` Get drill-down data for a pivot table cell, resolved by pivot name. @param name - Pivot table name @param rowKey - Row key from the pivot result @param columnKey - Column key from the pivot result @returns Source data rows that contribute to this cell #### addCalculatedField ```typescript addCalculatedField(pivotId: string, field: PivotCalculatedFieldSpec): Promise; ``` #### addCalculatedFieldAndPlace ```typescript addCalculatedFieldAndPlace( pivotId: string, field: PivotCalculatedFieldSpec, placement: Omit, ): Promise; ``` #### updateCalculatedField ```typescript updateCalculatedField( pivotId: string, calculatedFieldId: CalculatedFieldId, updates: Partial>, ): Promise; ``` #### removeCalculatedField ```typescript removeCalculatedField(pivotId: string, calculatedFieldId: CalculatedFieldId): Promise; ``` #### addCalculatedFieldLegacy ```typescript addCalculatedFieldLegacy(name: string, field: CalculatedField): Promise; ``` Add a calculated field to a pivot table, resolved by pivot name. @deprecated Legacy facade. Prefer define-only `addCalculatedField(pivotId, spec)`. @param name - Pivot table name @param field - Calculated field definition (fieldId, name, formula) #### removeCalculatedFieldLegacy ```typescript removeCalculatedFieldLegacy(name: string, fieldId: string): Promise; ``` Remove a calculated field from a pivot table, resolved by pivot name. @deprecated Legacy facade. Prefer `removeCalculatedField(pivotId, calculatedFieldId)`. @param name - Pivot table name @param fieldId - Calculated field ID to remove #### updateCalculatedFieldLegacy ```typescript updateCalculatedFieldLegacy( name: string, fieldId: string, updates: Partial>, ): Promise; ``` Update a calculated field on a pivot table, resolved by pivot name. @deprecated Legacy facade. Prefer `updateCalculatedField(pivotId, calculatedFieldId, patch)`. @param name - Pivot table name @param fieldId - Calculated field ID to update @param updates - Partial updates (name and/or formula) #### getRange ```typescript getRange(name: string): Promise; ``` Get the full range occupied by the rendered pivot table, resolved by pivot name. @param name - Pivot table name @returns CellRange covering the entire pivot table, or null if not computed #### getDataBodyRange ```typescript getDataBodyRange(name: string): Promise; ``` Get the range of the data body, resolved by pivot name. @param name - Pivot table name @returns CellRange covering the data body, or null if not computed #### getColumnLabelRange ```typescript getColumnLabelRange(name: string): Promise; ``` Get the range of column label headers, resolved by pivot name. @param name - Pivot table name @returns CellRange covering the column headers, or null if not computed #### getRowLabelRange ```typescript getRowLabelRange(name: string): Promise; ``` Get the range of row label headers, resolved by pivot name. @param name - Pivot table name @returns CellRange covering the row headers, or null if not computed #### getFilterAxisRange ```typescript getFilterAxisRange(name: string): Promise; ``` Get the range of the filter area, resolved by pivot name. @param name - Pivot table name @returns CellRange covering filter dropdowns, or null if no filter fields #### getAllPivotItems ```typescript getAllPivotItems(name: string): Promise; ``` Get pivot items for all placed fields, resolved by pivot name. @param name - Pivot table name @returns Items grouped by field #### setPivotItemVisibility ```typescript setPivotItemVisibility( name: string, fieldId: string, visibleItems: Record, ): Promise; ``` Set visibility of specific items in a field, resolved by pivot name. @param name - Pivot table name @param fieldId - Field ID @param visibleItems - Map of item value (as string) to visibility boolean #### toggleExpanded ```typescript toggleExpanded(name: string, headerKey: string, isRow: boolean): Promise; ``` Toggle expansion state for a header, resolved by pivot name. @param name - Pivot table name @param headerKey - Header key to toggle @param isRow - Whether this is a row header (true) or column header (false) @returns The new expansion state (true = expanded, false = collapsed) #### setAllExpanded ```typescript setAllExpanded(name: string, expanded: boolean): Promise; ``` Set expansion state for all headers, resolved by pivot name. @param name - Pivot table name @param expanded - Whether all headers should be expanded (true) or collapsed (false) #### getExpansionState ```typescript getExpansionState(name: string): Promise; ``` Get the current expansion state, resolved by pivot name. @param name - Pivot table name @returns Expansion state with expandedRows and expandedColumns maps #### getDataSourceType ```typescript getDataSourceType(name: string): Promise; ``` Get the data source type of a pivot table (range, table, or external). @param name - Pivot table name @returns The data source type #### setDataSource ```typescript setDataSource(name: string, dataSource: string): Promise; ``` Change the source data range for a pivot table without refreshing it. `dataSource` must be a qualified A1 range such as `Sheet1!A1:D100` or `'Bob''s Data'!A1:D100`. #### getAllowMultipleFiltersPerField ```typescript getAllowMultipleFiltersPerField(name: string): Promise; ``` Get whether multiple filters per field are allowed on a pivot table. @param name - Pivot table name @returns True if multiple filters per field are allowed #### setAllowMultipleFiltersPerField ```typescript setAllowMultipleFiltersPerField(name: string, allow: boolean): Promise; ``` Set whether multiple filters per field are allowed on a pivot table. @param name - Pivot table name @param allow - True to allow multiple filters per field #### getAutoFormat ```typescript getAutoFormat(name: string): Promise; ``` Get whether the pivot table auto-formats when refreshed. @param name - Pivot table name @returns True if auto-formatting is enabled #### setAutoFormat ```typescript setAutoFormat(name: string, autoFormat: boolean): Promise; ``` Set whether the pivot table auto-formats when refreshed. @param name - Pivot table name @param autoFormat - True to enable auto-formatting #### getPreserveFormatting ```typescript getPreserveFormatting(name: string): Promise; ``` Get whether custom formatting is preserved on refresh. @param name - Pivot table name @returns True if custom formatting is preserved #### setPreserveFormatting ```typescript setPreserveFormatting(name: string, preserve: boolean): Promise; ``` Set whether custom formatting is preserved on refresh. @param name - Pivot table name @param preserve - True to preserve custom formatting #### getDataHierarchy ```typescript getDataHierarchy(name: string, row: number, col: number): Promise; ``` Identify which data hierarchy (value field) a pivot cell belongs to. Given an output cell position (row, col) in the rendered pivot table, returns information about the value field (aggregate) that produced the cell. @param name - Pivot table name @param row - 0-based row index in the rendered pivot table @param col - 0-based column index in the rendered pivot table @returns Data hierarchy info, or null if the cell is not a data cell #### getPivotItems ```typescript getPivotItems(name: string, axis: 'row' | 'column', row: number, col: number): Promise; ``` Identify which row/column items intersect at a given pivot output cell. Returns the pivot items (group values) from the specified axis that define the cell's position in the pivot table. @param name - Pivot table name @param axis - 'row' or 'column' @param row - 0-based row index in the rendered pivot table @param col - 0-based column index in the rendered pivot table @returns Array of pivot item locations, or null if the cell is outside the data area #### getEnableMultipleFilterItems ```typescript getEnableMultipleFilterItems(name: string, fieldId: string): Promise; ``` Get whether multiple filter items per field are enabled for a specific field. When enabled, multiple `PivotFilter` entries can exist for the same field, combined with AND logic during evaluation. @param name - Pivot table name @param fieldId - Field ID to check @returns True if multiple filter items are enabled for this field #### setEnableMultipleFilterItems ```typescript setEnableMultipleFilterItems(name: string, fieldId: string, enabled: boolean): Promise; ``` Set whether multiple filter items per field are enabled for a specific field. When enabled, multiple `PivotFilter` entries can exist for the same field, combined with AND logic during evaluation. @param name - Pivot table name @param fieldId - Field ID to configure @param enabled - True to enable multiple filter items ## WorksheetSlicers Sub-API for slicer operations on a worksheet. ### Methods #### add ```typescript add(config: SlicerConfig): Promise; ``` Create a new slicer on this worksheet. @param config - Slicer configuration (table, column, position) @returns The created slicer with full state #### remove ```typescript remove(slicerId: string): Promise; ``` Remove a slicer from this worksheet. @param slicerId - ID of the slicer to remove #### clear ```typescript clear(): Promise; ``` Remove all slicers from this worksheet. #### list ```typescript list(): Promise; ``` List all slicers on this worksheet. @returns Array of slicer summary information #### has ```typescript has(slicerId: string): Promise; ``` Check if a slicer exists by ID. @param slicerId - ID of the slicer @returns True if the slicer exists #### getCount ```typescript getCount(): Promise; ``` Get the total number of slicers on this worksheet. @returns The count of slicers #### get ```typescript get(slicerId: string): Promise; ``` Get a slicer by ID, including full state. @param slicerId - ID of the slicer @returns Full slicer state, or null if not found #### getByName ```typescript getByName(name: string): Promise; ``` Find a slicer by its name, or null if not found. @param name - Slicer name to search for @returns Full slicer state, or null if no slicer matches #### getItemAt ```typescript getItemAt(index: number): Promise; ``` Get a slicer by its zero-based index in the list. @param index - Zero-based index of the slicer @returns Slicer summary information, or null if index is out of range #### getItems ```typescript getItems(slicerId: string): Promise; ``` Get the items (values) available in a slicer. @param slicerId - ID of the slicer @returns Array of slicer items with selection state #### getItem ```typescript getItem(slicerId: string, key: CellValue): Promise; ``` Get a slicer item by its string key. Throws if no item matches — use when you expect the item to exist. For conditional checks, use {@link getItemOrNullObject} which returns null instead. @param slicerId - ID of the slicer @param key - The value to look up (matched via string coercion) @returns The matching slicer item @throws KernelError if no item matches the key #### getItemOrNullObject ```typescript getItemOrNullObject(slicerId: string, key: CellValue): Promise; ``` Get a slicer item by its string key, or null if not found. Non-throwing alternative to {@link getItem} — use for conditional checks. @param slicerId - ID of the slicer @param key - The value to look up (matched via string coercion) @returns The matching slicer item, or null if not found #### setSelection ```typescript setSelection(slicerId: string, selectedItems: CellValue[]): Promise; ``` Set the selected items in a slicer, replacing any existing selection. @param slicerId - ID of the slicer @param selectedItems - Array of values to select #### clearSelection ```typescript clearSelection(slicerId: string): Promise; ``` Clear all selections in a slicer (show all items). @param slicerId - ID of the slicer #### duplicate ```typescript duplicate(slicerId: string, offset?: { x?: number; y?: number }): Promise; ``` Duplicate a slicer with an optional position offset. @param slicerId - ID of the slicer to duplicate @param offset - Position offset in pixels (defaults to { x: 20, y: 20 }) @returns The ID of the newly created slicer #### update ```typescript update(slicerId: string, updates: Partial): Promise; ``` Update a slicer's configuration. @param slicerId - ID of the slicer @param updates - Partial configuration updates #### getState ```typescript getState(slicerId: string): Promise; ``` Get the enriched runtime state of a slicer. @param slicerId - ID of the slicer @returns Enriched slicer state including computed items and connection status ## WorksheetSparklines Sub-API for sparkline operations on a worksheet. ### Methods #### add ```typescript add( cell: string, dataRange: string | CellRange, type: SparklineType, options?: CreateSparklineOptions, ): Promise; ``` Add a sparkline to a cell (A1 address form). @param cell - A1-style cell address (e.g. "B1") @param dataRange - Data range (A1-style string or CellRange) @param type - Sparkline type (line, column, winLoss) @param options - Optional creation settings @returns The created sparkline #### addGroup ```typescript addGroup( cells: Array<{ row: number; col: number }>, dataRanges: CellRange[], type: SparklineType, options?: CreateSparklineGroupOptions, ): Promise; ``` Add a group of sparklines with shared settings. @param cells - Array of cell positions @param dataRanges - Array of data ranges (must match cells length) @param type - Sparkline type @param options - Optional group creation settings @returns The created sparkline group #### get ```typescript get(sparklineId: string): Promise; ``` Get a sparkline by ID. @param sparklineId - Sparkline identifier @returns The sparkline, or null if not found #### getAtCell ```typescript getAtCell(address: string): Promise; ``` Get the sparkline at a specific cell. @param address - A1-style cell address (e.g. "B1") @returns The sparkline at the cell, or null if none #### list ```typescript list(): Promise; ``` List all sparklines in the worksheet. @returns Array of all sparklines #### getGroup ```typescript getGroup(groupId: string): Promise; ``` Get a sparkline group by ID. @param groupId - Group identifier @returns The sparkline group, or null if not found #### listGroups ```typescript listGroups(): Promise; ``` List all sparkline groups in the worksheet. @returns Array of all sparkline groups #### update ```typescript update(sparklineId: string, updates: Partial): Promise; ``` Update a sparkline's settings. @param sparklineId - Sparkline identifier @param updates - Partial sparkline properties to update #### updateGroup ```typescript updateGroup(groupId: string, updates: Partial): Promise; ``` Update a sparkline group's settings (applies to all members). @param groupId - Group identifier @param updates - Partial group properties to update #### remove ```typescript remove(sparklineId: string): Promise; ``` Remove a sparkline. @param sparklineId - Sparkline identifier #### removeGroup ```typescript removeGroup(groupId: string): Promise; ``` Remove a sparkline group and all its member sparklines. @param groupId - Group identifier #### clearInRange ```typescript clearInRange(range: string | CellRange): Promise; ``` Clear all sparklines whose cell falls within a range. @param range - A1-style range string or CellRange object #### clear ```typescript clear(): Promise; ``` Clear all sparklines in the worksheet. #### clearAll ```typescript clearAll(): Promise; ``` Clear all sparklines in the worksheet. @deprecated Use `clear()` instead. #### addToGroup ```typescript addToGroup(sparklineId: string, groupId: string): Promise; ``` Add a sparkline to a group. @param sparklineId - Sparkline identifier @param groupId - Group identifier #### removeFromGroup ```typescript removeFromGroup(sparklineId: string): Promise; ``` Remove a sparkline from its group (becomes standalone). @param sparklineId - Sparkline identifier #### ungroupAll ```typescript ungroupAll(groupId: string): Promise; ``` Ungroup all sparklines in a group (members become standalone). @param groupId - Group identifier @returns IDs of sparklines that were ungrouped #### has ```typescript has(address: string): Promise; ``` Check if a cell has a sparkline. @param address - A1-style cell address (e.g. "B1") @returns True if the cell has a sparkline #### getCount ```typescript getCount(): Promise; ``` Get the total number of sparklines on this sheet. @returns The count of sparklines #### getWithDataInRange ```typescript getWithDataInRange(range: string | CellRange): Promise; ``` Get sparklines whose data range intersects with a given range. @param range - A1-style range string or CellRange object @returns Sparklines with data in the range ## WorksheetComments Sub-API for comment and note operations on a worksheet. ### Methods #### addNote ```typescript addNote(cell: string, options: { text: string; author?: string }): Promise; ``` Add a note to a cell (options object form). @param cell - A1-style cell address (e.g. "A1") @param options - Note text and optional author #### setNote ```typescript setNote(address: string, text: string, author?: string): Promise; ``` @deprecated Use the options-object overload instead. Set the note for a cell (overwrites any existing note). @param address - A1-style cell address (e.g. "A1") @param text - Note text @param author - Optional author name (defaults to 'api') @deprecated Use the options-object overload instead. #### getNote ```typescript getNote(address: string): Promise; ``` Get the note for a cell as a Note object. @param address - A1-style cell address @returns The Note object, or null if no note #### removeNote ```typescript removeNote(address: string): Promise; ``` Remove the note from a cell. @param address - A1-style cell address #### getCount ```typescript getCount(): Promise; ``` Get the total number of comments (notes + threaded) on this worksheet. #### noteCount ```typescript noteCount(): Promise; ``` Get the number of notes (legacy comments) in the worksheet. @returns The count of notes only (excludes threaded comments) #### listNotes ```typescript listNotes(): Promise; ``` List all notes (legacy comments) in the worksheet. @returns Array of notes #### getNoteAt ```typescript getNoteAt(index: number): Promise; ``` Get a note by index from the list of all notes. @param index - Zero-based index into the notes list @returns The Note at that index, or null if out of range #### setNoteVisible ```typescript setNoteVisible(address: string, visible: boolean): Promise; ``` Set the visibility of a note at the given cell address. @param address - A1-style cell address @param visible - Whether the note should be visible #### setNoteHeight ```typescript setNoteHeight(address: string, height: number): Promise; ``` Set the height of a note callout box in points. @param address - A1-style cell address @param height - Height in points #### setNoteWidth ```typescript setNoteWidth(address: string, width: number): Promise; ``` Set the width of a note callout box in points. @param address - A1-style cell address @param width - Width in points #### add ```typescript add(cell: string, options: { text: string; author?: string }): Promise; ``` Add a threaded comment to a cell (options object form). @param cell - A1-style cell address @param options - Comment text and optional author #### update ```typescript update(commentId: string, updates: CommentUpdate): Promise; ``` Update an existing comment. @param commentId - Comment identifier @param updates - Object with fields to update (text, mentions, or both) #### remove ```typescript remove(commentId: string): Promise; ``` Remove a threaded comment by ID. @param commentId - Comment identifier #### resolveThread ```typescript resolveThread(threadId: string, resolved: boolean): Promise; ``` Set the resolved state of a comment thread. @param threadId - Thread identifier (cell ID) @param resolved - Whether the thread should be marked as resolved #### list ```typescript list(): Promise; ``` List all comments in the worksheet. @returns Array of all comments #### getForCell ```typescript getForCell(address: string): Promise; ``` Get all comments for a specific cell. @param address - A1-style cell address @returns Array of comments for the cell #### addReply ```typescript addReply(commentId: string, text: string, author: string): Promise; ``` Add a reply to an existing comment. @param commentId - ID of the comment to reply to @param text - Reply text @param author - Author name or identifier @returns The created reply comment #### convertNoteToThread ```typescript convertNoteToThread(commentId: string): Promise; ``` Convert a legacy note into a modern threaded comment. Flips `commentType` to `'threadedComment'`, clears note callout geometry (`noteHeight`/`noteWidth`/`visible`/`shapeId`), and assigns `threadId`. Idempotent on a comment that is already a threaded comment. @param commentId - ID of the note to convert @returns The updated comment so the caller can re-render in thread mode #### getThread ```typescript getThread(commentId: string): Promise; ``` Get all comments in a thread (root + replies), sorted by createdAt. @param commentId - ID of any comment in the thread @returns Array of comments in the thread #### getById ```typescript getById(commentId: string): Promise; ``` Get a single comment by its ID. @param commentId - Comment identifier @returns The comment, or null if not found #### getLocation ```typescript getLocation(commentId: string): Promise; ``` Get the A1-style cell address for a comment. Resolves the comment's internal cell reference (CellId) to a human-readable address like "A1", "B3", etc. @param commentId - Comment identifier @returns The A1-style cell address, or null if the comment doesn't exist #### getParentByReplyId ```typescript getParentByReplyId(replyId: string): Promise; ``` Get the parent comment for a reply. @param replyId - ID of the reply comment @returns The parent comment, or null if not found or not a reply #### getReplyCount ```typescript getReplyCount(commentId: string): Promise; ``` Get the number of replies in a thread (excluding the root comment). @param commentId - ID of any comment in the thread @returns The reply count #### getReplyAt ```typescript getReplyAt(commentId: string, index: number): Promise; ``` Get a reply at a specific index within a thread (zero-based, excludes root). @param commentId - ID of any comment in the thread @param index - Zero-based index into the replies @returns The reply comment, or null if out of range #### getNoteLocation ```typescript getNoteLocation(address: string): Promise; ``` Get the A1-style cell address for a note. @param address - A1-style cell address @returns The A1-style cell address, or null if no note exists at that address #### hasComment ```typescript hasComment(address: string): Promise; ``` Check if a cell has any comments. @param address - A1-style cell address @returns True if the cell has at least one comment #### removeForCell ```typescript removeForCell(address: string): Promise; ``` Remove all comments on a cell. @param address - A1-style cell address @returns The number of comments removed #### clear ```typescript clear(): Promise; ``` Clear all comments on the worksheet. #### clean ```typescript clean(): Promise; ``` Remove orphaned comments (comments referencing non-existent cells). @returns The number of orphaned comments removed ## WorksheetCustomProperties WorksheetCustomProperties — Sub-API for sheet-level custom properties. Provides a key-value store scoped to a single worksheet. Properties are persisted via sheet settings as a JSON-serialized object. ### Methods #### get ```typescript get(key: string): Promise; ``` Get a custom property value by key. @param key - Property key @returns The property value, or undefined if not set #### set ```typescript set(key: string, value: string | number | boolean): Promise; ``` Set a custom property. @param key - Property key @param value - Property value (string, number, or boolean) #### delete ```typescript delete(key: string): Promise; ``` Delete a custom property. @param key - Property key to delete @returns True if the property existed and was deleted, false otherwise #### getAll ```typescript getAll(): Promise>; ``` Get all custom properties as a record. @returns Record of all custom property key-value pairs #### count ```typescript count(): Promise; ``` Get the count of custom properties. @returns Number of custom properties currently set ## WorksheetHyperlinks WorksheetHyperlinks — Sub-API for cell hyperlink operations. Provides methods to set, get, and remove hyperlinks on cells. ### Methods #### set ```typescript set(address: string, url: string): Promise; ``` Set a hyperlink on a cell. @param address - A1-style cell address (e.g. "A1") @param url - Hyperlink URL #### get ```typescript get(address: string): Promise; ``` Get the hyperlink URL for a cell. @param address - A1-style cell address @returns The hyperlink URL, or null if no hyperlink #### has ```typescript has(address: string): Promise; ``` Check if a cell has a hyperlink. @param address - A1-style cell address @returns True if the cell has a hyperlink #### remove ```typescript remove(address: string): Promise; ``` Remove a hyperlink from a cell. @param address - A1-style cell address #### list ```typescript list(): Promise>; ``` List all hyperlinks in the worksheet. @returns Array of hyperlink entries with cell address and URL #### clear ```typescript clear(): Promise; ``` Remove all hyperlinks from the worksheet. ## WorksheetOutline Sub-API for outline (row/column grouping) operations on a worksheet. ### Methods #### groupRows ```typescript groupRows(startRow: number, endRow: number): Promise; ``` Group rows in a range. @param startRow - Start row index (0-based, inclusive) @param endRow - End row index (0-based, inclusive) #### ungroupRows ```typescript ungroupRows(startRow: number, endRow: number): Promise; ``` Ungroup rows in a range. @param startRow - Start row index (0-based, inclusive) @param endRow - End row index (0-based, inclusive) #### groupColumns ```typescript groupColumns(startCol: number, endCol: number): Promise; ``` Group columns in a range. @param startCol - Start column index (0-based, inclusive) @param endCol - End column index (0-based, inclusive) #### ungroupColumns ```typescript ungroupColumns(startCol: number, endCol: number): Promise; ``` Ungroup columns in a range. @param startCol - Start column index (0-based, inclusive) @param endCol - End column index (0-based, inclusive) #### toggleCollapsed ```typescript toggleCollapsed(groupId: string): Promise; ``` Toggle the collapsed state of a group. @param groupId - Group identifier #### expandAll ```typescript expandAll(): Promise; ``` Expand all groups in the worksheet. #### collapseAll ```typescript collapseAll(): Promise; ``` Collapse all groups in the worksheet. #### getState ```typescript getState(): Promise; ``` Get the full group state for the worksheet. @returns Group state including row groups, column groups, and max levels #### getLevel ```typescript getLevel(type: 'row' | 'column', index: number): Promise; ``` Get the outline level of a specific row or column. @param type - Whether to query a row or column @param index - Row or column index (0-based) @returns The outline level (0 if not in any group) #### getMaxLevel ```typescript getMaxLevel(type: 'row' | 'column'): Promise; ``` Get the maximum outline level for rows or columns. @param type - Whether to query rows or columns @returns The maximum outline level #### subtotal ```typescript subtotal(config: SubtotalConfig): Promise; ``` Apply automatic subtotals. @param config - Subtotal configuration #### getSettings ```typescript getSettings(): Promise; ``` Get the outline display settings. @returns Current outline settings #### setSettings ```typescript setSettings(settings: Partial): Promise; ``` Update outline display settings. @param settings - Partial outline settings to update #### showOutlineLevels ```typescript showOutlineLevels(rowLevels: number, colLevels: number): Promise; ``` Show outline to a specific level for rows and/or columns. Groups at levels > the specified level are collapsed; groups at levels <= are expanded. Pass 0 to collapse all, or a number > maxLevel to expand all. @param rowLevels - Target outline level for rows (0 = collapse all rows) @param colLevels - Target outline level for columns (0 = collapse all columns) ## WorksheetProtection Sub-API for worksheet protection operations. ### Methods #### isProtected ```typescript isProtected(): Promise; ``` Check whether the sheet is currently protected. @returns True if the sheet is protected #### protect ```typescript protect(password?: string): Promise; ``` Protect the sheet with an optional password. @param password - Optional password to require for unprotection #### protectWithOptions ```typescript protectWithOptions(password?: string, options?: ProtectionOptions): Promise; ``` Protect the sheet with an optional password and granular permission options. @param password - Optional password to require for unprotection @param options - Granular permissions (e.g., allowSort, allowFormatCells) #### unprotect ```typescript unprotect(password?: string): Promise; ``` Unprotect the sheet. Returns true if unprotection succeeded. @param password - Password if the sheet was protected with one @returns True if the sheet was successfully unprotected #### canEditCell ```typescript canEditCell(row: number, col: number): Promise; ``` Check whether a specific cell can be edited under current protection. Returns true if the sheet is unprotected or the cell is unlocked. @param row - Row index (0-based) @param col - Column index (0-based) @returns True if the cell is editable #### canEditCellFast ```typescript canEditCellFast(row: number, col: number): true | 'unknown'; ``` Synchronous protection fast path for edit-entry commands. Returns true only when the mirror proves the sheet is currently unprotected. Returns 'unknown' for protected sheets, where callers must use canEditCell(row, col) so cell lock state remains kernel-owned. #### canDoStructureOp ```typescript canDoStructureOp(operation: ProtectionOperation): Promise; ``` Check whether a structural operation is allowed under current protection. @param operation - Operation name (e.g., 'sort', 'insertRows', 'deleteColumns') @returns True if the operation is allowed #### canSort ```typescript canSort(): Promise; ``` Check whether sorting is allowed under current protection. Convenience shorthand for `canDoStructureOp('sort')`. @returns True if sorting is allowed #### getConfig ```typescript getConfig(): Promise; ``` Get the full protection configuration for the sheet. @returns Protection configuration including status and permission flags #### getSelectionMode ```typescript getSelectionMode(): Promise<'normal' | 'unlockedOnly' | 'none'>; ``` Get the current selection mode when the sheet is protected. @returns 'normal' (all cells selectable), 'unlockedOnly' (only unlocked cells), or 'none' (no selection) #### setSelectionMode ```typescript setSelectionMode(mode: 'normal' | 'unlockedOnly' | 'none'): Promise; ``` Set the selection mode for when the sheet is protected. Only takes effect when the sheet is actually protected. @param mode - Selection mode #### pauseProtection ```typescript pauseProtection(password?: string): Promise; ``` Temporarily suspend sheet protection. If the sheet is password-protected, the correct password must be provided. @param password - Password if the sheet is password-protected #### resumeProtection ```typescript resumeProtection(): Promise; ``` Re-enable previously paused protection with the original configuration. #### checkPassword ```typescript checkPassword(password?: string): Promise; ``` Check if the given password matches the current protection password without modifying protection state. @param password - Password to check @returns True if the password matches #### setPassword ```typescript setPassword(password?: string): Promise; ``` Change the protection password without needing to unprotect/re-protect. @param password - New password, or undefined/empty to remove the password #### updateOptions ```typescript updateOptions(options: Partial): Promise; ``` Update protection options without needing to unprotect/re-protect. @param options - Partial protection options to merge with existing options ## WorksheetPrint Sub-API for worksheet print and page break operations. ### Methods #### getSettings ```typescript getSettings(): Promise; ``` Get the current print settings for the sheet. @returns Current print settings #### setSettings ```typescript setSettings(settings: Partial): Promise; ``` Update print settings. Only the provided keys are changed. @param settings - Partial print settings to apply #### getArea ```typescript getArea(): Promise; ``` Get the current print area as an A1-notation range string. @returns The print area range string, or null if no print area is set #### setArea ```typescript setArea(area: string): Promise; ``` Set the print area to the specified A1-notation range. @param area - A1-notation range string (e.g., "A1:H20") #### clearArea ```typescript clearArea(): Promise; ``` Clear the print area so the entire sheet prints. #### addPageBreak ```typescript addPageBreak(type: 'horizontal' | 'vertical', position: number): Promise; ``` Add a manual page break at the specified position. @param type - 'horizontal' (row break) or 'vertical' (column break) @param position - 0-based row or column index for the break #### removePageBreak ```typescript removePageBreak(type: 'horizontal' | 'vertical', position: number): Promise; ``` Remove a manual page break at the specified position. @param type - 'horizontal' or 'vertical' @param position - 0-based row or column index of the break to remove #### getPageBreaks ```typescript getPageBreaks(): Promise<{ rowBreaks: Array<{ id: number; min: number; max: number; manual: boolean; pt: boolean }>; colBreaks: Array<{ id: number; min: number; max: number; manual: boolean; pt: boolean }>; }>; ``` Get all manual page breaks in the sheet. @returns Object containing arrays of horizontal and vertical break positions #### clearPageBreaks ```typescript clearPageBreaks(): Promise; ``` Remove all manual page breaks from the sheet. #### setPrintTitleRows ```typescript setPrintTitleRows(startRow: number, endRow: number): Promise; ``` Set the rows to repeat at the top of each printed page (print titles). @param startRow - 0-based start row index @param endRow - 0-based end row index (inclusive) #### setPrintTitleColumns ```typescript setPrintTitleColumns(startCol: number, endCol: number): Promise; ``` Set the columns to repeat at the left of each printed page (print titles). @param startCol - 0-based start column index @param endCol - 0-based end column index (inclusive) #### getPrintTitleRows ```typescript getPrintTitleRows(): Promise<[number, number] | null>; ``` Get the rows configured to repeat at the top of each printed page. @returns A [startRow, endRow] tuple (0-based, inclusive), or null if no repeat rows are set #### getPrintTitleColumns ```typescript getPrintTitleColumns(): Promise<[number, number] | null>; ``` Get the columns configured to repeat at the left of each printed page. @returns A [startCol, endCol] tuple (0-based, inclusive), or null if no repeat columns are set #### clearPrintTitles ```typescript clearPrintTitles(): Promise; ``` Clear all print titles (both repeat rows and repeat columns). Other print settings (margins, orientation, etc.) are preserved. #### setPrintMargins ```typescript setPrintMargins( unit: 'inches' | 'points' | 'centimeters', options: Partial, ): Promise; ``` Set page margins with unit conversion. Values are converted to inches (OOXML native unit) before storing. Only provided margin fields are updated; others are preserved. @param unit - Unit of the provided values: 'inches', 'points', or 'centimeters' @param options - Partial margin values to set #### getCellAfterBreak ```typescript getCellAfterBreak( type: 'horizontal' | 'vertical', position: number, ): { row: number; col: number }; ``` Get the cell position immediately after a page break. @param type - Break type: 'horizontal' (row break) or 'vertical' (column break) @param position - 0-based row or column index of the break @returns Cell coordinates of the first cell after the break #### getHeaderFooterImages ```typescript getHeaderFooterImages(): Promise; ``` Get all header/footer images for this sheet. @returns Array of image info objects, one per occupied position #### setHeaderFooterImage ```typescript setHeaderFooterImage(info: HeaderFooterImageInfo): Promise; ``` Set or replace a header/footer image at the specified position. The engine automatically manages the `&G` format code in the corresponding header/footer string. @param info - Image info including position, src (data-URL or path), and dimensions #### removeHeaderFooterImage ```typescript removeHeaderFooterImage(position: HfImagePosition): Promise; ``` Remove the header/footer image at the specified position. The engine automatically removes the `&G` format code from the corresponding header/footer string. @param position - Which of the 6 header/footer positions to clear ## WorksheetSettings Sub-API for worksheet settings operations. ### Methods #### get ```typescript get(): Promise; ``` Get all sheet settings. @returns Current sheet settings #### set ```typescript set(key: K, value: SheetSettingsInfo[K]): Promise; ``` Set an individual sheet setting by key. @param key - Setting key (e.g., 'showGridlines', 'defaultRowHeight') @param value - New value for the setting #### getStandardHeight ```typescript getStandardHeight(): Promise; ``` Get the standard (default) row height in pixels. This is the height used for rows that haven't been explicitly sized. Read-only (matches spreadsheet special-cell typesemantics). #### getStandardWidth ```typescript getStandardWidth(): Promise; ``` Get the standard (default) column width in pixels. This is the width used for columns that haven't been explicitly sized. #### setStandardWidth ```typescript setStandardWidth(width: number): Promise; ``` Set the standard (default) column width in pixels. This changes the default width for all columns that haven't been explicitly sized. @param width - New default column width in pixels ## WorksheetBindings Sub-API for worksheet data binding operations. ### Methods #### list ```typescript list(): Promise; ``` List all data bindings on the sheet. @returns Array of binding info objects #### get ```typescript get(bindingId: string): Promise; ``` Get a data binding by ID. @param bindingId - The binding ID to retrieve @returns The binding info, or null if not found #### getCount ```typescript getCount(): Promise; ``` Get the total number of data bindings on this sheet. @returns The count of bindings #### clear ```typescript clear(): Promise; ``` Remove all data bindings from the sheet. #### add ```typescript add(config: CreateBindingConfig): Promise; ``` Add a new data binding on the sheet. @param config - Binding configuration (connection, column mappings, etc.) @returns The created binding info #### remove ```typescript remove(bindingId: string): Promise; ``` Remove a data binding by ID. @param bindingId - The binding ID to remove #### getProjectionRange ```typescript getProjectionRange(row: number, col: number): Promise; ``` Get the spill range for a projected (dynamic array) cell. @param row - Row index (0-based) @param col - Column index (0-based) @returns The spill range, or null if the cell is not a projection source #### getProjectionSource ```typescript getProjectionSource(row: number, col: number): Promise<{ row: number; col: number } | null>; ``` Get the source cell of a projected value. @param row - Row index (0-based) @param col - Column index (0-based) @returns The source cell position, or null if the cell is not a projection #### isProjectedPosition ```typescript isProjectedPosition(row: number, col: number): Promise; ``` Check whether a cell position is a projected (spilled) value. @param row - Row index (0-based) @param col - Column index (0-based) @returns True if the cell holds a projected value #### getViewportProjectionData ```typescript getViewportProjectionData( range: string | CellRange, ): Promise>; ``` Get all projection data overlapping a viewport range (batch query). Returns one entry per projection with origin position and dimensions. @param range - A1-style range string or CellRange object ## WorksheetNames Sub-API for sheet-scoped named range operations. ### Methods #### add ```typescript add(name: string, reference: string, comment?: string): Promise; ``` Add a named range scoped to this sheet. @param name - Name for the range @param reference - Cell reference (e.g., "A1:B10" or "=Sheet1!A1:B10") @param comment - Optional comment @returns The created named range info #### has ```typescript has(name: string): Promise; ``` Check if a named range exists in this sheet's scope. @param name - Name to check @returns True if the named range exists #### getCount ```typescript getCount(): Promise; ``` Get the total number of named ranges scoped to this sheet. @returns The count of named ranges #### get ```typescript get(name: string): Promise; ``` Get a named range by name, scoped to this sheet. @param name - Name to look up @returns Named range info or null if not found #### getRange ```typescript getRange(name: string): Promise; ``` Get the range reference for a named range scoped to this sheet. @param name - Name to look up @returns Range reference or null if not found #### remove ```typescript remove(name: string): Promise; ``` Remove a named range scoped to this sheet. @param name - Name to remove #### update ```typescript update(name: string, updates: NamedRangeUpdateOptions): Promise; ``` Update a named range scoped to this sheet. @param name - Name of the range to update @param updates - Fields to update #### clear ```typescript clear(): Promise; ``` Remove all named ranges scoped to this sheet. #### list ```typescript list(): Promise; ``` List all named ranges scoped to this sheet. @returns Array of named range info objects ## WorksheetStyles Sub-API for named cell style operations on a worksheet. ### Methods #### applyStyle ```typescript applyStyle(address: string, styleName: string): Promise; ``` Apply a named style to a cell. Resolves the style name to its format definition and applies all format properties to the target cell. @param address - A1-style cell address @param styleName - Name of the style to apply (e.g., "Normal", "Heading 1") @throws KernelError if style name is not found #### applyStyleToRange ```typescript applyStyleToRange(range: string | CellRange, styleName: string): Promise; ``` Apply a named style to a range. @param range - A1-style range string (e.g. "A1:C3") @param styleName - Name of the style to apply @throws KernelError if style name is not found #### getStyle ```typescript getStyle(address: string): Promise; ``` Get the name of the named style that matches a cell's format (best-effort). Since Mog copies format values rather than storing a style reference, this performs a reverse lookup by comparing the cell's current format against all known style formats. @param address - A1-style cell address @returns Style name if a matching style is found, null otherwise --- # Types ## AccentNode Accent - Accent mark over base expression (hat, tilde, dot, etc.) ```typescript type AccentNode = { type: 'acc'; /** Accent character (defaults to combining circumflex U+0302) */ chr?: string; /** Base expression */ e: MathNode[]; } ``` ## AccessExplanation Derivation trace returned by `wb.security.explainAccess(...)`. Matches the Rust `compute_security::engine::AccessExplanation` serde shape. ```typescript type AccessExplanation = { /** The resolved access level */ level: AccessLevel; /** The policy that determined the level (null = default, no policy matched) */ matchedPolicy: AccessPolicy | null; /** Why this level was chosen */ reason: string; /** All policies that were considered during evaluation */ candidatePolicies: AccessPolicy[]; /** Warnings (e.g., "ambiguous: 2 policies at same specificity+priority disagree") */ warnings: string[]; } ``` ## AccessLevel Single linear access level scale. No per-aspect complexity. - `none` — hidden, scope doesn't exist for this principal - `structure` — formulas, types, formatting visible; values show type placeholders - `read` — full data, no write - `write` — full access - `admin` — full access + can modify policies ```typescript type AccessLevel = 'none' | 'structure' | 'read' | 'write' | 'admin' ``` ## AccessPolicy A data access policy. Policies define what access level a principal (matched by tag glob) has to a target (matched by target pattern). `level: 'none'` is the deny — there is no separate `effect` field. ```typescript type AccessPolicy = { id: PolicyId; /** Glob-matched against principal's tags */ principalTag: TagMatcher; /** Target pattern to match */ target: TargetMatcher; /** The granted access level */ level: AccessLevel; /** Higher priority wins within the same specificity tier. Recommended ranges: - 0-99: App-defined policies (default: 0) - 100-199: Template-generated policies - 200+: Platform/system policies (owner lockout, etc.) */ priority: number; /** Whether this policy is active */ enabled: boolean; /** Policy metadata for auditing and template tracking */ metadata: AccessPolicyMetadata; } ``` ## AccessPolicyMetadata Metadata attached to an access policy. ```typescript type AccessPolicyMetadata = { /** Tag of the principal who created this policy */ createdBy: string; /** Creation timestamp (epoch ms) */ createdAt: number; /** Human-readable description */ description?: string; /** If created by a template, tracks which one */ templateId?: string; } ``` ## AccessPrincipal A principal is identified by a set of opaque string tags. Mog provides the matching engine; apps define their own identity taxonomy. Examples: - `{ tags: ['user:alice@co.com', 'team:finance'] }` - `{ tags: ['agent:copilot'] }` - `{ tags: ['mog:owner'] }` ```typescript type AccessPrincipal = { tags: string[]; } ``` ## AccessTarget Identity-based resource target. Phase 1 supports workbook, sheet, and column. Uses a discriminated union for type-safe exhaustive switch checking. ```typescript type AccessTarget = | { readonly kind: 'workbook' } | { readonly kind: 'sheet'; readonly sheetId: SheetId } | { readonly kind: 'column'; readonly colId: ColId; readonly sheetId: SheetId } ``` ## ActiveCellEditSource Kernel-owned read model for the source text used when entering edit mode on the active cell. ```typescript type ActiveCellEditSource = { sheetId: SheetId; row: number; col: number; source: string; version: number; fresh: boolean; } ``` ## ActiveScenarioState Session-scoped state for an applied scenario. ```typescript type ActiveScenarioState = { /** Scenario whose values are currently applied in this local session. */ scenarioId: string; /** Session baseline token used by restore once Rust-owned apply/restore lands. */ baselineId: string; /** Document handle this session state belongs to. */ documentId: string; /** Whether the stored scenario definition still matches the active baseline. */ definitionStatus?: 'current' | 'stale' | 'deleted'; /** Whether active cells have diverged from the baseline. */ cellMutationStatus?: 'clean' | 'conflicted'; } ``` ## AddCheckboxFormControlOptions ```typescript type AddCheckboxFormControlOptions = WorksheetCreateCheckboxOptions & { type: 'checkbox'; } ``` ## AdjustmentValues Adjustment values for fine-tuning warp parameters. Each warp preset has 0-2 adjustment handles that control its shape. Values are percentages (typically 0-100) or absolute values depending on preset. The specific meaning of each adjustment depends on the preset type. @see ECMA-376 Part 1, Section 20.1.9.9 (CT_GeomGuideList) @example // textArchUp has one adjustment (arc height) { adj1: 50 } // 50% arc height @example // textWave1 has two adjustments (amplitude, frequency) { adj1: 20, adj2: 30 } ```typescript type AdjustmentValues = { /** Primary adjustment value. Meaning depends on the warp preset: - Arc presets: arc height/curvature - Wave presets: amplitude - Inflate/deflate: bulge amount - Fade presets: fade percentage */ adj1?: number; /** Secondary adjustment value. Meaning depends on the warp preset: - Wave presets: phase offset - Pour presets: inner radius - Some geometric presets: secondary parameter */ adj2?: number; } ``` ## AdvancedFilterCopyToOptions ```typescript type AdvancedFilterCopyToOptions = { listRange: string; criteriaRange?: string | null; mode: 'copyTo'; copyToRange: string; uniqueRecordsOnly?: boolean; filterId?: never; } ``` ## AdvancedFilterCopyToResult ```typescript type AdvancedFilterCopyToResult = { mode: 'copyTo'; listRange: string; criteriaRange?: string; filterId?: never; rowsMatched: number; rowsHidden?: never; rowsCopied: number; columnsCopied: number; destinationRange?: string; } ``` ## AdvancedFilterDetailInfo ```typescript type AdvancedFilterDetailInfo = { /** Resolved criteria range, if this Advanced Filter has criteria. */ criteriaRange?: { startRow: number; startCol: number; endRow: number; endCol: number }; /** Whether duplicate full-row records are hidden/copied after criteria evaluation. */ uniqueRecordsOnly: boolean; /** Whether this Advanced Filter currently has criteria or unique-records semantics. */ active: boolean; } ``` ## AdvancedFilterInPlaceOptions ```typescript type AdvancedFilterInPlaceOptions = { listRange: string; criteriaRange?: string | null; mode: 'inPlace'; copyToRange?: never; uniqueRecordsOnly?: boolean; filterId?: string; } ``` ## AdvancedFilterInPlaceResult ```typescript type AdvancedFilterInPlaceResult = { mode: 'inPlace'; listRange: string; criteriaRange?: string; filterId: string; rowsMatched: number; rowsHidden: number; rowsCopied?: never; columnsCopied?: never; destinationRange?: never; } ``` ## AdvancedFilterOptions ```typescript type AdvancedFilterOptions = AdvancedFilterInPlaceOptions | AdvancedFilterCopyToOptions ``` ## AdvancedFilterResult ```typescript type AdvancedFilterResult = AdvancedFilterInPlaceResult | AdvancedFilterCopyToResult ``` ## AggregateFunction ```typescript type AggregateFunction = 'sum' | 'count' | 'counta' | 'countunique' | 'average' | 'min' | 'max' | 'product' | 'stdev' | 'stdevp' | 'var' | 'varp' ``` ## AggregateResult Aggregate values for selected cells (status bar display). ```typescript type AggregateResult = { /** Sum of numeric values */ sum: number; /** Total number of non-empty cells */ count: number; /** Number of numeric cells */ numericCount: number; /** Average of numeric values (null if no numeric cells) */ average: number | null; /** Minimum numeric value (null if no numeric cells) */ min: number | null; /** Maximum numeric value (null if no numeric cells) */ max: number | null; } ``` ## ApplyScenarioResult Result returned from applyScenario(). ```typescript type ApplyScenarioResult = { /** Session baseline token to pass to restoreScenario(). */ baselineId: string; /** Document/session handle this baseline belongs to. */ documentId?: string; /** Number of cells that were updated with scenario values. */ cellsUpdated: number; /** CellIds that could not be found (deleted cells). */ skippedCells: string[]; /** Original values to pass to restoreScenario() later. */ originalValues: OriginalCellValue[]; } ``` ## AreaSubType ```typescript type AreaSubType = 'standard' | 'stacked' | 'percentStacked' ``` ## ArrowHead Arrow head style for connectors. ```typescript type ArrowHead = { /** Arrow head type */ type: 'none' | 'triangle' | 'stealth' | 'diamond' | 'oval' | 'open'; /** Arrow head size */ size: 'small' | 'medium' | 'large'; } ``` ## AuthorizedMaterializedCacheMetadata ```typescript type AuthorizedMaterializedCacheMetadata = { cachedValuesVersion?: string; materializedAt?: string; policyVersion?: string; } ``` ## AutoFillChange A single cell change produced by the fill engine. ```typescript type AutoFillChange = { row: number; col: number; type: 'value' | 'formula' | 'format' | 'clear'; } ``` ## AutoFillMode Fill mode for autoFill() — matches Rust FillMode enum. Covers the full spreadsheet fill behavior set. ```typescript type AutoFillMode = | 'auto' // Detect pattern automatically (default) | 'copy' // Always copy (no series) | 'series' // Force series interpretation | 'days' // Force date unit: days | 'weekdays' // Force date unit: weekdays | 'months' // Force date unit: months | 'years' // Force date unit: years | 'formats' // Copy formats only | 'values' // Copy values only (no formats) | 'withoutFormats' // Copy values + formulas, skip formats | 'linearTrend' // Force linear regression trend | 'growthTrend' ``` ## AutoFillResult Result from autoFill() — summary of what the fill engine did. ```typescript type AutoFillResult = { /** The pattern that was detected (or forced by mode) */ patternType: FillPatternType; /** Number of cells that were filled */ filledCellCount: number; /** Any warnings generated during fill */ warnings: AutoFillWarning[]; /** Per-cell changes listing each cell written */ changes: AutoFillChange[]; } ``` ## AutoFillWarning ```typescript type AutoFillWarning = { row: number; col: number; kind: AutoFillWarningKind; } ``` ## AutoFillWarningKind ```typescript type AutoFillWarningKind = | { type: 'mergedCellsInTarget' } | { type: 'formulaRefOutOfBounds'; refIndex: number } | { type: 'sourceCellEmpty' } ``` ## AutoFilterClearReceipt Receipt for clearing an auto-filter. ```typescript type AutoFilterClearReceipt = { kind: 'autoFilterClear'; } ``` ## AutoFilterSetReceipt Receipt for setting an auto-filter. ```typescript type AutoFilterSetReceipt = { kind: 'autoFilterSet'; range: string; } ``` ## AxisBound ```typescript type AxisBound = AxisBoundLabel | number ``` ## AxisBoundLabel ```typescript type AxisBoundLabel = "auto" | "same" ``` ## AxisConfig Axis configuration (matches AxisData wire type). Wire field names: categoryAxis, valueAxis, secondaryCategoryAxis, secondaryValueAxis. Legacy aliases: xAxis, yAxis, secondaryYAxis (mapped in chart-bridge). ```typescript type AxisConfig = { categoryAxis?: SingleAxisConfig; valueAxis?: SingleAxisConfig; secondaryCategoryAxis?: SingleAxisConfig; secondaryValueAxis?: SingleAxisConfig; seriesAxis?: SingleAxisConfig; /** @deprecated Use categoryAxis instead */ xAxis?: SingleAxisConfig; /** @deprecated Use valueAxis instead */ yAxis?: SingleAxisConfig; /** @deprecated Use secondaryValueAxis instead */ secondaryYAxis?: SingleAxisConfig; } ``` ## AxisType Axis type ```typescript type AxisType = 'category' | 'value' | 'time' | 'log' ``` ## BarNode Bar - Horizontal bar over or under base ```typescript type BarNode = { type: 'bar'; /** Position: 'top' (overline) or 'bot' (underline) */ pos: 'top' | 'bot'; /** Base expression */ e: MathNode[]; } ``` ## BarSubType Chart sub-types for variations ```typescript type BarSubType = 'clustered' | 'stacked' | 'percentStacked' ``` ## Bevel Bevel effect for a 3D shape edge. @see ECMA-376 Part 1, Section 20.1.5.3 (bevelT) and 20.1.5.4 (bevelB) ```typescript type Bevel = { /** Bevel width in EMUs */ w?: number; /** Bevel height in EMUs */ h?: number; /** Bevel preset type */ prst?: BevelPresetType; } ``` ## BevelEffect 3D bevel effect configuration. ```typescript type BevelEffect = { /** Bevel preset type */ type: | 'none' | 'relaxed' | 'circle' | 'slope' | 'cross' | 'angle' | 'soft-round' | 'convex' | 'cool-slant' | 'divot' | 'riblet' | 'hard-edge' | 'art-deco'; /** Bevel width in pixels */ width: number; /** Bevel height in pixels */ height: number; } ``` ## BevelPresetType Bevel preset type. Defines the cross-section profile of a 3D bevel edge effect. 12 presets defining different edge shapes. @see ECMA-376 Part 1, Section 20.1.10.6 (ST_BevelPresetType) ```typescript type BevelPresetType = | 'relaxedInset' // Subtle rounded inset | 'circle' // Circular cross-section | 'slope' // Linear angled edge | 'cross' // Cross-shaped profile | 'angle' // Sharp angled edge | 'softRound' // Soft rounded profile | 'convex' // Outward curving edge | 'coolSlant' // Stylized slanted edge | 'divot' // Indented groove | 'riblet' // Ribbed texture | 'hardEdge' // Sharp, defined edge | 'artDeco' ``` ## BlipFill Picture/texture fill definition. ```typescript type BlipFill = { src: string; stretch?: boolean; tile?: TileSettings; } ``` ## BorderBoxNode BorderBox - Box with visible borders ```typescript type BorderBoxNode = { type: 'borderBox'; /** Hide individual borders */ hideTop?: boolean; hideBot?: boolean; hideLeft?: boolean; hideRight?: boolean; /** Strikethrough lines */ strikeH?: boolean; strikeV?: boolean; strikeBLTR?: boolean; strikeTLBR?: boolean; /** Content */ e: MathNode[]; } ``` ## BorderStyle Border style. D3: Spreadsheet border styles. The full XLSX border-style set is supported: - Solid: 'thin', 'medium', 'thick' (varying line widths) - Dashed: 'dashed', 'mediumDashed' (varying dash lengths) - Dotted: 'dotted', 'hair' (dots and very fine lines) - Double: 'double' (two parallel lines) - Dash-dot combinations: 'dashDot', 'dashDotDot', 'mediumDashDot', 'mediumDashDotDot' - Special: 'slantDashDot' (slanted dash-dot pattern) @see cells-layer.ts getBorderDashPattern() for canvas rendering @see format-mapper.ts for XLSX import/export mapping ```typescript type BorderStyle = { style: | 'none' | 'thin' | 'medium' | 'thick' | 'dashed' | 'dotted' | 'double' | 'hair' | 'mediumDashed' | 'dashDot' | 'dashDotDot' | 'mediumDashDot' | 'mediumDashDotDot' | 'slantDashDot'; color?: string; /** Tint modifier for border color (-1.0 to +1.0, ECMA-376). */ colorTint?: number; } ``` ## BoxNode Box - Invisible container for grouping/alignment ```typescript type BoxNode = { type: 'box'; /** Operator emulator (acts as operator for spacing) */ opEmu?: boolean; /** No break (keep together) */ noBreak?: boolean; /** Differential (italic d for dx) */ diff?: boolean; /** Alignment point */ aln?: boolean; /** Content */ e: MathNode[]; } ``` ## BoxplotConfig Box plot configuration ```typescript type BoxplotConfig = { showOutliers?: boolean; showMean?: boolean; whiskerType?: 'tukey' | 'minMax' | 'percentile'; } ``` ## BreakWorkbookLinkOptions ```typescript type BreakWorkbookLinkOptions = { keepValues?: boolean; } ``` ## ButtonControl Button control - triggers actions on click. Unlike other controls, Button's primary purpose is triggering actions, not storing values. linkedCellId is optional. Use cases: - Increment a counter cell on click - Trigger a macro/script (via actionId) - Navigate to another sheet/location ```typescript type ButtonControl = { type: 'button'; /** Button label text */ label: string; /** Optional - Cell to write to on click. Common patterns: - Increment counter: read current value, write value + 1 - Toggle: write opposite of current value - Fixed value: write specific value (e.g., timestamp) */ linkedCellId?: CellId; /** Action ID for future macro/script integration. Will be used to trigger named actions defined elsewhere. */ actionId?: string; /** Value to write to linked cell on click. Only used if linkedCellId is set and clickAction is 'setValue'. */ clickValue?: unknown; /** Click behavior when linkedCellId is set. - 'setValue': Write clickValue to cell - 'increment': Add 1 to current numeric value - 'decrement': Subtract 1 from current numeric value - 'toggle': Toggle boolean value */ clickAction?: 'setValue' | 'increment' | 'decrement' | 'toggle'; } ``` ## CFAboveAverageRule Above/below average rule. ```typescript type CFAboveAverageRule = { type: 'aboveAverage'; aboveAverage: boolean; equalAverage?: boolean; stdDev?: number; style: CFStyle; } ``` ## CFCellValueRule Cell value comparison rule. ```typescript type CFCellValueRule = { type: 'cellValue'; operator: CFOperator; value1: number | string; value2?: number | string; style: CFStyle; } ``` ## CFColorScale Color scale configuration (2 or 3 colors). ```typescript type CFColorScale = { minPoint: CFColorPoint; midPoint?: CFColorPoint; maxPoint: CFColorPoint; } ``` ## CFColorScaleRule Color scale rule. ```typescript type CFColorScaleRule = { type: 'colorScale'; colorScale: CFColorScale; } ``` ## CFContainsBlanksRule Contains blanks rule. ```typescript type CFContainsBlanksRule = { type: 'containsBlanks'; blanks: boolean; style: CFStyle; } ``` ## CFContainsErrorsRule Contains errors rule. ```typescript type CFContainsErrorsRule = { type: 'containsErrors'; errors: boolean; style: CFStyle; } ``` ## CFContainsTextRule Contains text rule. ```typescript type CFContainsTextRule = { type: 'containsText'; operator: CFTextOperator; text: string; style: CFStyle; } ``` ## CFDataBar Data bar configuration. ```typescript type CFDataBar = { minPoint: CFColorPoint; maxPoint: CFColorPoint; positiveColor: string; negativeColor?: string; borderColor?: string; negativeBorderColor?: string; showBorder?: boolean; gradient?: boolean; direction?: 'leftToRight' | 'rightToLeft' | 'context'; axisPosition?: CFDataBarAxisPosition; axisColor?: string; showValue?: boolean; /** When true, negative bars use the positive fill color. */ matchPositiveFillColor?: boolean; /** When true, negative bars use the positive border color. */ matchPositiveBorderColor?: boolean; /** Extension identifier for OOXML ext data bars. */ extId?: string; } ``` ## CFDataBarRule Data bar rule. ```typescript type CFDataBarRule = { type: 'dataBar'; dataBar: CFDataBar; } ``` ## CFDuplicateValuesRule Duplicate/unique values rule. ```typescript type CFDuplicateValuesRule = { type: 'duplicateValues'; unique?: boolean; style: CFStyle; } ``` ## CFFormulaRule Formula-based rule. ```typescript type CFFormulaRule = { type: 'formula'; formula: string; style: CFStyle; } ``` ## CFIconSet Icon set configuration. ```typescript type CFIconSet = { iconSetName: CFIconSetName; thresholds?: CFIconThreshold[]; reverseOrder?: boolean; showIconOnly?: boolean; /** Per-threshold custom icon overrides (null entries use default icons). */ customIcons?: (CFCustomIcon | null)[]; } ``` ## CFIconSetRule Icon set rule. ```typescript type CFIconSetRule = { type: 'iconSet'; iconSet: CFIconSet; } ``` ## CFOperator Comparison operators for cellValue rules. ```typescript type CFOperator = | 'greaterThan' | 'lessThan' | 'greaterThanOrEqual' | 'lessThanOrEqual' | 'equal' | 'notEqual' | 'between' | 'notBetween' ``` ## CFRule Union of all rule types. ```typescript type CFRule = | CFCellValueRule | CFFormulaRule | CFColorScaleRule | CFDataBarRule | CFIconSetRule | CFTop10Rule | CFAboveAverageRule | CFDuplicateValuesRule | CFContainsTextRule | CFContainsBlanksRule | CFContainsErrorsRule | CFTimePeriodRule ``` ## CFRuleInput Rule input for creating new rules (id and priority assigned by the API). Callers provide the rule configuration; the API generates id and sets priority. ```typescript type CFRuleInput = Omit ``` ## CFStyle Conditional Formatting Render Types Types needed by canvas-renderer to render conditional formatting results. These are extracted from engine to avoid circular dependencies during the canvas-renderer extraction. ## Two-tier Rust type architecture The CFStyle defined here mirrors `compute-cf/src/types/rule.rs` — the computation / rendering type used by the Rust CF evaluation engine. A separate, intentionally simplified persistence subset lives in `domain-types/src/domain/conditional_format.rs`. That domain type is auto-generated into `compute-types.gen.ts`, which is therefore NOT the rendering source of truth for CFStyle — this file is. @module contracts/conditional-format/render-types ```typescript type CFStyle = { backgroundColor?: string; fontColor?: string; bold?: boolean; italic?: boolean; underlineType?: 'none' | 'single' | 'double' | 'singleAccounting' | 'doubleAccounting'; strikethrough?: boolean; numberFormat?: string; borderColor?: string; borderStyle?: CFBorderStyle; borderTopColor?: string; borderTopStyle?: CFBorderStyle; borderBottomColor?: string; borderBottomStyle?: CFBorderStyle; borderLeftColor?: string; borderLeftStyle?: CFBorderStyle; borderRightColor?: string; borderRightStyle?: CFBorderStyle; } ``` ## CFTextOperator Text operators for containsText rules. ```typescript type CFTextOperator = 'contains' | 'notContains' | 'beginsWith' | 'endsWith' ``` ## CFTimePeriodRule Time period (date occurring) rule. ```typescript type CFTimePeriodRule = { type: 'timePeriod'; timePeriod: DatePeriod; style: CFStyle; } ``` ## CFTop10Rule Top/bottom N rule. ```typescript type CFTop10Rule = { type: 'top10'; rank: number; percent?: boolean; bottom?: boolean; style: CFStyle; } ``` ## CalcMode Calculation settings for the workbook. G.3: Supports iterative calculation for circular references. Excel allows formulas with circular references to calculate iteratively until they converge or reach the maximum iterations. When disabled (default), circular references result in #CALC! errors. @see plans/active/spreadsheet-compatibility/04-EDITING-BEHAVIORS-PLAN.md - G.3 ```typescript type CalcMode = 'auto' | 'autoNoTable' | 'manual' ``` ## CalculateOptions Options for wb.calculate() — all optional, backward compatible. ```typescript type CalculateOptions = { /** Enable iterative calculation for circular references. - `true` — enable with default settings (100 iterations, 0.001 threshold) - `{ maxIterations?: number; maxChange?: number }` — enable with custom settings - `false` — disable (override workbook setting) - `undefined` — use workbook setting (default) */ iterative?: boolean | { maxIterations?: number; maxChange?: number }; } ``` ## CalculateResult Result from wb.calculate() — includes convergence metadata. ```typescript type CalculateResult = { /** Whether circular references were detected. */ hasCircularRefs: boolean; /** Whether iterative calculation converged. Only meaningful when hasCircularRefs is true. */ converged: boolean; /** Number of iterations performed (0 if no circular refs). */ iterations: number; /** Maximum per-cell delta at final iteration. */ maxDelta: number; /** Number of cells involved in circular references. */ circularCellCount: number; /** Number of formula cells recomputed during this calculation. Zero when nothing changed since last full recalc. */ recomputedCount: number; } ``` ## CalculatedField Legacy calculated-field shape. New contracts should use `PivotCalculatedField`. ```typescript type CalculatedField = { fieldId: string; calculatedFieldId?: CalculatedFieldId; name: string; formula: string; status?: CalculatedFieldStatus; createdAt?: string; updatedAt?: string; } ``` ## CalculatedFieldId ```typescript type CalculatedFieldId = string & { readonly __brand: 'CalculatedFieldId' } ``` ## CalculatedFieldStatus ```typescript type CalculatedFieldStatus = { state: 'valid' | 'invalid'; error?: PivotKernelMutationError; referencedFieldIds: string[]; } ``` ## CalculationSettings ```typescript type CalculationSettings = { /** Whether to allow iterative calculation for circular references. When true, formulas with circular references calculate iteratively. When false (default), circular references show #CALC! error. */ enableIterativeCalculation: boolean; /** Maximum number of iterations for iterative calculation. Excel default: 100 */ maxIterations: number; /** Maximum change between iterations for convergence. Calculation stops when all results change by less than this amount. Excel default: 0.001 */ maxChange: number; /** Calculation mode (auto/manual/autoNoTable). Default: 'auto' */ calcMode: CalcMode; /** Whether to use full (15-digit) precision for calculations. Default: true */ fullPrecision: boolean; /** Cell reference style (true = R1C1, false = A1). Default: false */ r1c1Mode: boolean; /** Whether to perform a full calculation when the file is opened. Default: false */ fullCalcOnLoad: boolean; } ``` ## CallableDisposable A disposable that can also be called as a function (shorthand for dispose). This type alias stays in contracts since it's used in service interface signatures. ```typescript type CallableDisposable = (() => void) & IDisposable ``` ## CellAnchor Cell anchor point with pixel offset. Used for precise positioning relative to cell boundaries. Cell Identity Model: Uses CellId for stable references that survive row/col insert/delete. Position is resolved at render time via CellPositionLookup. @example // User places image at B5 const anchor: CellAnchor = { cellId: 'abc-123...', // CellId of B5 xOffset: 10, // 10px from cell left edge yOffset: 5 // 5px from cell top edge }; // After inserting row at row 3, the CellId is unchanged // but resolves to position (row: 5, col: 1) → image moves down ```typescript type CellAnchor = { /** Stable cell reference that survives row/col insert/delete. Resolve to current position via CellPositionLookup.getPosition(). */ cellId: CellId; /** Horizontal offset from cell top-left in pixels */ xOffset: number; /** Vertical offset from cell top-left in pixels */ yOffset: number; } ``` ## CellBorders Cell borders ECMA-376 CT_Border: Full border specification for cells. Supports standard borders (top/right/bottom/left), diagonal borders, RTL equivalents (start/end), and internal borders for ranges (vertical/horizontal). ```typescript type CellBorders = { top?: BorderStyle; right?: BorderStyle; bottom?: BorderStyle; left?: BorderStyle; diagonal?: BorderStyle & { direction?: 'up' | 'down' | 'both' }; /** Diagonal up flag (ECMA-376 CT_Border @diagonalUp). When true, diagonal line runs from bottom-left to top-right. Note: This is the spec-compliant representation. For convenience, diagonal.direction can also be used which derives from these flags. */ diagonalUp?: boolean; /** Diagonal down flag (ECMA-376 CT_Border @diagonalDown). When true, diagonal line runs from top-left to bottom-right. Note: This is the spec-compliant representation. For convenience, diagonal.direction can also be used which derives from these flags. */ diagonalDown?: boolean; /** RTL start border (maps to left in LTR, right in RTL). Used for bidirectional text support. */ start?: BorderStyle; /** RTL end border (maps to right in LTR, left in RTL). Used for bidirectional text support. */ end?: BorderStyle; /** Internal vertical border (between cells in a range). Only meaningful when applied to a range of cells. */ vertical?: BorderStyle; /** Internal horizontal border (between cells in a range). Only meaningful when applied to a range of cells. */ horizontal?: BorderStyle; /** Outline mode flag. When true, borders are applied as outline around the range. When false/undefined, borders apply to individual cells. */ outline?: boolean; } ``` ## CellControl Cell-embedded interactive control (e.g., checkbox). When a cell contains a control, formulas see its `checked` state as TRUE/FALSE. The `type` field discriminates the control kind for future extensibility (toggle, dropdown, etc.). ```typescript type CellControl = { /** The kind of control. Currently only 'checkbox' is supported. */ type: 'checkbox'; /** Whether the control is in its active state (checkbox: ticked). */ checked: boolean; } ``` ## CellData Complete cell data ```typescript type CellData = { value: CellValue; formula?: FormulaA1; format?: CellFormat; borders?: CellBorders; comment?: string; hyperlink?: string; /** Pre-formatted display string from Rust (e.g., "$1,234.50", "1/1/2024"). */ formatted?: string; } ``` ## CellFormat Cell formatting options This interface defines ALL Excel format properties that can be applied to cells. The implementation status of each property is tracked in format-registry.ts. @see FORMAT_PROPERTY_REGISTRY in format-registry.ts for implementation status ```typescript type CellFormat = { /** Spreadsheet number format code string. Common format codes: - Currency: '$#,##0.00' - Accounting: '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)' - Percentage: '0.00%' - Date: 'M/D/YYYY', 'YYYY-MM-DD', 'MMM D, YYYY' - Time: 'h:mm AM/PM', 'HH:mm:ss' - Number: '#,##0.00', '0.00' - Scientific: '0.00E+00' - Text: '@' - Fraction: '# ?/?' See the `formatPresets` section in api-spec.json for the full catalog of 85+ pre-defined format codes with examples. @example // Currency { numberFormat: '$#,##0.00' } // Percentage with 1 decimal { numberFormat: '0.0%' } // ISO date { numberFormat: 'YYYY-MM-DD' } */ numberFormat?: string; /** Number format category hint. Auto-detected from numberFormat when not set. Valid values: 'general' | 'number' | 'currency' | 'accounting' | 'date' | 'time' | 'percentage' | 'fraction' | 'scientific' | 'text' | 'special' | 'custom' */ numberFormatType?: NumberFormatType; fontFamily?: string; fontSize?: number; /** Theme font reference for "+Headings" / "+Body" workbook theme fonts. When set, the cell uses the theme's majorFont (headings) or minorFont (body) instead of fontFamily. Theme fonts are resolved at render time, allowing cells to automatically update when the workbook theme changes. Behavior: - 'major': Uses theme.fonts.majorFont - 'minor': Uses theme.fonts.minorFont - undefined: Uses fontFamily property (or default font if not set) When fontTheme is set, fontFamily is ignored for rendering but may still be stored for fallback purposes. This matches Excel's behavior where "+Headings" cells can have a fontFamily that's used when the theme is unavailable. @see resolveThemeFonts in theme.ts for resolution @see ThemeFonts for theme font pair definition */ fontTheme?: 'major' | 'minor'; /** Font color. Can be: - Absolute hex: '#4472c4' or '#ff0000' - Theme reference: 'theme:accent1' (uses current theme's accent1 color) - Theme with tint: 'theme:accent1:0.4' (40% lighter) or 'theme:accent1:-0.25' (25% darker) Theme references are resolved at render time via resolveThemeColors(). This enables cells to automatically update when the workbook theme changes. @see resolveThemeColors in theme.ts for resolution @see ThemeColorSlot for valid slot names (dark1, light1, accent1-6, etc.) */ fontColor?: string; /** Font color tint modifier (-1.0 to +1.0). Applied on top of fontColor. */ fontColorTint?: number; bold?: boolean; italic?: boolean; /** Underline type. Excel supports 4 underline styles: - 'none': No underline (default) - 'single': Standard underline under all characters - 'double': Two parallel lines under all characters - 'singleAccounting': Underline under text only (not spaces), for column alignment - 'doubleAccounting': Double underline under text only (not spaces), for column alignment */ underlineType?: 'none' | 'single' | 'double' | 'singleAccounting' | 'doubleAccounting'; strikethrough?: boolean; /** Superscript text (vertAlign = 'superscript' in Excel). Text is rendered smaller and raised above the baseline. */ superscript?: boolean; /** Subscript text (vertAlign = 'subscript' in Excel). Text is rendered smaller and lowered below the baseline. */ subscript?: boolean; /** Font outline effect. Draws only the outline of each character (hollow text). Rare in modern spreadsheets but supported by Excel. */ fontOutline?: boolean; /** Font shadow effect. Adds a shadow behind the text. Rare in modern spreadsheets but supported by Excel. */ fontShadow?: boolean; /** Horizontal text alignment. - 'general': Context-based (left for text, right for numbers) - Excel default - 'left': Left-align text - 'center': Center text - 'right': Right-align text - 'fill': Repeat content to fill cell width - 'justify': Justify text (distribute evenly) - 'centerContinuous': Center across selection without merging - 'distributed': Distribute text evenly with indent support */ horizontalAlign?: | 'general' | 'left' | 'center' | 'right' | 'fill' | 'justify' | 'centerContinuous' | 'distributed'; /** Vertical text alignment. The TypeScript/API contract uses `middle` for centered vertical alignment. - 'top': Align to top of cell - 'middle': Center vertically - 'bottom': Align to bottom of cell - Excel default - 'justify': Justify vertically (distribute lines evenly) - 'distributed': Distribute text evenly with vertical spacing */ verticalAlign?: 'top' | 'middle' | 'bottom' | 'justify' | 'distributed'; wrapText?: boolean; /** Text rotation angle in degrees. - 0-90: Counter-clockwise rotation - 91-180: Clockwise rotation (180 - value) - 255: Vertical text (stacked characters, read top-to-bottom) */ textRotation?: number; /** Indent level (0-15). Each level adds approximately 8 pixels of indent from the cell edge. Works with left and right horizontal alignment. */ indent?: number; /** Shrink text to fit cell width. Reduces font size to fit all text within the cell width. Mutually exclusive with wrapText in Excel behavior. */ shrinkToFit?: boolean; /** Text reading order for bidirectional text support. - 'context': Determined by first character with strong directionality - 'ltr': Left-to-right (forced) - 'rtl': Right-to-left (forced) */ readingOrder?: 'context' | 'ltr' | 'rtl'; /** Auto-indent flag (ECMA-376 CT_CellAlignment/@autoIndent). */ autoIndent?: boolean; /** Background color. Can be: - Absolute hex: '#ffffff' or '#c6efce' - Theme reference: 'theme:accent1' (uses current theme's accent1 color) - Theme with tint: 'theme:accent1:0.4' (40% lighter) or 'theme:accent1:-0.25' (25% darker) Theme references are resolved at render time via resolveThemeColors(). This enables cells to automatically update when the workbook theme changes. For solid fills, this is the only color needed. For pattern fills, this is the background color behind the pattern. @see resolveThemeColors in theme.ts for resolution @see ThemeColorSlot for valid slot names (dark1, light1, accent1-6, etc.) */ backgroundColor?: string; /** Background color tint modifier (-1.0 to +1.0). Applied on top of backgroundColor. */ backgroundColorTint?: number; /** Pattern fill type. XLSX supports 18 pattern types for cell backgrounds. When set (and not 'none' or 'solid'), the cell uses a pattern fill. */ patternType?: PatternType; /** Pattern foreground color. The color of the pattern itself (dots, lines, etc.). Only used when patternType is set to a non-solid pattern. */ patternForegroundColor?: string; /** Pattern foreground color tint modifier (-1.0 to +1.0). */ patternForegroundColorTint?: number; /** Gradient fill configuration. When set, overrides backgroundColor and pattern fill. Excel supports linear and path (radial) gradients. */ gradientFill?: GradientFill; /** Cell borders (top, right, bottom, left, diagonal) */ borders?: CellBorders; /** Cell is locked when sheet protection is enabled. Default is true in Excel (all cells locked by default). Only effective when the sheet's isProtected flag is true. */ locked?: boolean; /** Formula is hidden when sheet protection is enabled. When true, the cell's formula is not shown in the formula bar. The computed value is still displayed in the cell. Only effective when the sheet's isProtected flag is true. */ hidden?: boolean; /** Cell value is forced to text mode (apostrophe prefix). When true: - Raw value includes the leading apostrophe - Display value strips the apostrophe - Formula bar shows the apostrophe - Value is NOT coerced to date/number/etc. Set when user types ' as first character. Follows cell on sort/move (keyed by CellId, Cell Identity Model). @see plans/active/spreadsheet-compatibility/08-EDITING.md - Item 8.1 */ forcedTextMode?: boolean; /** Arbitrary extension data for future features. Use namespaced keys: "myfeature.mykey" Example: { ignoreError: true } to suppress error indicators. */ extensions?: Record; } ``` ## CellId ```typescript type CellId = string & { readonly [__cellId]: true } ``` ## CellIdRange A range defined by corner cell identities. This is the universal type for CRDT-safe range references used by: - Charts (data ranges, anchor positions) - Tables (table extent) - Grouping (group extent) Unlike position-based ranges, CellIdRange automatically handles: - Concurrent structure changes (insert/delete rows/cols) - Range expansion when cells inserted between corners - Correct CRDT composition under concurrent edits Position resolution happens at render/extraction time via GridIndex. @example // Chart data range A1:D10 const range: CellIdRange = { topLeftCellId: 'abc-123...', // CellId of A1 bottomRightCellId: 'def-456...' // CellId of D10 }; // After user inserts column at B: // - CellIds unchanged // - But A1 is still at (0,0), D10 is now at (9,4) // - Range automatically covers A1:E10 ```typescript type CellIdRange = { /** Cell identifier string (CellId) of the top-left corner cell */ topLeftCellId: string; /** Cell identifier string (CellId) of the bottom-right corner cell */ bottomRightCellId: string; } ``` ## CellRange Cell range reference. This is THE canonical range type for ALL range operations in the spreadsheet. Uses flat format for simplicity and JSON compatibility. Used by: XState machines, canvas coordinates, React hooks, API, events, tables, pivots ```typescript type CellRange = { startRow: number; startCol: number; endRow: number; endCol: number; /** True when entire column(s) selected via column header click */ isFullColumn?: boolean; /** True when entire row(s) selected via row header click */ isFullRow?: boolean; sheetId?: string; } ``` ## CellRecord Typed cell readback record returned by {@link WorksheetCellsAccessor.get}. Shape is intentionally divergent from {@link Worksheet.getCell}'s `{value: null}` empty form: every in-bounds cell carries a `valueType` tag so callers can switch on the discriminant without a separate "is this in-bounds" check. Out-of-bounds reads return `undefined`. ```typescript type CellRecord = { /** Sheet-relative position (0-indexed). */ row: number; col: number; /** A1 address as supplied to `cells.get`, normalized to upper-case. */ addr: string; /** Effective value (formula result for formula cells, raw value otherwise). `null` for empty. */ value: CellValuePrimitive | null; /** Per-cell value type classification — string-keyed enum already used by {@link Worksheet.getValueTypes} for ranges. `Empty | String | Double | Boolean | Error` (dates classified as `Double`, matching the workbook API). */ valueType: RangeValueType; /** Authored formula (A1) when the cell has one; `null` otherwise. */ formula: string | null; /** Unified region-membership shape. `null` for plain cells. */ region: RegionMeta | null; /** Convenience: `region != null && !region.isAnchor`. Derived, not stored. */ isArrayMember: boolean; } ``` ## CellStyle Named cell style that can be applied to cells. Styles are a named collection of formatting properties. When applied, the format values are copied to cells (not referenced by ID). This matches Excel behavior where style changes don't affect already-styled cells. Built-in styles are defined in code and never persisted. Custom styles are stored in Yjs for collaboration. ```typescript type CellStyle = { /** Unique identifier (e.g., 'good', 'heading1', 'custom-abc123') */ id: string; /** Display name shown in UI (e.g., 'Good', 'Heading 1') */ name: string; /** Category for UI grouping */ category: StyleCategory; /** The formatting properties to apply */ format: CellFormat; /** True for built-in styles, false for user-created */ builtIn: boolean; } ``` ## CellStyleCatalog ```typescript type CellStyleCatalog = { /** Ordered category metadata for categories with matching styles. */ categories: readonly CellStyleCategoryInfo[]; /** Styles matching the catalog query. */ styles: readonly CellStyle[]; } ``` ## CellStyleCategoryInfo ```typescript type CellStyleCategoryInfo = { /** Stable category identifier used by CellStyle.category. */ id: StyleCategory; /** User-facing category label. */ label: string; /** Display order within the catalog. */ order: number; } ``` ## CellStyleListOptions ```typescript type CellStyleListOptions = { /** Which style source to include. Defaults to all styles. */ source?: CellStyleSource; /** Restrict results to a single style category. */ category?: StyleCategory; } ``` ## CellStyleSource ```typescript type CellStyleSource = 'all' | 'builtIn' | 'custom' ``` ## CellType Cell type classification for `getSpecialCells()`. Matches the spreadsheet special-cell type. ```typescript enum CellType { Blanks = 'Blanks', Constants = 'Constants', Formulas = 'Formulas', Visible = 'Visible', ConditionalFormats = 'ConditionalFormats', DataValidations = 'DataValidations', } ``` ## CellValue WorkbookFunctions -- Sub-API for programmatic function invocation. Provides namespaced access to spreadsheet function evaluation without writing to any cell. Usage: `const result = await wb.functions.sum("A1:A10")` ```typescript type CellValue = string | number | boolean | null ``` ## CellValuePrimitive Primitive cell value types ```typescript type CellValuePrimitive = string | number | boolean | null ``` ## CellValueType Value type filter for `getSpecialCells()` when cellType is `Constants` or `Formulas`. Matches the spreadsheet special-cell value type. ```typescript enum CellValueType { Numbers = 'Numbers', Text = 'Text', Logicals = 'Logicals', Errors = 'Errors', } ``` ## CellWriteOptions Options controlling how a cell value is interpreted when written. ```typescript type CellWriteOptions = { /** If true, value is treated as a formula (prefixed with =) */ asFormula?: boolean; /** If true, string values starting with "=" are stored as literal text, not formulas. */ literal?: boolean; } ``` ## ChangeOrigin Origin of a change: direct write, formula recalculation, or remote collaborator. ```typescript type ChangeOrigin = 'direct' | 'cascade' | 'remote' ``` ## ChangeRecord WorksheetChanges — Sub-API for opt-in change tracking. Creates lightweight trackers that accumulate cell-level change records across mutations. Trackers are opt-in to avoid bloating return values; they return addresses + metadata only (no cell values) so callers can hydrate via getRange() when needed. Inspired by query-scoped subscriptions and transaction origin tagging. ```typescript type ChangeRecord = { /** Cell address in A1 notation (e.g. "B1"). */ address: string; /** 0-based row index. */ row: number; /** 0-based column index. */ col: number; /** What caused this change. */ origin: ChangeOrigin; /** Type of change. */ type: 'modified'; /** Value before the change (undefined if cell was previously empty). */ oldValue?: unknown; /** Value after the change (undefined if cell was cleared). */ newValue?: unknown; } ``` ## ChangeTrackOptions Options for creating a change tracker. ```typescript type ChangeTrackOptions = { /** Only track changes within this range (A1 notation, e.g. "A1:Z100"). Omit for whole-sheet. */ scope?: string; /** Exclude changes from these origin types. */ excludeOrigins?: ChangeOrigin[]; } ``` ## ChangeTracker A handle that accumulates change records across mutations. ```typescript type ChangeTracker = { /** Drain all accumulated changes since creation or last collect() call. Returns addresses + metadata only (no cell values) — call ws.getRange() to hydrate if needed. */ collect(): ChangeRecord[];; /** Stop tracking and release internal resources. */ close(): void;; /** Whether this tracker is still active (not closed). */ active: boolean; } ``` ## Chart Chart as returned by get/list operations. Extends ChartConfig with identity and metadata fields. ```typescript type Chart = { id: string; sheetId?: string; createdAt?: number; updatedAt?: number; } ``` ## ChartAreaConfig Chart area configuration ```typescript type ChartAreaConfig = { fill?: ChartFill; border?: ChartBorder; format?: ChartFormat; } ``` ## ChartBorder Shared chart border configuration (matches ChartBorderData wire type) ```typescript type ChartBorder = { color?: string; width?: number; style?: string; } ``` ## ChartColor Color: hex string for direct colors, object for theme-aware colors. ```typescript type ChartColor = string | { theme: string; tintShade?: number } ``` ## ChartConfig Public chart configuration -- the shape used by the unified API surface. This contains all user-facing fields for creating/updating charts. Internal-only fields (CellId anchors, zIndex, table linking cache) are defined in StoredChartConfig in the charts package. ```typescript type ChartConfig = { type: ChartType; /** Chart sub-type. For type-safe usage, prefer TypedChartConfig which constrains subType to match type. */ subType?: BarSubType | LineSubType | AreaSubType | StockSubType | RadarSubType; /** Anchor row (0-based) */ anchorRow: number; /** Anchor column (0-based) */ anchorCol: number; /** Chart width in cells */ width: number; /** Chart height in cells */ height: number; /** Data range in A1 notation (e.g., "A1:D10"). Optional when series[].values are provided. */ dataRange?: string; /** Series labels range in A1 notation */ seriesRange?: string; /** Category labels range in A1 notation */ categoryRange?: string; seriesOrientation?: SeriesOrientation; title?: string; subtitle?: string; legend?: LegendConfig; axis?: AxisConfig; colors?: string[]; series?: SeriesConfig[]; dataLabels?: DataLabelConfig; pieSlice?: PieSliceConfig; /** @deprecated Use trendlines[] instead — kept for backward compat */ trendline?: TrendlineConfig; /** Wire-compatible trendline array */ trendlines?: TrendlineConfig[]; /** Connect scatter points with lines (scatter-lines variant) */ showLines?: boolean; /** Use smooth curves for scatter lines (scatter-smooth-lines variant) */ smoothLines?: boolean; /** Fill area under radar lines */ radarFilled?: boolean; /** Show markers on radar vertices */ radarMarkers?: boolean; /** How blank cells are plotted: 'gap' (leave gap), 'zero' (treat as zero), 'span' (interpolate) */ displayBlanksAs?: 'gap' | 'zero' | 'span'; /** Whether to plot only visible cells (respecting row/column hiding) */ plotVisibleOnly?: boolean; /** Gap width between bars/columns as percentage (0-500). Applied to bar/column chart types. */ gapWidth?: number; /** Overlap between bars/columns (-100 to 100). Applied to clustered bar/column types. */ overlap?: number; /** Hole size for doughnut charts as percentage (10-90) */ doughnutHoleSize?: number; /** First slice angle for pie/doughnut charts in degrees (0-360) */ firstSliceAngle?: number; /** Bubble scale for bubble charts as percentage (0-300) */ bubbleScale?: number; /** Split type for of-pie charts (pie-of-pie, bar-of-pie) */ splitType?: 'auto' | 'value' | 'percent' | 'position' | 'custom'; /** Split value threshold for of-pie charts */ splitValue?: number; waterfall?: WaterfallConfig; histogram?: HistogramConfig; boxplot?: BoxplotConfig; heatmap?: HeatmapConfig; violin?: ViolinConfig; treemap?: TreemapConfig; sunburst?: SunburstConfig; regionMap?: RegionMapConfig; name?: string; chartTitle?: TitleConfig; chartArea?: ChartAreaConfig; plotArea?: PlotAreaConfig; style?: number; roundedCorners?: boolean; autoTitleDeleted?: boolean; showDataLabelsOverMaximum?: boolean; chartFormat?: ChartFormat; plotFormat?: ChartFormat; titleFormat?: ChartFormat; titleRichText?: ChartFormatString[]; titleFormula?: string; dataTable?: DataTableConfig; /** Which level of multi-level category labels to show (0-based). */ categoryLabelLevel?: number; /** Which level of multi-level series names to show (0-based). */ seriesNameLevel?: number; /** Show/hide all pivot field buttons on the chart. */ showAllFieldButtons?: boolean; /** Size of the secondary plot for PieOfPie/BarOfPie charts (5-200%). OOXML c:secondPieSize. */ secondPlotSize?: number; /** Use different colors per category. OOXML c:varyColors (chart-group level). */ varyByCategories?: boolean; /** Pivot chart display options. */ pivotOptions?: PivotChartOptions; /** Z-order command for layering charts. Accepted as a convenience field by ws.charts.update() to adjust z-index: - 'front': bring to top of stack - 'back': send to bottom of stack - 'forward': move one layer up - 'backward': move one layer down */ zOrder?: 'front' | 'back' | 'forward' | 'backward'; /** Mark shape for 3D bar/column charts (default: 'box'). Maps to OOXML c:shape. */ barShape?: 'box' | 'cylinder' | 'cone' | 'pyramid'; /** Extensible extra data for enriched chart configurations. Contains additional chart-specific settings (e.g., chartTitle font, chartArea fill) that are stored on the chart but not part of the core config schema. */ extra?: unknown; /** Chart height in points */ heightPt?: number; /** Chart width in points */ widthPt?: number; /** Left offset in points */ leftPt?: number; /** Top offset in points */ topPt?: number; /** Enable 3D bubble effect for bubble charts */ bubble3DEffect?: boolean; /** Render surface chart as wireframe */ wireframe?: boolean; /** Use surface chart top-down view (contour) */ surfaceTopView?: boolean; /** Chart color scheme index */ colorScheme?: number; } ``` ## ChartFill Fill. Maps to OOXML EG_FillProperties. ```typescript type ChartFill = | { type: 'none' } | { type: 'solid'; color: ChartColor; transparency?: number } | { type: 'gradient'; gradientType: 'linear' | 'radial' | 'rectangular'; angle?: number; stops: { position: number; color: ChartColor; transparency?: number }[]; } | { type: 'pattern'; pattern: string; foreground?: ChartColor; background?: ChartColor } ``` ## ChartFont Font. Maps to OOXML tx_pr → defRPr. ```typescript type ChartFont = { name?: string; size?: number; bold?: boolean; italic?: boolean; color?: ChartColor; underline?: | 'none' | 'single' | 'double' | 'singleAccountant' | 'doubleAccountant' | 'dash' | 'dashLong' | 'dotDash' | 'dotDotDash' | 'dotted' | 'heavy' | 'wavy' | 'wavyDouble' | 'wavyHeavy' | 'words'; strikethrough?: 'single' | 'double'; } ``` ## ChartFormat Composite format for a chart element. ```typescript type ChartFormat = { fill?: ChartFill; line?: ChartLineFormat; font?: ChartFont; textRotation?: number; shadow?: ChartShadow; } ``` ## ChartFormatString A styled text run for rich text in chart titles and data labels. ```typescript type ChartFormatString = { text: string; font?: ChartFont; } ``` ## ChartLeaderLinesFormat Leader line formatting for data labels. ```typescript type ChartLeaderLinesFormat = { format: ChartLineFormat; } ``` ## ChartLineFormat Line/border. Maps to OOXML CT_LineProperties. ```typescript type ChartLineFormat = { color?: ChartColor; width?: number; dashStyle?: 'solid' | 'dot' | 'dash' | 'dashDot' | 'longDash' | 'longDashDot' | 'longDashDotDot'; transparency?: number; } ``` ## ChartObject Chart floating object. Integrates charts with the FloatingObjectManager to provide: - Hit-testing for selection - Drag/resize/z-order operations - Consistent interaction model with other floating objects Architecture Notes: - Uses Cell Identity Model with CellIdRange references (CRDT-safe) - Full chart configuration lives in the Charts domain module - This interface provides the FloatingObject layer for interactions - Position resolution happens at render time via CellPositionLookup @example // Chart data range A1:D10 const chart: ChartObject = { id: 'chart-1', type: 'chart', sheetId: 'sheet-abc', position: { anchorType: 'oneCell', from: { cellId: '...', xOffset: 0, yOffset: 0 }, width: 400, height: 300 }, zIndex: 1, locked: false, printable: true, chartType: 'column', anchorMode: 'oneCell', widthCells: 8, heightCells: 15, chartConfig: { series: [], axes: {} }, dataRangeIdentity: { topLeftCellId: '...', bottomRightCellId: '...' } }; ```typescript type ChartObject = { type: 'chart'; /** The type of chart (bar, line, pie, etc.) */ chartType: ChartObjectType; /** How chart anchors to cells - affects resize behavior. - 'oneCell': Chart moves with anchor cell, but doesn't resize with cell changes - 'twoCell': Chart moves and resizes with both anchor cells */ anchorMode: 'oneCell' | 'twoCell'; /** Width in cell units (for oneCell mode sizing). In twoCell mode, width is determined by the anchor cell positions. */ widthCells: number; /** Height in cell units (for oneCell mode sizing). In twoCell mode, height is determined by the anchor cell positions. */ heightCells: number; /** Full chart configuration (series, axes, legend, colors, etc.). Stored directly on the floating object as a sub-object field, following the same pattern as fill/outline/shadow on shapes. */ chartConfig: Record; /** Chart data range using CellId corners (CRDT-safe). Automatically expands when rows/cols inserted between corners. Optional because some charts may have inline data or external sources. */ dataRangeIdentity?: CellIdRange; /** Series labels range using CellId corners (CRDT-safe). Used to label each data series in the chart. */ seriesRangeIdentity?: CellIdRange; /** Category labels range using CellId corners (CRDT-safe). Used for x-axis labels in most chart types. */ categoryRangeIdentity?: CellIdRange; } ``` ## ChartObjectType Supported chart types for the ChartObject. Matches the ChartType from charts package but defined here for contracts. ```typescript type ChartObjectType = | 'bar' | 'column' | 'line' | 'area' | 'pie' | 'doughnut' | 'scatter' | 'bubble' | 'combo' | 'radar' | 'stock' | 'funnel' | 'waterfall' ``` ## ChartSeriesDimension Dimension identifiers for series data access. ```typescript type ChartSeriesDimension = 'categories' | 'values' | 'bubbleSizes' ``` ## ChartShadow Shadow effect for chart elements. ```typescript type ChartShadow = { visible?: boolean; color?: ChartColor; blur?: number; offsetX?: number; offsetY?: number; transparency?: number; } ``` ## ChartType Supported chart types for spreadsheet charts ```typescript type ChartType = | 'bar' | 'column' | 'line' | 'area' | 'pie' | 'doughnut' | 'scatter' | 'bubble' | 'combo' | 'radar' | 'stock' | 'funnel' | 'waterfall' // OOXML roundtrip types | 'surface' | 'surface3d' | 'ofPie' | 'bar3d' | 'column3d' | 'line3d' | 'pie3d' | 'area3d' // Statistical chart types | 'histogram' | 'boxplot' | 'heatmap' | 'violin' | 'pareto' // Hierarchical chart types | 'treemap' | 'sunburst' // Geographic chart types | 'regionMap' // Exploded pie variants | 'pieExploded' | 'pie3dExploded' | 'doughnutExploded' // Bubble with 3D effect | 'bubble3DEffect' // Surface variants | 'surfaceWireframe' | 'surfaceTopView' | 'surfaceTopViewWireframe' // Line with markers | 'lineMarkers' | 'lineMarkersStacked' | 'lineMarkersStacked100' // Decorative 3D shape charts (cylinder) | 'cylinderColClustered' | 'cylinderColStacked' | 'cylinderColStacked100' | 'cylinderBarClustered' | 'cylinderBarStacked' | 'cylinderBarStacked100' | 'cylinderCol' // Decorative 3D shape charts (cone) | 'coneColClustered' | 'coneColStacked' | 'coneColStacked100' | 'coneBarClustered' | 'coneBarStacked' | 'coneBarStacked100' | 'coneCol' // Decorative 3D shape charts (pyramid) | 'pyramidColClustered' | 'pyramidColStacked' | 'pyramidColStacked100' | 'pyramidBarClustered' | 'pyramidBarStacked' | 'pyramidBarStacked100' | 'pyramidCol' ``` ## CheckboxControl Checkbox control - reads/writes boolean to linked cell. NO local "checked" state - value lives in cell. This is critical for single source of truth. Data flow: 1. Render: Read from cell → `checked = store.getCellValueById(linkedCellId) === true` 2. Click: Write to cell → `store.setCellValueById(linkedCellId, !checked)` 3. EventBus fires → component re-renders with new value @example // Cell A1 contains TRUE/FALSE // Checkbox linked to A1 // Formula =IF(A1, "Yes", "No") works automatically ```typescript type CheckboxControl = { type: 'checkbox'; /** REQUIRED - Cell that holds the boolean value. Uses CellId for stability across row/col insert/delete. Expected cell values: - TRUE, true, 1 → checked - FALSE, false, 0, empty → unchecked */ linkedCellId: CellId; /** Optional label displayed next to checkbox */ label?: string; /** Value to write when checked. Default: true (boolean TRUE) */ checkedValue?: unknown; /** Value to write when unchecked. Default: false (boolean FALSE) */ uncheckedValue?: unknown; } ``` ## CheckpointInfo Information about a saved checkpoint (version snapshot). ```typescript type CheckpointInfo = { /** Unique checkpoint ID */ id: string; /** Optional human-readable label */ label?: string; /** Creation timestamp (Unix ms) */ timestamp: number; } ``` ## Choose OOXML choose element for conditional layout branching. Contains one or more `if` clauses evaluated in order, and an optional `else` clause. The first `if` clause whose condition evaluates to true has its children included in the layout tree. If no `if` clause matches, the `else` clause children are used (if present). @see ECMA-376 Section 21.4.2.4 choose (Choose) ```typescript type Choose = { /** Discriminator for LayoutNodeChild union type */ kind: 'choose'; /** Optional name for this choose element. */ name: string; /** Ordered list of if-clauses. Evaluated in document order; first matching clause wins. */ ifClauses: readonly IfClause[]; /** Optional else clause. Used when no if-clause condition evaluates to true. Null if no else clause is defined. */ elseClauses: ElseClause | null; } ``` ## ChromeTheme Data Source Shared Types Types shared between `./data-sources.ts` and `./render-context.ts`. Extracted to break the cycle between those two modules — both now import from this leaf file instead of from each other. @module @mog-sdk/contracts/rendering/data-source-types ```typescript type ChromeTheme = { canvasBackground: string; gridlineColor: string; headerBackground: string; headerText: string; headerBorder: string; headerHighlightBackground: string; headerHighlightText: string; selectionFill: string; selectionBorder: string; activeCellBorder: string; fillHandleColor: string; dragSourceColor: string; dragTargetColor: string; scrollbarTrack: string; scrollbarThumb: string; } ``` ## ClearApplyTo Determines which aspects of a range to clear. Matches the spreadsheet clear-mode enum. ```typescript type ClearApplyTo = 'all' | 'contents' | 'formats' | 'hyperlinks' ``` ## ClearResult Confirmation returned by clearData() and clear(). ```typescript type ClearResult = { /** Number of cells in the cleared range. */ cellCount: number; } ``` ## CodeResult Result of a code execution. ```typescript type CodeResult = { /** Whether execution completed successfully */ success: boolean; /** Captured console output */ output?: string; /** Error message (if success is false) */ error?: string; /** Execution duration in milliseconds */ duration?: number; } ``` ## ColId ```typescript type ColId = string & { readonly [__colId]: true } ``` ## ColumnFilterCriteria Column filter criteria - what's applied to a single column. Each column in a filter range can have its own criteria. Rows must match ALL column filters (AND logic across columns). ```typescript type ColumnFilterCriteria = { /** Type of filter applied to this column. - value: Checkbox list of specific values to include - condition: Operator-based rules (equals, contains, etc.) - color: Filter by cell background or font color - top10: Top/bottom N items or percent */ type: 'value' | 'condition' | 'color' | 'top10' | 'dynamic' | 'icon'; /** For value filters: list of values to INCLUDE (show). Unchecked values in the dropdown are excluded (hidden). Include empty string or null to show blank cells. */ values?: CellValue[]; /** For value filters: explicitly include blank cells. When present, takes precedence over inferring from values array. */ includeBlanks?: boolean; /** For condition filters: one or two filter conditions. When two conditions are present, conditionLogic determines how they combine. */ conditions?: FilterCondition[]; /** Logic for combining multiple conditions. - 'and': Row must match ALL conditions - 'or': Row must match ANY condition Default: 'and' */ conditionLogic?: 'and' | 'or'; /** For color filters: filter by fill (background) or font color. */ colorFilter?: { /** * Which color axis to filter on. * * Vocabulary matches Excel/ECMA-376: `'fill'` is the cell's background * fill color; `'font'` is the text color. (Renamed from `'background'` * to `'fill'` so the filter discriminator lines up with the rest of the * filter/sort surface and the harness probe.) */ type: 'fill' | 'font'; /** Hex color to match (e.g., '#ff0000') */ color: string; }; /** For top/bottom N filters: show only the highest or lowest values. */ topBottom?: { /** Show top values or bottom values */ type: 'top' | 'bottom'; /** Number of items or percentage */ count: number; /** Whether count is number of items or percentage */ by: 'items' | 'percent' | 'sum'; }; /** For dynamic filters: a pre-defined rule resolved against live data. Examples: above average, below average, today, this month, etc. */ dynamicFilter?: { /** The dynamic filter rule to apply */ rule: DynamicFilterRule; }; /** For icon filters: filter by conditional formatting icon. Requires an icon set CF rule on the column. Rows are shown only if the evaluated icon matches the specified set + index. */ iconFilter?: { /** Icon set name (e.g. "3Arrows", "4Rating") */ iconSet: string; /** Icon index within the set (0-based) */ iconIndex: number; }; } ``` ## ColumnMapping Column mapping for a sheet data binding. ```typescript type ColumnMapping = { /** Column index to write to (0-indexed) */ columnIndex: number; /** JSONPath or field name to extract from data */ dataPath: string; /** Optional transform formula (receives value as input) */ transform?: string; /** Header text (if headerRow >= 0) */ headerText?: string; } ``` ## ComboBoxControl ComboBox control - dropdown selection linked to cell. NO local "selectedIndex" state - value lives in cell. Cell stores the selected VALUE (string), not the index. Data flow: 1. Render: Read from cell → find matching item index 2. Select: Write to cell → `store.setCellValueById(linkedCellId, selectedItem)` 3. EventBus fires → component re-renders with new selection Items can be: - Static: `items: ['Option A', 'Option B', 'Option C']` - Dynamic: `itemsSourceRef: { startId: 'abc', endId: 'xyz' }` (range of cells) ```typescript type ComboBoxControl = { type: 'comboBox'; /** REQUIRED - Cell that holds the selected value. Uses CellId for stability across row/col insert/delete. Stores the selected item VALUE (string), not index. This makes formulas like =VLOOKUP(A1, ...) work naturally. */ linkedCellId: CellId; /** Static items list. Use this for fixed options that don't change. */ items?: string[]; /** Dynamic items from a cell range. Uses IdentityRangeRef (CellId-based) for stability. Range values are read at render time. If both `items` and `itemsSourceRef` are set, `itemsSourceRef` takes precedence. */ itemsSourceRef?: IdentityRangeRef; /** Placeholder text when no value is selected. */ placeholder?: string; /** Whether to allow typing to filter items. Default: true */ filterable?: boolean; } ``` ## Comment ```typescript type Comment = { id: string; cellRef: string; author: string; authorId?: string; authorEmail?: string; content: string | null; runs: RichTextRun[]; threadId: string | null; parentId: string | null; personId?: string; resolved?: boolean; timestamp?: string; createdAt: number | null; modifiedAt: number | null; xrUid?: string; shapeId?: number; extLstXml?: string; contentType?: CommentContentType; mentions?: CommentMention[]; commentType: CommentType; visible?: boolean; noteHeight?: number; noteWidth?: number; } ``` ## CommentContentType Distinguishes plain text comments from those containing @mentions. ```typescript type CommentContentType = 'plain' | 'mention' ``` ## CommentMention A mention of a user within a comment's rich text content. ```typescript type CommentMention = { displayText: string; userId: string; email?: string; startIndex: number; length: number; } ``` ## CommentType Whether a comment is a legacy note or a modern threaded comment. ```typescript type CommentType = 'note' | 'threadedComment' ``` ## CommentUpdate Options for updating an existing comment via `comments.update()`. ```typescript type CommentUpdate = { /** New plain-text content for the comment. */ text?: string; /** @mentions to embed in the comment (implies content_type = Mention). */ mentions?: CommentMention[]; } ``` ## CompoundLine Compound line type for multi-line strokes. Maps to ST_CompoundLine (ECMA-376, dml-main.xsd). Uses camelCase variants; bridge uses PascalCase. ```typescript type CompoundLine = 'sng' | 'dbl' | 'thickThin' | 'thinThick' | 'tri' ``` ## CompoundLineStyle Compound line style. ```typescript type CompoundLineStyle = 'single' | 'double' | 'thickThin' | 'thinThick' | 'triple' ``` ## ComputedConnector Computed connector between two nodes. ```typescript type ComputedConnector = { /** Source node ID */ fromNodeId: NodeId; /** Target node ID */ toNodeId: NodeId; /** Connector type */ connectorType: ConnectorType; /** Path data for rendering */ path: ConnectorPath; /** Stroke color (CSS color string) */ stroke: string; /** Stroke width in pixels */ strokeWidth: number; /** Arrow head at start of connector */ arrowStart?: ArrowHead; /** Arrow head at end of connector */ arrowEnd?: ArrowHead; } ``` ## ComputedLayout Computed layout result (runtime cache, NOT persisted to Yjs). This is calculated by layout algorithms and cached by the bridge. Invalidated whenever the diagram structure or styling changes. Layout computation is expensive, so this cache avoids recalculating positions on every render. ```typescript type ComputedLayout = { /** Computed shape positions and styles for each node */ shapes: ComputedShape[]; /** Computed connector paths between nodes */ connectors: ComputedConnector[]; /** Overall bounds of the rendered diagram */ bounds: { width: number; height: number }; /** Version number, incremented on each layout change */ version: number; } ``` ## ComputedShape Computed shape position and style for a single node. Contains all information needed to render a node's shape. ```typescript type ComputedShape = { /** The node this shape represents */ nodeId: NodeId; /** Shape type to render */ shapeType: SmartArtShapeType; /** X position in pixels (relative to diagram origin) */ x: number; /** Y position in pixels (relative to diagram origin) */ y: number; /** Width in pixels */ width: number; /** Height in pixels */ height: number; /** Rotation angle in degrees */ rotation: number; /** Fill color (CSS color string) */ fill: string; /** Stroke/border color (CSS color string) */ stroke: string; /** Stroke width in pixels */ strokeWidth: number; /** Text content to display */ text: string; /** Text styling */ textStyle: TextStyle; /** Visual effects (shadow, glow, etc.) */ effects: ShapeEffects; } ``` ## ConditionalFormat A conditional format definition — associates rules with cell ranges. This is the public API type. The kernel stores additional internal fields (CellIdRange for CRDT-safe structure change handling) that are resolved to position-based ranges before being returned through the API. ```typescript type ConditionalFormat = { /** Unique format identifier. */ id: string; /** Sheet this format belongs to. */ sheetId?: string; /** Whether this CF was created from a pivot table. */ pivot?: boolean; /** Cell ranges this format applies to. */ ranges: CellRange[]; /** CellId-based range identities for CRDT-safe tracking. */ rangeIdentities?: { topLeftCellId: string; bottomRightCellId: string }[]; /** Rules to evaluate (sorted by priority). */ rules: CFRule[]; } ``` ## ConditionalFormatUpdate Update payload for a conditional format. ```typescript type ConditionalFormatUpdate = { /** Replace the rules array. */ rules?: CFRule[]; /** Replace the ranges this format applies to. */ ranges?: CellRange[]; /** Set stopIfTrue on all rules in this format. */ stopIfTrue?: boolean; } ``` ## ConnectorHandle ```typescript type ConnectorHandle = { /** Update connector routing, endpoints, fill, outline. ConnectorConfig pending — uses generic record. */ update(props: Record): Promise;; duplicate(offsetX?: number, offsetY?: number): Promise;; getData(): Promise;; } ``` ## ConnectorObject Connector floating object. A line or connector shape that links two objects (or floats freely). Connectors have optional arrowheads and connection site bindings. ```typescript type ConnectorObject = { type: 'connector'; /** Connector shape preset (e.g., straightConnector1, bentConnector3) */ shapeType: ShapeType; /** Start connection binding (which shape and site index) */ startConnection?: { shapeId: string; siteIndex: number }; /** End connection binding (which shape and site index) */ endConnection?: { shapeId: string; siteIndex: number }; /** Fill configuration */ fill?: ObjectFill; /** Outline/stroke configuration (includes arrowheads) */ outline?: ShapeOutline; } ``` ## ConnectorPath Path data for rendering a connector. ```typescript type ConnectorPath = { /** Path type */ type: 'line' | 'bezier' | 'polyline'; /** Points along the path */ points: Array<{ x: number; y: number }>; /** Control points for bezier curves */ controlPoints?: Array<{ x: number; y: number }>; } ``` ## ConnectorType Type of connector line between nodes. ```typescript type ConnectorType = 'straight' | 'elbow' | 'curved' | 'none' ``` ## CopyFromOptions Options for Range.copyFrom() operation. ```typescript type CopyFromOptions = { /** What to copy — defaults to 'all'. */ copyType?: CopyType; /** Skip blank source cells (preserve target values where source is empty). */ skipBlanks?: boolean; /** Transpose rows ↔ columns during copy. */ transpose?: boolean; } ``` ## CopyType Specifies what data to copy in a range copy operation. Maps to the spreadsheet range-copy mode. ```typescript type CopyType = 'all' | 'formulas' | 'values' | 'formats' ``` ## CreateBindingConfig Configuration for creating a sheet data binding. ```typescript type CreateBindingConfig = { /** Connection providing the data */ connectionId: string; /** Maps data fields to columns */ columnMappings: ColumnMapping[]; /** Auto-insert/delete rows to match data length (default: true) */ autoGenerateRows?: boolean; /** Row index for headers (-1 = no header row, default: 0) */ headerRow?: number; /** First row of data (0-indexed, default: 1) */ dataStartRow?: number; /** Preserve header row formatting on refresh (default: true) */ preserveHeaderFormatting?: boolean; } ``` ## CreateCheckboxOptions Options for creating a checkbox control. ```typescript type CreateCheckboxOptions = { /** Sheet to create in */ sheetId: SheetId; /** Anchor position (row, col, offsets) - converted to CellId internally */ anchor: { row: number; col: number; xOffset?: number; yOffset?: number }; /** Cell to link (row, col) - converted to CellId internally */ linkedCell: { row: number; col: number }; /** Optional label */ label?: string; /** Optional size override */ width?: number; height?: number; } ``` ## CreateComboBoxOptions Options for creating a comboBox control. ```typescript type CreateComboBoxOptions = { /** Sheet to create in */ sheetId: SheetId; /** Anchor position */ anchor: { row: number; col: number; xOffset?: number; yOffset?: number }; /** Cell to link for selected value */ linkedCell: { row: number; col: number }; /** Static items list */ items?: string[]; /** Dynamic items source range (row/col based, converted to CellId) */ itemsSource?: { startRow: number; startCol: number; endRow: number; endCol: number; }; /** Placeholder text */ placeholder?: string; /** Optional size override */ width?: number; height?: number; } ``` ## CreateDataTableOptions Persistent Data Table creation options. `tableRange` is the full anchor-inclusive table selection. The worksheet is implied by the Worksheet API instance. ```typescript type CreateDataTableOptions = { /** Full A1 range selected for the Data Table, including formula/header cells. */ tableRange: string; /** Excel row input cell. It receives top-row header values. */ rowInputCell?: string | null; /** Excel column input cell. It receives left-column header values. */ colInputCell?: string | null; } ``` ## CreateDataTableResult Result of creating a persistent Data Table region. ```typescript type CreateDataTableResult = { regionId: string; tableRange: string; bodyRange: string; rowInputCell?: string | null; colInputCell?: string | null; rowsComputed: number; colsComputed: number; cellCount: number; } ``` ## CreateDrawingOptions Options for creating a new drawing object. ```typescript type CreateDrawingOptions = { /** Optional name for the drawing object */ name?: string; /** Alt text for accessibility */ altText?: string; /** Whether the drawing is locked */ locked?: boolean; /** Whether the drawing appears in print */ printable?: boolean; /** Initial background color */ backgroundColor?: string; /** Initial tool settings */ toolState?: Partial; } ``` ## CreateNamesFromSelectionOptions Options for creating named ranges from row/column labels in a selection. ```typescript type CreateNamesFromSelectionOptions = { /** Create names from labels in the top row of the selection. */ top?: boolean; /** Create names from labels in the left column of the selection. */ left?: boolean; /** Create names from labels in the bottom row of the selection. */ bottom?: boolean; /** Create names from labels in the right column of the selection. */ right?: boolean; } ``` ## CreateNamesResult Result of a create-names-from-selection operation. ```typescript type CreateNamesResult = { /** Number of names successfully created. */ success: number; /** Number of names skipped (already exist or invalid). */ skipped: number; } ``` ## CreateSparklineGroupOptions Options for creating a sparkline group. ```typescript type CreateSparklineGroupOptions = { /** Whether data is in rows (true) or columns (false) */ dataInRows?: boolean; /** Shared visual settings */ visual?: Partial; /** Shared axis settings */ axis?: Partial; } ``` ## CreateSparklineOptions Options for creating a new sparkline. ```typescript type CreateSparklineOptions = { /** Whether data is in rows (true) or columns (false) */ dataInRows?: boolean; /** Visual settings override */ visual?: Partial; /** Axis settings override */ axis?: Partial; } ``` ## CreateWordArtInput Configuration for creating new text effects. ```typescript type CreateWordArtInput = { /** Text content. */ text: string; /** Text warp preset. Missing values are filled by kernel defaults. */ warpPreset?: TextWarpPreset; /** Warp adjustment values. */ warpAdjustments?: AdjustmentValues; /** Text fill configuration. Missing values are filled by kernel defaults. */ fill?: WordArtFill; /** Text outline configuration. Missing values are filled by kernel defaults. */ outline?: WordArtOutline; /** Text effects configuration. Missing values are filled by kernel defaults. */ effects?: TextEffects; /** Visual text-effect configuration overrides. */ wordArt?: Partial; /** X position in pixels. */ x?: number; /** Y position in pixels. */ y?: number; /** Width in pixels. */ width?: number; /** Height in pixels. */ height?: number; /** Display name. */ name?: string; } ``` ## CreateWorkbookLinkInput ```typescript type CreateWorkbookLinkInput = { linkId?: LinkId; expectedWorkbookId?: WorkbookId | null; target: PersistedLinkTarget; displayName: string; sourceKind: WorkbookLinkSourceKind; importedExcelIdentity?: ImportedExternalLinkIdentity; materializedCacheMetadata?: AuthorizedMaterializedCacheMetadata; } ``` ## CrossFilterMode ST_SlicerCacheCrossFilter mode. Canonical source: compute-types.gen.ts ```typescript type CrossFilterMode = 'none' | 'showItemsWithDataAtTop' | 'showItemsWithNoData' ``` ## CultureInfo Complete culture information for formatting numbers, dates, and currencies. All properties are required - no partial cultures allowed. Use the culture registry to get complete CultureInfo objects. @example ```typescript const culture = getCulture('de-DE'); // culture.decimalSeparator === ',' // culture.thousandsSeparator === '.' // culture.monthNames[0] === 'Januar' ``` ```typescript type CultureInfo = { /** IETF language tag (e.g., 'en-US', 'de-DE', 'ja-JP'). This is the key used to look up the culture in the registry. */ name: string; /** Human-readable display name (e.g., 'English (United States)'). Used in UI dropdowns. */ displayName: string; /** Native name in the culture's own language (e.g., 'Deutsch (Deutschland)'). */ nativeName: string; /** ISO 639-1 two-letter language code (e.g., 'en', 'de', 'ja'). */ twoLetterLanguageCode: string; /** Decimal separator character (e.g., '.' for en-US, ',' for de-DE). */ decimalSeparator: string; /** Thousands/grouping separator (e.g., ',' for en-US, '.' for de-DE, ' ' for fr-FR). */ thousandsSeparator: string; /** Negative sign (usually '-'). */ negativeSign: string; /** Positive sign (usually '+' or ''). */ positiveSign: string; /** Pattern for negative numbers. */ negativeNumberPattern: NegativeNumberPattern; /** Number of digits per group (usually 3). Some cultures use variable grouping (e.g., Indian: 3, then 2, 2, 2...). For simplicity, we use a single value in v1. */ numberGroupSize: number; /** Percent symbol (usually '%'). */ percentSymbol: string; /** Per mille symbol (‰). */ perMilleSymbol: string; /** Pattern for positive percentages. */ percentPositivePattern: PercentPositivePattern; /** Pattern for negative percentages. */ percentNegativePattern: PercentNegativePattern; /** Default currency symbol for this culture (e.g., '$', '€', '¥'). */ currencySymbol: string; /** ISO 4217 currency code (e.g., 'USD', 'EUR', 'JPY'). */ currencyCode: string; /** Pattern for positive currency values. */ currencyPositivePattern: CurrencyPositivePattern; /** Pattern for negative currency values. */ currencyNegativePattern: CurrencyNegativePattern; /** Number of decimal digits for currency (e.g., 2 for USD, 0 for JPY). */ currencyDecimalDigits: number; /** Date separator (e.g., '/' for en-US, '.' for de-DE). */ dateSeparator: string; /** Time separator (e.g., ':'). */ timeSeparator: string; /** Short date pattern (e.g., 'M/d/yyyy' for en-US, 'dd.MM.yyyy' for de-DE). Used for format code interpretation. */ shortDatePattern: string; /** Long date pattern (e.g., 'dddd, MMMM d, yyyy'). */ longDatePattern: string; /** Short time pattern (e.g., 'h:mm tt' for en-US, 'HH:mm' for de-DE). */ shortTimePattern: string; /** Long time pattern (e.g., 'h:mm:ss tt' for en-US, 'HH:mm:ss' for de-DE). */ longTimePattern: string; /** AM designator (e.g., 'AM' for en-US, '' for 24-hour cultures). */ amDesignator: string; /** PM designator (e.g., 'PM' for en-US, '' for 24-hour cultures). */ pmDesignator: string; /** First day of the week (0 = Sunday, 1 = Monday). */ firstDayOfWeek: DayOfWeek; /** Full month names (12 entries, January = index 0). */ monthNames: readonly [ string, string, string, string, string, string, string, string, string, string, string, string, ]; /** Abbreviated month names (12 entries, Jan = index 0). */ abbreviatedMonthNames: readonly [ string, string, string, string, string, string, string, string, string, string, string, string, ]; /** Full day names (7 entries, Sunday = index 0). */ dayNames: readonly [string, string, string, string, string, string, string]; /** Abbreviated day names (7 entries, Sun = index 0). */ abbreviatedDayNames: readonly [string, string, string, string, string, string, string]; /** Shortest day names (7 entries, typically 1-2 letters). Used in narrow calendar UIs. */ shortestDayNames: readonly [string, string, string, string, string, string, string]; /** String for TRUE value (e.g., 'TRUE', 'WAHR', 'VRAI'). */ trueString: string; /** String for FALSE value (e.g., 'FALSE', 'FALSCH', 'FAUX'). */ falseString: string; /** List separator (e.g., ',' for en-US, ';' for de-DE). This affects function argument separators in formulas. */ listSeparator: string; } ``` ## CurrencyNegativePattern Currency negative pattern (matches .NET NumberFormatInfo). Determines how negative currency values are displayed. 0 = ($n) - en-US accounting 1 = -$n - en-US standard 2 = $-n 3 = $n- 4 = (n$) 5 = -n$ 6 = n-$ 7 = n$- 8 = -n $ - de-DE 9 = -$ n 10 = n $- 11 = $ n- 12 = $ -n 13 = n- $ 14 = ($ n) 15 = (n $) ```typescript type CurrencyNegativePattern = | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 ``` ## CurrencyPositivePattern Currency positive pattern (matches .NET NumberFormatInfo). Determines where the currency symbol appears relative to the number. 0 = $n (symbol before, no space) - en-US 1 = n$ (symbol after, no space) 2 = $ n (symbol before, space) 3 = n $ (symbol after, space) - de-DE, fr-FR ```typescript type CurrencyPositivePattern = 0 | 1 | 2 | 3 ``` ## CustomList Custom Lists Types Type definitions for user-defined fill lists. Runtime constant (BUILT_IN_LISTS) has been moved to @mog-sdk/kernel/domain/fill/custom-lists. @see plans/active/excel-parity/10-FILL-AUTOFILL-PLAN.md ```typescript type CustomList = { /** Unique ID for the list */ id: string; /** Display name for the list */ name: string; /** The list values in order */ values: string[]; /** Whether this is a built-in list (cannot be deleted) */ isBuiltIn?: boolean; } ``` ## DataLabelConfig Data label configuration (matches DataLabelData wire type) ```typescript type DataLabelConfig = { show: boolean; position?: | 'center' | 'insideEnd' | 'insideBase' | 'outsideEnd' | 'left' | 'right' | 'top' | 'bottom' | 'bestFit' | 'callout' | 'outside' | 'inside'; format?: string; showValue?: boolean; showCategoryName?: boolean; /** @deprecated Use showCategoryName instead. Alias kept for legacy consumers. */ showCategory?: boolean; showSeriesName?: boolean; showPercentage?: boolean; /** @deprecated Use showPercentage instead. Alias kept for legacy consumers. */ showPercent?: boolean; showBubbleSize?: boolean; showLegendKey?: boolean; separator?: string; showLeaderLines?: boolean; text?: string; visualFormat?: ChartFormat; numberFormat?: string; /** Text orientation angle in degrees (-90 to 90) */ textOrientation?: number; richText?: ChartFormatString[]; /** Whether the label auto-generates text from data. */ autoText?: boolean; /** Horizontal text alignment. */ horizontalAlignment?: 'left' | 'center' | 'right' | 'justify' | 'distributed'; /** Vertical text alignment. */ verticalAlignment?: 'top' | 'middle' | 'bottom' | 'justify' | 'distributed'; /** Whether the number format is linked to the source data cell format. */ linkNumberFormat?: boolean; /** Callout shape type (e.g., 'rectangle', 'roundRectangle', 'wedgeRoundRectCallout'). */ geometricShapeType?: string; /** Formula-based label text. */ formula?: string; /** X position in points (read-only, populated from render engine). */ left?: number; /** Y position in points (read-only, populated from render engine). */ top?: number; /** Height in points (read-only, populated from render engine). */ height?: number; /** Width in points (read-only, populated from render engine). */ width?: number; /** Leader line formatting configuration. */ leaderLinesFormat?: ChartLeaderLinesFormat; } ``` ## DataSourceType The type of data source backing a pivot table. Mirrors the workbook data source type. ```typescript type DataSourceType = 'range' | 'table' | 'external' ``` ## DataTableConfig Data table configuration (matches ChartDataTableData wire type). ```typescript type DataTableConfig = { showHorzBorder?: boolean; showVertBorder?: boolean; showOutline?: boolean; showKeys?: boolean; format?: ChartFormat; /** Whether to show legend keys in the data table */ showLegendKey?: boolean; /** Whether the data table is visible */ visible?: boolean; } ``` ## DataTableResult Result of Data Table operation. ```typescript type DataTableResult = { /** 2D array of computed results. results[rowIndex][colIndex] is the value when: - rowInputCell = rowValues[rowIndex] - colInputCell = colValues[colIndex] */ results: CellValue[][]; /** Total number of cells computed. */ cellCount: number; /** Time taken in milliseconds. */ elapsedMs: number; /** Whether the operation was cancelled. */ cancelled?: boolean; } ``` ## DatePeriod Date periods for timePeriod rules. ```typescript type DatePeriod = | 'yesterday' | 'today' | 'tomorrow' | 'last7Days' | 'lastWeek' | 'thisWeek' | 'nextWeek' | 'lastMonth' | 'thisMonth' | 'nextMonth' | 'lastQuarter' | 'thisQuarter' | 'nextQuarter' | 'lastYear' | 'thisYear' | 'nextYear' ``` ## DateUnit Unit for date-based series fills. ```typescript type DateUnit = 'day' | 'weekday' | 'month' | 'year' ``` ## DayOfWeek Culture/Locale types for internationalized number, date, and currency formatting. Stream G: Culture & Localization Design principles: 1. CultureInfo is immutable and complete - no partial definitions 2. Culture is workbook-level state (persisted in WorkbookSettings.culture) 3. Format codes are culture-agnostic; culture applies at render time 4. Uses IETF language tags (en-US, de-DE) not Windows locale IDs ```typescript type DayOfWeek = 0 | 1 | 2 | 3 | 4 | 5 | 6 ``` ## DeleteCellsReceipt Receipt for a deleteCellsWithShift mutation. ```typescript type DeleteCellsReceipt = { kind: 'deleteCells'; sheetId: string; range: { startRow: number; startCol: number; endRow: number; endCol: number }; direction: 'left' | 'up'; } ``` ## DeleteColumnsReceipt Receipt for a deleteColumns mutation. ```typescript type DeleteColumnsReceipt = { kind: 'deleteColumns'; sheetId: string; deletedAt: number; count: number; } ``` ## DeleteRowsReceipt Receipt for a deleteRows mutation. ```typescript type DeleteRowsReceipt = { kind: 'deleteRows'; sheetId: string; deletedAt: number; count: number; } ``` ## DelimiterNode Delimiter - Parentheses, brackets, braces, etc. ```typescript type DelimiterNode = { type: 'd'; /** Beginning character (default '(') */ begChr?: string; /** Separator character (default '|') */ sepChr?: string; /** Ending character (default ')') */ endChr?: string; /** Grow with content */ grow?: boolean; /** Shape: 'centered' or 'match' */ shp?: 'centered' | 'match'; /** Content elements (separated by sepChr) */ e: MathNode[][]; } ``` ## Direction Cardinal directions for keyboard navigation and commit actions. ```typescript type Direction = 'up' | 'down' | 'left' | 'right' ``` ## DocumentId ```typescript type DocumentId = string ``` ## DocumentProperties ```typescript type DocumentProperties = { title?: string; creator?: string; description?: string; subject?: string; created?: string; modified?: string; lastModifiedBy?: string; category?: string; keywords?: string; company?: string; manager?: string; } ``` ## DrawingHandle ```typescript type DrawingHandle = { addStroke(stroke: InkStroke): Promise;; eraseStrokes(strokeIds: StrokeId[]): Promise;; clearStrokes(): Promise;; moveStrokes(strokeIds: StrokeId[], dx: number, dy: number): Promise;; transformStrokes(strokeIds: StrokeId[], transform: StrokeTransformParams): Promise;; findStrokesAtPoint(x: number, y: number, tolerance?: number): Promise;; duplicate(offsetX?: number, offsetY?: number): Promise;; getData(): Promise;; } ``` ## DrawingObject Drawing object floating on the spreadsheet. Extends FloatingObjectBase to integrate with the existing floating object system (selection, drag, resize, z-order, etc.). CRDT-SAFE DESIGN: - Strokes stored as Map to avoid array ordering conflicts - Uses CellId for anchors (survives row/col insert/delete) - Y.Map under the hood for concurrent editing support ```typescript type DrawingObject = { type: 'drawing'; /** Strokes in this drawing, keyed by StrokeId. Using Map instead of array for CRDT safety: - No ordering conflicts when concurrent users add strokes - O(1) lookup/delete by ID - Stable references across edits Render order is determined by stroke createdAt timestamps. */ strokes: Map; /** Current tool settings for this drawing. Persisted per-drawing to remember user preferences. */ toolState: InkToolState; /** Recognition results for strokes in this drawing. Maps from a "recognition ID" to the result. A recognition can be: - A shape recognized from one or more strokes - Text recognized from handwriting strokes */ recognitions: Map; /** Background color of the drawing canvas. - undefined = transparent (shows sheet grid) - CSS color string = solid background */ backgroundColor?: string; } ``` ## DynamicFilterRule Dynamic filter rule — pre-defined filter rules that resolve against live data (e.g. above average, date-relative). Mirrors the Rust DynamicFilterRule enum in compute-core. ```typescript type DynamicFilterRule = | 'aboveAverage' | 'belowAverage' | 'today' | 'yesterday' | 'tomorrow' | 'thisWeek' | 'lastWeek' | 'nextWeek' | 'thisMonth' | 'lastMonth' | 'nextMonth' | 'thisQuarter' | 'lastQuarter' | 'nextQuarter' | 'thisYear' | 'lastYear' | 'nextYear' ``` ## ElseClause OOXML else-clause within a choose element. Contains layout children that are used when no if-clause condition evaluates to true. Acts as the default/fallback branch. @see ECMA-376 Section 21.4.2.11 else (Else) ```typescript type ElseClause = { /** Optional name for this else-clause. */ name: string; /** Child layout elements included when no if-clause matches. */ children: readonly LayoutNodeChild[]; } ``` ## EmptyCellDisplay ```typescript type EmptyCellDisplay = "gaps" | "zero" | "connect" ``` ## EnterKeyDirection Direction for enter key movement after committing an edit. Issue 8: Settings Panel ```typescript type EnterKeyDirection = 'down' | 'right' | 'up' | 'left' | 'none' ``` ## EqArrayNode Equation Array - Vertically aligned equations ```typescript type EqArrayNode = { type: 'eqArr'; /** Base justification */ baseJc?: 'top' | 'center' | 'bottom'; /** Maximum distribution */ maxDist?: boolean; /** Object distribution */ objDist?: boolean; /** Row spacing rule */ rSpRule?: 0 | 1 | 2 | 3 | 4; /** Row spacing value */ rSp?: number; /** Array rows */ e: MathNode[][]; } ``` ## Equation Main equation data model ```typescript type Equation = { /** Unique equation identifier */ id: EquationId; /** OMML XML string - the canonical storage format. This is what gets written to XLSX files. Example: ...... */ omml: string; /** LaTeX source (optional, for display/editing). Not stored in XLSX - regenerated from OMML on import if needed. */ latex?: string; /** Parsed AST (computed, not persisted). Used for rendering. Regenerated from OMML when needed. */ ast?: MathNode; /** Cached rendered image as data URL. Invalidated when equation changes. */ _cachedImageData?: string; /** Style options */ style: EquationStyle; } ``` ## EquationConfig Configuration for creating a new equation. ```typescript type EquationConfig = { /** LaTeX source for the equation. */ latex: string; /** Anchor cell as `{row, col}`. When set, `x`/`y` are offsets from this cell instead of from cell `(0, 0)`. */ anchorCell?: { row: number; col: number }; /** X position in pixels. */ x?: number; /** Y position in pixels. */ y?: number; /** Width in pixels. */ width?: number; /** Height in pixels. */ height?: number; /** Equation style options. */ style?: EquationStyleConfig; } ``` ## EquationDefaults Fully normalized equation defaults used by Worksheet equation creation. ```typescript type EquationDefaults = { /** Fully populated default equation style. */ style: EquationStyle; /** Default equation object width in pixels. */ width: number; /** Default equation object height in pixels. */ height: number; } ``` ## EquationHandle ```typescript type EquationHandle = { update(props: EquationUpdates): Promise;; duplicate(offsetX?: number, offsetY?: number): Promise;; getData(): Promise;; } ``` ## EquationId Unique identifier for an equation ```typescript type EquationId = string & { readonly __brand: 'EquationId' } ``` ## EquationJustification Equation justification within its bounding box ```typescript type EquationJustification = 'left' | 'center' | 'right' | 'centerGroup' ``` ## EquationObject Equation floating object. Contains a mathematical equation rendered as a floating object. ```typescript type EquationObject = { type: 'equation'; /** The equation data */ equation: Equation; } ``` ## EquationStyle Equation rendering style options ```typescript type EquationStyle = { /** Math font family */ fontFamily: MathFont; /** Base font size in points */ fontSize: number; /** Text color (CSS color string) */ color: string; /** Background color (CSS color string, 'transparent' for none) */ backgroundColor: string; /** Justification */ justification: EquationJustification; /** Display mode (block) vs inline mode */ displayMode: boolean; /** Use small fractions (numerator/denominator same size as surrounding) */ smallFractions: boolean; } ``` ## EquationStyleConfig Styling overrides for an equation. Missing fields are filled by kernel defaults. ```typescript type EquationStyleConfig = Partial ``` ## EquationUpdates Updates for an existing equation. ```typescript type EquationUpdates = { /** Updated LaTeX source. */ latex?: string; /** Updated OMML XML. */ omml?: string; /** Updated style options. */ style?: Partial; } ``` ## ErrorBarConfig Error bar configuration for series (matches ErrorBarData wire type) ```typescript type ErrorBarConfig = { visible?: boolean; direction?: string; barType?: string; valueType?: string; value?: number; noEndCap?: boolean; lineFormat?: ChartLineFormat; } ``` ## ExecuteOptions Options for code execution via `workbook.executeCode()`. ```typescript type ExecuteOptions = { /** Maximum execution time in milliseconds */ timeout?: number; /** Whether to run in a sandboxed environment */ sandbox?: boolean; } ``` ## FieldDef Schema-Driven Initialization Types These types define how Yjs structures are specified declaratively. All creation, copying, and lazy-init is derived from schemas. ARCHITECTURE: Single Source of Truth - Field definitions are declared ONCE in a schema - createFromSchema() derives structure initialization - copyFromSchema() derives copy behavior - ensureLazyFields() derives migration behavior This eliminates: - Manual field enumeration in multiple places - Divergent copy vs init logic - Missing fields in new code paths @see plans/active/refactor/SCHEMA-DRIVEN-INITIALIZATION.md ```typescript type FieldDef = { /** The Yjs type or primitive indicator. - 'Y.Map': Creates new Y.Map() - 'Y.Array': Creates new Y.Array() - 'Y.Text': Creates new Y.Text() - 'primitive': Uses the default value directly */ type: 'Y.Map' | 'Y.Array' | 'Y.Text' | 'primitive'; /** Documentation of the value type for Y.Map and Y.Array. Example: 'SerializedCellData' for cells map, 'number' for heights map. This is for documentation only - TypeScript cannot enforce Yjs internals. */ valueType?: string; /** Short name for CRDT storage efficiency (optional). Used by Cell Data schema where 'raw' -> 'r', 'formula' -> 'f', etc. If not specified, the long name (schema key) is used as-is. This is for documentation/mapping purposes. The actual Yjs storage uses the short name, while the API/runtime uses the long name (schema key). */ shortName?: string; /** Whether this field is required during structure creation. - true: Created by createFromSchema() - false: Only created on demand or via lazyInit */ required: boolean; /** Copy strategy for this field. - 'deep': Deep copy (JSON.parse/stringify for plain objects, recursive for Yjs) - 'shallow': Shallow reference copy (same object) - 'skip': Don't copy this field (omit from result) */ copy: 'deep' | 'shallow' | 'skip'; /** Whether to auto-create this field if missing. Used for migration: old documents may lack new fields. ensureLazyFields() creates fields where lazyInit=true and field is missing. */ lazyInit: boolean; /** Default value for primitive fields. Only used when type='primitive'. */ default?: unknown; } ``` ## FillDirection Direction of a fill operation relative to the source range. ```typescript type FillDirection = 'down' | 'right' | 'up' | 'left' ``` ## FillPatternType Pattern type detected by the fill engine. ```typescript type FillPatternType = | 'copy' | 'linear' | 'growth' | 'date' | 'time' | 'weekday' | 'weekdayShort' | 'month' | 'monthShort' | 'quarter' | 'ordinal' | 'textWithNumber' | 'customList' ``` ## FillSeriesOptions Options for the Fill Series dialog (Edit > Fill > Series). ```typescript type FillSeriesOptions = { direction: FillDirection; seriesType: 'linear' | 'growth' | 'date'; stepValue: number; stopValue?: number; dateUnit?: DateUnit; trend?: boolean; } ``` ## FillType Fill type for shapes, text boxes, and connectors. Matches the Rust `FillType` enum in `domain-types`. ```typescript type FillType = 'solid' | 'gradient' | 'pattern' | 'pictureAndTexture' | 'none' ``` ## FilterByColorOptions Options for {@link WorksheetFilters.byColor}. Excel/ECMA-376 vocabulary: `'fill'` matches the cell background fill color; `'font'` matches the cell font color. Both compare the resolved per-cell effective format (direct cell formatting; CF-derived colors are not yet supported — see plans/active/ux/filter/round-1/). ```typescript type FilterByColorOptions = { /** Whether to filter by background fill color or font color. */ colorType: 'fill' | 'font'; /** Hex color to match (e.g. '#FFFF00'). Case-insensitive. */ color: string; /** Optional filter ID; defaults to the first auto-filter on the sheet. */ filterId?: string; } ``` ## FilterCondition A single filter condition with operator and value(s). Used in condition filters where users specify rules like "greater than 100" or "contains 'error'". ```typescript type FilterCondition = { /** The comparison operator */ operator: FilterOperator; /** Primary comparison value (not used for isBlank/isNotBlank) */ value?: CellValue; /** Secondary value for 'between' operator (inclusive range) */ value2?: CellValue; } ``` ## FilterDetailInfo Detailed filter information including resolved numeric range and column filters. ```typescript type FilterDetailInfo = { /** Filter ID */ id: string; /** Filter kind. */ filterKind: FilterKind; /** Resolved numeric range of the filter */ range: { startRow: number; startCol: number; endRow: number; endCol: number }; /** Per-column filter criteria, keyed by header cell ID */ columnFilters: Record; /** Table ID if this filter is associated with a table. */ tableId?: string; /** Advanced Filter metadata, present for advanced filters. */ advancedFilter?: AdvancedFilterDetailInfo; } ``` ## FilterInfo ```typescript type FilterInfo = { /** Filter ID */ id: string; /** Filter kind. */ filterKind: FilterKind; /** The filtered range */ range?: string; /** Per-column filter criteria */ columns?: Record; /** Table ID if this filter is associated with a table. */ tableId?: string; /** Per-column filter criteria, keyed by column identifier. */ columnFilters?: Record; } ``` ## FilterKind Information about a filter applied to a sheet. ```typescript type FilterKind = 'autoFilter' | 'tableFilter' | 'advancedFilter' ``` ## FilterOperator Filter operators for record triggers. ```typescript type FilterOperator = | 'equals' | 'not_equals' | 'contains' | 'starts_with' | 'ends_with' | 'greater_than' | 'greater_than_or_equals' | 'less_than' | 'less_than_or_equals' | 'in' | 'not_in' | 'is_null' | 'is_not_null' ``` ## FilterSortState Sort state for a filter. ```typescript type FilterSortState = { /** Column index or header cell ID to sort by */ column: string | number; /** Sort direction */ direction: 'asc' | 'desc'; /** Sort criteria (optional, for advanced sorting) */ criteria?: any; } ``` ## FilterState API filter state — derived from Rust FilterState with A1-notation range. ```typescript type FilterState = { /** The range the auto-filter is applied to (A1 notation) */ range: string; /** Per-column filter criteria, keyed by column identifier (string) */ columnFilters: Record; } ``` ## FindInRangeOptions Options for findInRange — range is provided as a separate method parameter. ```typescript type FindInRangeOptions = Omit ``` ## FloatingObject Union of all floating object types. Use type narrowing on the 'type' discriminator to access specific properties. ```typescript type FloatingObject = | PictureObject | TextBoxObject | ShapeObject | ConnectorObject | ChartObject | DrawingObject | EquationObject | SmartArtObject | OleObjectObject ``` ## FloatingObjectHandle ```typescript type FloatingObjectHandle = { /** Stable object ID. */ id: string; /** Discriminator for type narrowing. */ type: FloatingObjectKind; /** Move by delta. dx/dy are pixel offsets (relative). Rust resolves to new cell anchor. */ move(dx: number, dy: number): Promise;; /** Set absolute dimensions in pixels. */ resize(width: number, height: number): Promise;; /** Set absolute rotation angle in degrees. */ rotate(angle: number): Promise;; /** Flip horizontally or vertically. */ flip(axis: 'horizontal' | 'vertical'): Promise;; bringToFront(): Promise;; sendToBack(): Promise;; bringForward(): Promise;; sendBackward(): Promise;; delete(): Promise;; duplicate(offsetX?: number, offsetY?: number): Promise;; /** Sync pixel bounds from scene graph. Null if not rendered yet. */ getBounds(): ObjectBounds | null;; /** Full object data (async — reads from store). */ getData(): Promise;; } ``` ## FloatingObjectInfo Summary information about a floating object (returned by listFloatingObjects). ```typescript type FloatingObjectInfo = { /** Unique object ID. */ id: string; /** Object type discriminator. */ type: FloatingObjectType; /** Optional display name. */ name?: string; /** X position in pixels. */ x: number; /** Y position in pixels. */ y: number; /** Width in pixels. */ width: number; /** Height in pixels. */ height: number; /** Rotation angle in degrees. */ rotation?: number; /** Flipped horizontally. */ flipH?: boolean; /** Flipped vertically. */ flipV?: boolean; /** Z-order index. */ zIndex?: number; /** Whether the object is visible. */ visible?: boolean; /** ID of the parent group (if this object is grouped). */ groupId?: string; /** Anchor mode (twoCell/oneCell/absolute). */ anchorType?: ObjectAnchorType; /** Alt text for accessibility. */ altText?: string; } ``` ## FloatingObjectKind Object type discriminator. Used for type narrowing in union types. Extends CanvasObjectType (which is `string`) with a specific union for spreadsheet object types. This ensures backward compatibility: any code expecting FloatingObjectKind still gets the specific union, while CanvasObjectType-based code accepts it as a string. Storage-layer discriminant for floating objects. Mirrors Rust FloatingObjectKind. See also FloatingObjectType in api/types.ts (API-layer superset that adds 'wordart'). Note: 'slicer' is defined here for the FloatingObjectKind union, but the full SlicerConfig type is in contracts/src/slicers.ts because slicers have significant additional properties. ```typescript type FloatingObjectKind = | 'shape' | 'connector' | 'picture' | 'textbox' | 'chart' | 'camera' | 'equation' | 'smartart' | 'drawing' | 'oleObject' | 'formControl' | 'slicer' ``` ## FloatingObjectMutationReceipt Receipt for a floating object creation or update mutation. ```typescript type FloatingObjectMutationReceipt = { domain: 'floatingObject'; action: 'create' | 'update'; id: string; object: FloatingObject; bounds: ObjectBounds; } ``` ## FloatingObjectRemoveReceipt Receipt for a floating object removal mutation. ```typescript type FloatingObjectRemoveReceipt = { domain: 'floatingObject'; action: 'remove'; id: string; } ``` ## FloatingObjectType Type discriminator for floating objects (API layer). Superset of FloatingObjectKind (12 storage-layer variants) + 'wordart' (API-only ergonomic alias). text-effect objects are stored as Textbox with word_art config; this type lets consumers reference them directly. ```typescript type FloatingObjectType = | 'shape' | 'connector' | 'picture' | 'textbox' | 'chart' | 'camera' | 'equation' | 'smartart' | 'drawing' | 'oleObject' | 'formControl' | 'slicer' | 'wordart' ``` ## FormControl Union of all implemented form control types. Currently: Checkbox, Button, ComboBox Future: RadioButton, Slider, Spinner ```typescript type FormControl = CheckboxControl | ButtonControl | ComboBoxControl ``` ## FormControlAnchorUpdate ```typescript type FormControlAnchorUpdate = { row: number; col: number; xOffset?: number; yOffset?: number; } ``` ## FormControlUpdate ```typescript type FormControlUpdate = Partial> ``` ## FormatChangeResult Result of a format set/setRange operation. ```typescript type FormatChangeResult = { /** Number of cells whose formatting was changed */ cellCount: number; } ``` ## FormatEntry Entry for batch format-values call. ```typescript type FormatEntry = { /** Cell value descriptor */ value: { type: string; value?: unknown }; /** Number format code (e.g., "#,##0.00") */ formatCode: string; } ``` ## FormulaA1 A formula string WITH the `=` prefix: `"=SUM(A1:B10)"`, `"=A1+A2"`. This is the display/input format used at the Rust-TS boundary and in the UI. ```typescript type FormulaA1 = string & { readonly [formulaA1Brand]: true } ``` ## FormulaSyntaxValidationError Result returned when formula syntax validation rejects an input. `errorPosition` is a zero-based character offset into the authored formula text, when the parser can locate one. ```typescript type FormulaSyntaxValidationError = { errorMessage: string; errorPosition?: number; } ``` ## FractionNode Fraction - Numerator over denominator IMPORTANT: Uses `fractionType` field (NOT `type_`) Maps to OMML ```typescript type FractionNode = { type: 'f'; /** Fraction type: bar (stacked), skw (skewed), lin (linear), noBar (no bar) */ fractionType: 'bar' | 'skw' | 'lin' | 'noBar'; /** Numerator */ num: MathNode[]; /** Denominator */ den: MathNode[]; } ``` ## FunctionArgument ```typescript type FunctionArgument = { name: string; description: string; type: FunctionArgumentType; optional: boolean; repeating?: boolean; } ``` ## FunctionArgumentType Function Registry -- Lightweight metadata registry for Excel functions. Types remain here in contracts. Migrated from @mog/calculator. ```typescript type FunctionArgumentType = | 'number' | 'text' | 'logical' | 'reference' | 'array' | 'any' | 'date' ``` ## FunctionInfo Information about a spreadsheet function (e.g., SUM, VLOOKUP). ```typescript type FunctionInfo = { /** Function name (uppercase, e.g., "SUM") */ name: string; /** Description of what the function does */ description: string; /** Function category (e.g., "Math & Trig", "Lookup & Reference") */ category: string; /** Syntax example (e.g., "SUM(number1, [number2], ...)") */ syntax: string; /** Usage examples */ examples?: string[]; /** Function argument metadata for IntelliSense/argument hints */ arguments?: FunctionArgument[]; } ``` ## FunctionNode Function - Named function like sin, cos, lim ```typescript type FunctionNode = { type: 'func'; /** Function name */ fName: MathNode[]; /** Argument */ e: MathNode[]; } ``` ## GlowEffect Glow effect configuration. ```typescript type GlowEffect = { /** Glow color (CSS color string) */ color: string; /** Glow radius in pixels */ radius: number; /** Opacity (0 = transparent, 1 = opaque) */ opacity: number; } ``` ## GoalSeekResult Result of a goal seek operation. ```typescript type GoalSeekResult = { /** Whether a solution was found */ found: boolean; /** The value found for the changing cell (if found) */ value?: number; /** Number of iterations performed */ iterations?: number; } ``` ## GradientFill Gradient fill configuration. Excel supports two gradient types: - linear: Color transitions along a line at a specified angle - path: Color transitions radially from a center point Gradients require at least 2 stops (start and end colors). ```typescript type GradientFill = { /** Type of gradient. - 'linear': Straight line gradient at specified degree - 'path': Radial/rectangular gradient from center point */ type: 'linear' | 'path'; /** Angle of linear gradient in degrees (0-359). 0 = left-to-right, 90 = bottom-to-top, etc. Only used when type is 'linear'. */ degree?: number; /** Center point for path gradients (0.0 to 1.0 for each axis). { left: 0.5, top: 0.5 } = center of cell. Only used when type is 'path'. */ center?: { left: number; top: number; }; /** Gradient color stops. Must have at least 2 stops. Stops should be ordered by position. */ stops: GradientStop[]; } ``` ## GradientStop GradientStop — Core contracts layer. Maps to CT_GradientStop (dml-main.xsd:1539) with position + color for cell formatting. ```typescript type GradientStop = { /** Position along the gradient (0.0 to 1.0). 0.0 = start of gradient, 1.0 = end of gradient. */ position: number; /** Color at this position. Can be absolute hex or theme reference. */ color: string; } ``` ## GroupCharNode Group Character - Grouping symbol (underbrace, overbrace) ```typescript type GroupCharNode = { type: 'groupChr'; /** Character (default is underbrace) */ chr?: string; /** Position: 'top' or 'bot' */ pos?: 'top' | 'bot'; /** Vertical justification */ vertJc?: 'top' | 'bot'; /** Content */ e: MathNode[]; } ``` ## GroupState State of all row/column groups on a sheet. ```typescript type GroupState = { /** All row groups */ rowGroups: any[]; /** All column groups */ columnGroups: any[]; /** Maximum outline level for rows */ maxRowLevel: number; /** Maximum outline level for columns */ maxColLevel: number; } ``` ## HeaderFooter Header/footer configuration (OOXML CT_HeaderFooter). ```typescript type HeaderFooter = { oddHeader: string | null; oddFooter: string | null; evenHeader: string | null; evenFooter: string | null; firstHeader: string | null; firstFooter: string | null; differentOddEven: boolean; differentFirst: boolean; scaleWithDoc: boolean; alignWithMargins: boolean; } ``` ## HeaderFooterImageInfo Header/footer image metadata. Stores image references (path or data-URL), not binary blobs. ```typescript type HeaderFooterImageInfo = { position: HfImagePosition; /** Image source — resolved path for imported, or data-URL for API-created */ src: string; /** Descriptive title */ title: string; /** Width in points */ widthPt: number; /** Height in points */ heightPt: number; } ``` ## HeatmapConfig Heatmap configuration ```typescript type HeatmapConfig = { colorScale?: string[]; showLabels?: boolean; minColor?: string; maxColor?: string; } ``` ## HfImagePosition Position of a header/footer image in the page layout. ```typescript type HfImagePosition = | 'leftHeader' | 'centerHeader' | 'rightHeader' | 'leftFooter' | 'centerFooter' | 'rightFooter' ``` ## HistogramConfig Histogram configuration ```typescript type HistogramConfig = { binCount?: number; binWidth?: number; cumulative?: boolean; } ``` ## IDisposable Disposable — Handle-based lifecycle management. Three primitives for consumer-scoped stateful APIs: 1. `IDisposable` — interface for any resource with explicit lifecycle. 2. `DisposableBase` — abstract class with idempotent dispose + Symbol.dispose. 3. `DisposableStore` — tracks child disposables; disposing the store disposes all children. Supports TC39 Explicit Resource Management (TS 5.2+): using region = wb.viewport.createRegion(sheetId, bounds); // auto-disposed at block exit @see plans/archive/kernel/round-5/02-HANDLE-BASED-API-PATTERN.md ```typescript type IDisposable = { dispose(): void;; [Symbol.dispose](): void;; } ``` ## IObjectBoundsReader ```typescript type IObjectBoundsReader = { /** Pixel bounds in document space. Null if object not in scene graph. */ getBounds(objectId: string): ObjectBounds | null;; /** Union bounds of all objects in a group. */ getGroupBounds(groupId: string): ObjectBounds | null;; /** Bounds for multiple objects. Skips objects not in scene graph. */ getBoundsMany(objectIds: readonly string[]): Map;; } ``` ## IdentifiedCellData Cell data enriched with stable CellId identity. Used by operations that need to reference cells by identity (not position), such as find-replace, clipboard, and cell relocation. The CellId is a CRDT-safe identifier that survives row/column insert/delete operations. Unlike `CellData` (position-implied), `IdentifiedCellData` includes explicit position and identity for flat iteration over non-empty cells in a range. ```typescript type IdentifiedCellData = { /** Stable cell identity (CRDT-safe, survives structural changes). */ cellId: string; /** Row index (0-based). */ row: number; /** Column index (0-based). */ col: number; /** The computed cell value (null for empty cells). */ value: CellValue | null; /** Formula text (e.g., "=A1+B1") when the cell contains a formula. */ formulaText?: string; /** Pre-formatted display string (e.g., "$1,234.56" for a currency-formatted number). */ displayString: string; } ``` ## IdentityRangeRef Reference to a range by corner cell identities (for formula storage). Ranges are defined by their corner cells. When rows/columns are inserted between the corners, the range automatically expands because the corner cells' positions change. ```typescript type IdentityRangeRef = { type: 'range'; /** Start cell (top-left corner) identity */ startId: CellId; /** End cell (bottom-right corner) identity */ endId: CellId; /** Absolute flags for start cell display */ startRowAbsolute: boolean; startColAbsolute: boolean; /** Absolute flags for end cell display */ endRowAbsolute: boolean; endColAbsolute: boolean; } ``` ## IfClause OOXML if-clause within a choose element. Evaluates a condition based on the current iteration context: `func(arg)` `op` `val` Where: - `func` determines what value to compute (count, position, variable, etc.) - `arg` provides additional context for the function (used with 'var' function) - `op` is the comparison operator - `val` is the value to compare against The if-clause also supports axis/ptType navigation for context-sensitive evaluation (similar to forEach). @see ECMA-376 Section 21.4.2.14 if (If) ```typescript type IfClause = { /** Optional name for this if-clause. */ name: string; /** Function to evaluate against the current context. Determines what property of the context is being tested. @see ST_FunctionType */ func: ST_FunctionType; /** Argument for the function. Primarily used with `func='var'` to specify which variable to look up. @see ST_FunctionArgument */ arg: ST_FunctionArgument; /** Comparison operator for the condition. @see ST_FunctionOperator */ op: ST_FunctionOperator; /** Value to compare the function result against. For numeric functions (cnt, pos, depth, etc.), this is a number as string. For variable functions (var), this is the expected variable value. */ val: string; /** Axis type(s) for navigation context. Used when the function needs to navigate the data model (e.g., counting children along a specific axis). @see ST_AxisType */ axis: string; /** Point type filter(s) for navigation. @see ST_ElementType */ ptType: string; /** Maximum count of points for axis navigation. 0 means no limit. Defaults to 0. */ cnt: number; /** Starting index (1-based) for axis navigation subsequence. Defaults to 1. */ st: number; /** Step value for axis navigation. Defaults to 1. */ step: number; /** Whether to hide the last sibling transition during navigation. Defaults to true. */ hideLastTrans: boolean; /** Child layout elements included when this condition is true. */ children: readonly LayoutNodeChild[]; } ``` ## ImageColorType Image color transform type. ```typescript type ImageColorType = 'automatic' | 'grayScale' | 'blackAndWhite' | 'watermark' ``` ## ImageExportFormat Image export format options ```typescript type ImageExportFormat = 'png' | 'jpeg' | 'svg' ``` ## ImageExportOptions Image export options ```typescript type ImageExportOptions = { /** Image format (default: 'png') */ format?: ImageExportFormat; /** Pixel ratio for higher resolution (default: 2) */ pixelRatio?: number; /** Background color (default: '#ffffff') */ backgroundColor?: string; /** Target width in pixels (default: 640) */ width?: number; /** Target height in pixels (default: 480) */ height?: number; /** JPEG quality 0-1 (default: 0.92, only used when format is 'jpeg') */ quality?: number; /** Fitting mode (default: 'fill') */ fittingMode?: ImageFittingMode; } ``` ## ImageFittingMode Image fitting mode for exports: - 'fill': scale the chart to fill the entire target canvas (may crop) - 'fit': scale the chart to fit within the target dimensions (preserves aspect ratio) - 'fitAndCenter': same as 'fit' but centers the chart within the target canvas ```typescript type ImageFittingMode = 'fill' | 'fit' | 'fitAndCenter' ``` ## ImportedExternalLinkIdentity ```typescript type ImportedExternalLinkIdentity = { excelOrdinal: number; workbookRelId: string; partName: string; externalBookRid?: string; target?: string; targetMode?: 'External' | 'Internal'; } ``` ## InkPoint A single point in a stroke with pressure and tilt support. Coordinates are in local drawing object space (pixels relative to drawing object bounds). Transform to sheet coordinates happens at render time. Pressure and tilt are normalized to [0, 1] ranges for consistent rendering regardless of input device. ```typescript type InkPoint = { /** X coordinate in drawing object local space (pixels) */ x: number; /** Y coordinate in drawing object local space (pixels) */ y: number; /** Pen pressure normalized to [0, 1]. - 0 = minimum pressure (or mouse with no pressure support) - 1 = maximum pressure - undefined = no pressure data (mouse, touch without pressure) Used for variable stroke width rendering. */ pressure?: number; /** Tilt angle in radians [0, PI/2]. - 0 = perpendicular to surface - PI/2 = parallel to surface - undefined = no tilt data Used for brush shape and texture effects. */ tilt?: number; /** Timestamp when this point was captured (ms since stroke start). Used for velocity calculations and replay animations. - undefined = no timing data */ timestamp?: number; } ``` ## InkStroke A complete ink stroke with all rendering properties. Strokes are immutable once created - modifications create new strokes with the same ID (for CRDT merge semantics). ```typescript type InkStroke = { /** Unique identifier for this stroke */ id: StrokeId; /** Ordered array of points composing the stroke */ points: InkPoint[]; /** Tool used to create this stroke */ tool: InkTool; /** Stroke color in CSS color format (hex, rgb, hsl) */ color: string; /** Base stroke width in pixels. Actual rendered width may vary with pressure. */ width: number; /** Stroke opacity [0, 1]. - 0 = fully transparent - 1 = fully opaque Different tools have different default opacities (e.g., highlighter defaults to ~0.4). */ opacity: number; /** User ID who created this stroke. Used for: - Collaboration: Show who drew what - Permissions: Only creator can modify their strokes - Undo: Per-user undo stacks */ createdBy: string; /** Timestamp when stroke was created (Unix ms). Used for ordering and undo/redo. */ createdAt: number; /** Whether this stroke is currently selected. This is a transient UI state, not persisted. */ selected?: boolean; } ``` ## InkTool Available ink tools for drawing. Each tool has different rendering characteristics: - pen: Solid line, pressure-sensitive width - pencil: Textured line, slight transparency - highlighter: Wide, semi-transparent, blends with background - marker: Bold, opaque, consistent width - brush: Artistic brush effects, pressure-sensitive - eraser: Removes strokes (not a drawing tool, but handled similarly) ```typescript type InkTool = 'pen' | 'pencil' | 'highlighter' | 'marker' | 'brush' | 'eraser' ``` ## InkToolSettings Default settings for a specific ink tool. Each tool can have different defaults for width, opacity, etc. These are used when creating new strokes. ```typescript type InkToolSettings = { /** Default stroke width in pixels */ width: number; /** Default opacity [0, 1] */ opacity: number; /** Default color (CSS color string) */ color: string; /** Whether this tool supports pressure sensitivity. Some tools (e.g., highlighter) ignore pressure. */ supportsPressure: boolean; } ``` ## InkToolState Current tool state for a drawing session. Tracks the active tool and its settings. ```typescript type InkToolState = { /** Currently selected tool */ activeTool: InkTool; /** Per-tool settings (user preferences) */ toolSettings: Record; } ``` ## InnerShadowEffect Inner shadow effect (shadow cast inside the text). Creates a shadow effect along the inside edges of the text, giving the appearance that the text is embossed or inset. Unlike outer shadows, inner shadows are rendered within the text bounds. @example // Subtle inner shadow for depth const innerShadow: InnerShadowEffect = { blurRadius: 25400, // 2pt blur distance: 12700, // 1pt offset direction: 225, // Light from top-left color: '#000000', opacity: 0.3 }; @see ECMA-376 Part 1, Section 20.1.8.40 (innerShdw) ```typescript type InnerShadowEffect = { /** Blur radius in EMUs. Controls how soft/diffuse the inner shadow appears. */ blurRadius: number; /** Shadow distance from the text edge in EMUs. How far the shadow extends inward from the edge. */ distance: number; /** Shadow direction in degrees. Angle measured clockwise from the positive x-axis. Determines which edge of the text the shadow appears on. */ direction: number; /** Shadow color (CSS color string). */ color: string; /** Shadow opacity (0-1). 0 = fully transparent, 1 = fully opaque. */ opacity: number; } ``` ## InsertCellsReceipt Receipt for an insertCellsWithShift mutation. ```typescript type InsertCellsReceipt = { kind: 'insertCells'; sheetId: string; range: { startRow: number; startCol: number; endRow: number; endCol: number }; direction: 'right' | 'down'; } ``` ## InsertColumnsReceipt Receipt for an insertColumns mutation. ```typescript type InsertColumnsReceipt = { kind: 'insertColumns'; sheetId: string; insertedAt: number; count: number; } ``` ## InsertRowsReceipt Receipt for an insertRows mutation. ```typescript type InsertRowsReceipt = { kind: 'insertRows'; sheetId: string; insertedAt: number; count: number; } ``` ## InsertWorksheetOptions Options for insertWorksheetsFromBase64 — controls which sheets to import and where to place them in the workbook. ```typescript type InsertWorksheetOptions = { /** Which sheets to import by name. Default: all sheets. */ sheetNamesToInsert?: string[]; /** Where to insert relative to existing sheets. Default: 'end'. */ positionType?: 'before' | 'after' | 'beginning' | 'end'; /** Sheet name to position relative to (required for 'before'/'after'). */ relativeTo?: string; } ``` ## Issue ```typescript type Issue = { id: string; title: string; description?: string; status: 'open' | 'in_progress' | 'review' | 'done' | 'closed'; priority: 'low' | 'medium' | 'high' | 'critical'; type: 'bug' | 'feature' | 'task' | 'improvement'; assignee?: { id: string; name: string; email: string }; labels: string[]; createdAt: string; updatedAt: string; closedAt?: string; } ``` ## LayoutForm ```typescript type LayoutForm = 'compact' | 'outline' | 'tabular' ``` ## LayoutNodeChild Discriminated union type for children of a layout node. A layout node's children can be: - A nested `LayoutNode` (static child) - A `ForEach` element (data-driven iteration) - A `Choose` element (conditional branching) Discriminated via the `kind` field: - `kind: 'layoutNode'` → LayoutNode (defined in ooxml-layout-types.ts) - `kind: 'forEach'` → ForEach - `kind: 'choose'` → Choose Note: The actual LayoutNode type with `kind: 'layoutNode'` is defined in the layout definition types (managed by Agent 1). This union is designed to be extended via intersection when all types are combined. ```typescript type LayoutNodeChild = ForEach | Choose | LayoutNodeChildRef ``` ## LegendConfig Legend configuration (matches LegendData wire type) ```typescript type LegendConfig = { show: boolean; position: string; visible: boolean; overlay?: boolean; font?: ChartFont; format?: ChartFormat; entries?: LegendEntryConfig[]; /** Custom legend X position (0-1, fraction of chart area) when position is 'custom' */ customX?: number; /** Custom legend Y position (0-1, fraction of chart area) when position is 'custom' */ customY?: number; shadow?: ChartShadow; /** Show drop shadow on legend box. */ showShadow?: boolean; /** Legend height in points (read-only, populated from render engine). */ height?: number; /** Legend width in points (read-only, populated from render engine). */ width?: number; /** Legend left position in points (read-only, populated from render engine). */ left?: number; /** Legend top position in points (read-only, populated from render engine). */ top?: number; } ``` ## LegendEntryConfig Legend entry override (show/hide individual entries). ```typescript type LegendEntryConfig = { idx: number; delete?: boolean; format?: ChartFormat; /** Whether this legend entry is visible */ visible?: boolean; } ``` ## LimLowNode Lower Limit - Base with limit below ```typescript type LimLowNode = { type: 'limLow'; /** Base expression */ e: MathNode[]; /** Limit expression */ lim: MathNode[]; } ``` ## LimUppNode Upper Limit - Base with limit above ```typescript type LimUppNode = { type: 'limUpp'; /** Base expression */ e: MathNode[]; /** Limit expression */ lim: MathNode[]; } ``` ## LineCap Line cap style. Maps to ST_LineCap (ECMA-376, dml-main.xsd). Uses lowercase variants; bridge uses PascalCase. ```typescript type LineCap = | 'flat' // Flat end (ends exactly at the endpoint) | 'round' // Rounded end (semicircle at the endpoint) | 'square' ``` ## LineDash Detailed line dash pattern. Matches OOXML line dash styles and Rust `LineDash` enum. Uses the same 11 variants as OOXML ST_PresetLineDashVal. ```typescript type LineDash = | 'solid' | 'dot' | 'dash' | 'dashDot' | 'lgDash' | 'lgDashDot' | 'lgDashDotDot' | 'sysDash' | 'sysDot' | 'sysDashDot' | 'sysDashDotDot' ``` ## LineEndSize Arrowhead/line-end size for connector endpoints. Maps to ST_LineEndLength/ST_LineEndWidth (ECMA-376, dml-main.xsd). Canonical source; re-exported by drawing-canvas scene/types. ```typescript type LineEndSize = 'sm' | 'med' | 'lg' ``` ## LineEndType Arrowhead/line-end type for connector endpoints. Maps to ST_LineEndType (ECMA-376, dml-main.xsd). Canonical source; re-exported by drawing-canvas scene/types. ```typescript type LineEndType = 'none' | 'triangle' | 'stealth' | 'diamond' | 'oval' | 'arrow' ``` ## LineJoin Line join style. Maps to EG_LineJoinProperties (ECMA-376, dml-main.xsd). Uses lowercase variants; bridge uses tagged union. ```typescript type LineJoin = | 'bevel' // Beveled corner (flat cut at the join) | 'miter' // Mitered corner (sharp pointed join) | 'round' ``` ## LineSubType ```typescript type LineSubType = | 'straight' | 'smooth' | 'stepped' | 'stacked' | 'percentStacked' | 'markers' | 'markersStacked' | 'markersPercentStacked' ``` ## LinkId ```typescript type LinkId = string ``` ## LinkStatus ```typescript type LinkStatus = | 'unresolved' | 'loading' | 'ready' | 'stale' | 'denied' | 'broken' | 'ambiguous' ``` ## LinkStatusReason ```typescript type LinkStatusReason = | 'wrongWorkbookId' | 'missingTarget' | 'unsupportedLinkKind' | 'permissionDenied' | 'sourceUnavailable' ``` ## LinkStatusView ```typescript type LinkStatusView = { linkId: LinkId; status: LinkStatus; statusReason?: LinkStatusReason; lastResolvedAt?: string; cachedValuesVersion?: string; } ``` ## MarkerStyle Marker style for scatter/line chart markers. ```typescript type MarkerStyle = | 'circle' | 'dash' | 'diamond' | 'dot' | 'none' | 'picture' | 'plus' | 'square' | 'star' | 'triangle' | 'x' | 'auto' ``` ## MathFont Math font for equation rendering Excel uses Cambria Math by default ```typescript type MathFont = | 'Cambria Math' // Default Excel math font | 'Latin Modern' // TeX-style | 'STIX Two Math' // Scientific publishing | 'XITS Math' // Based on STIX | string ``` ## MathNode Any math AST node ```typescript type MathNode = | OMath | OMathPara | AccentNode | BarNode | BoxNode | BorderBoxNode | DelimiterNode | EqArrayNode | FractionNode | FunctionNode | GroupCharNode | LimLowNode | LimUppNode | MatrixNode | NaryNode | PhantomNode | RadicalNode | PreScriptNode | SubscriptNode | SubSupNode | SuperscriptNode | MathRun ``` ## MathRun Text Run - Actual text/symbol content ```typescript type MathRun = { type: 'r'; /** Text content */ text: string; /** Run properties */ rPr?: MathRunProperties; } ``` ## MatrixNode Matrix - Mathematical matrix ```typescript type MatrixNode = { type: 'm'; /** Base justification */ baseJc?: 'top' | 'center' | 'bottom'; /** Hide placeholder */ plcHide?: boolean; /** Row spacing rule */ rSpRule?: 0 | 1 | 2 | 3 | 4; /** Column gap rule */ cGpRule?: 0 | 1 | 2 | 3 | 4; /** Row spacing */ rSp?: number; /** Column spacing */ cSp?: number; /** Column gap */ cGp?: number; /** Column properties */ mcs?: Array<{ count?: number; mcJc?: 'left' | 'center' | 'right' }>; /** Matrix rows - each row is an array of cells, each cell is an array of nodes */ mr: MathNode[][][]; } ``` ## MergeReceipt Receipt for a merge mutation. ```typescript type MergeReceipt = { kind: 'merge'; range: string; } ``` ## MergedRegion Information about a merged cell region. ```typescript type MergedRegion = { /** The merged range in A1 notation (e.g., "A1:B2") */ range: string; /** Start row (0-based) */ startRow: number; /** Start column (0-based) */ startCol: number; /** End row (0-based, inclusive) */ endRow: number; /** End column (0-based, inclusive) */ endCol: number; /** Row span (endRow - startRow + 1) */ rowSpan: number; /** Column span (endCol - startCol + 1) */ colSpan: number; } ``` ## NameAddReceipt Receipt for a named range add mutation. ```typescript type NameAddReceipt = { kind: 'nameAdd'; name: string; reference: string; } ``` ## NameRemoveReceipt Receipt for a named range remove mutation. ```typescript type NameRemoveReceipt = { kind: 'nameRemove'; name: string; } ``` ## NamedItemType API type classification for a named item's value. @see https://learn.microsoft.com/en-us/javascript/api/excel/excel.nameditemtype ```typescript type NamedItemType = | 'String' | 'Integer' | 'Double' | 'Boolean' | 'Range' | 'Error' | 'Array' ``` ## NamedRangeInfo Information about a defined name / named range. ```typescript type NamedRangeInfo = { /** The defined name */ name: string; /** The reference formula (e.g., "Sheet1!$A$1:$B$10") */ reference: string; /** Scope: undefined or sheet name (undefined = workbook scope) */ scope?: string; /** Optional descriptive comment */ comment?: string; /** Whether the name is visible in Name Manager. Hidden names are typically system-generated. */ visible?: boolean; } ``` ## NamedRangeReference Parsed reference for a named range that refers to a simple sheet!range. ```typescript type NamedRangeReference = { /** The sheet name (e.g., "Sheet1") */ sheetName: string; /** The range portion (e.g., "$A$1:$B$10") */ range: string; } ``` ## NamedRangeUpdateOptions Options for updating a named range. ```typescript type NamedRangeUpdateOptions = { /** New name (for renaming) */ name?: string; /** New reference (A1-style) */ reference?: string; /** New comment */ comment?: string; /** Whether the name is visible in Name Manager */ visible?: boolean; } ``` ## NamedSlicerStyle A named slicer style stored in the workbook (custom or built-in). ```typescript type NamedSlicerStyle = { name: string; readOnly: boolean; style: SlicerCustomStyle; } ``` ## NamedTimelineStyle A named timeline style stored in the workbook (custom or built-in). ```typescript type NamedTimelineStyle = { name: string; readOnly: boolean; style: SlicerCustomStyle; } ``` ## NaryNode N-ary Operator - Summation, integral, product, etc. ```typescript type NaryNode = { type: 'nary'; /** Operator character (sum, integral, product, etc.) */ chr?: string; /** Limit location: 'undOvr' (above/below) or 'subSup' (sub/superscript) */ limLoc?: 'undOvr' | 'subSup'; /** Grow with content */ grow?: boolean; /** Hide subscript */ subHide?: boolean; /** Hide superscript */ supHide?: boolean; /** Subscript (lower limit) */ sub: MathNode[]; /** Superscript (upper limit) */ sup: MathNode[]; /** Content (integrand, summand) */ e: MathNode[]; } ``` ## NegativeNumberPattern Negative number pattern. Determines how negative numbers are displayed (outside of currency context). 0 = (n) - parentheses 1 = -n - leading minus (most common) 2 = - n - leading minus with space 3 = n- - trailing minus 4 = n - - trailing minus with space ```typescript type NegativeNumberPattern = 0 | 1 | 2 | 3 | 4 ``` ## NoFill No fill (transparent). Text will be rendered without any fill color. @see ECMA-376 Part 1, Section 20.1.8.45 (CT_NoFillProperties) ```typescript type NoFill = { type: 'none'; } ``` ## NodeId Unique identifier for a diagram node. This is a branded type for type safety - prevents accidental use of arbitrary strings as NodeIds. Uses UUID v4 format. ```typescript type NodeId = string & { readonly __brand: 'SmartArtNodeId' } ``` ## NodeMoveDirection Hierarchical movement direction for a diagram node. Used by bridges, api/worksheet/smartart, and editor actions. ```typescript type NodeMoveDirection = 'promote' | 'demote' | 'move-up' | 'move-down' ``` ## NodePosition Node insertion position relative to a target diagram node. Used by bridges, api/worksheet/smartart, and editor actions. ```typescript type NodePosition = 'before' | 'after' | 'above' | 'below' | 'child' ``` ## Note A cell note (simple, single string per cell). API-only type (no Rust equivalent). ```typescript type Note = { content: string; author: string; cellAddress: string; /** Visible state of the note shape. */ visible?: boolean; /** Note callout box height in points. */ height?: number; /** Note callout box width in points. */ width?: number; } ``` ## Notification A single notification ```typescript type Notification = { /** Unique ID for the notification */ id: NotificationId; /** Notification type/severity */ type: NotificationType; /** Short title (optional) */ title?: string; /** Main message content */ message: string; /** Timestamp when created */ timestamp: number; /** Auto-dismiss after this many ms (null = manual dismiss only) */ duration: number | null; /** Whether the notification can be dismissed */ dismissible: boolean; /** Optional action button */ action?: { label: string; onClick: () => void; }; } ``` ## NotificationId Branded type for notification IDs — prevents accidental use of arbitrary strings. ```typescript type NotificationId = string & { readonly __brand: 'NotificationId' } ``` ## NotificationOptions Options for creating a notification ```typescript type NotificationOptions = { /** Notification type/severity (default: 'info') */ type?: NotificationType; /** Short title */ title?: string; /** Auto-dismiss duration in ms (default: 5000, null for no auto-dismiss) */ duration?: number | null; /** Whether dismissible (default: true) */ dismissible?: boolean; /** Optional action button */ action?: { label: string; onClick: () => void; }; } ``` ## NotificationType Notification severity levels ```typescript type NotificationType = 'info' | 'success' | 'warning' | 'error' ``` ## NumberFormatCategory Number format category classification. Matches the FormatType enum from Rust compute-formats. ```typescript enum NumberFormatCategory { General = 'General', Number = 'Number', Currency = 'Currency', Accounting = 'Accounting', Date = 'Date', Time = 'Time', Percentage = 'Percentage', Fraction = 'Fraction', Scientific = 'Scientific', Text = 'Text', Special = 'Special', Custom = 'Custom', } ``` ## NumberFormatType ```typescript type NumberFormatType = | 'general' | 'number' | 'currency' | 'accounting' | 'date' | 'time' | 'percentage' | 'fraction' | 'scientific' | 'text' | 'special' | 'custom' ``` ## OMath Root math container - ```typescript type OMath = { type: 'oMath'; children: MathNode[]; } ``` ## OMathPara Math paragraph - ```typescript type OMathPara = { type: 'oMathPara'; justification?: 'left' | 'right' | 'center' | 'centerGroup'; equations: OMath[]; } ``` ## ObjectAnchorType How the object anchors to the sheet. Determines behavior when rows/columns are resized. ```typescript type ObjectAnchorType = | 'twoCell' // Anchored to two cells (moves and resizes with cells) | 'oneCell' // Anchored to one cell (moves but doesn't resize) | 'absolute' ``` ## ObjectBorder Border style for floating objects. ```typescript type ObjectBorder = { /** Border line style */ style: 'none' | 'solid' | 'dashed' | 'dotted'; /** Border color (CSS color string) */ color: string; /** Border width in pixels */ width: number; } ``` ## ObjectBounds Pure-primitive rendering bounds types Leaf types (zero intra-contracts deps) that describe geometric/visual records. Promoted to Tier 1 during Phase C: they are consumed by both Tier 2 machines/actors and Tier 2 rendering, so hosting them here breaks what would otherwise be a types-machines ↔ types-rendering cycle. @module @mog/types-viewport/rendering/bounds ```typescript type ObjectBounds = { x: number; y: number; width: number; height: number; rotation: number; } ``` ## ObjectFill Fill configuration for shapes and text boxes. Matches the Rust `ObjectFill` struct in `domain-types`. ```typescript type ObjectFill = { /** Fill type */ type: FillType; /** Solid fill color (CSS color string) */ color?: string; /** Gradient configuration */ gradient?: GradientFill; /** Fill transparency (0 = opaque, 1 = fully transparent). */ transparency?: number; /** Pattern fill configuration (for type='pattern') */ pattern?: PatternFill; /** Picture/texture fill configuration (for type='pictureAndTexture') */ blip?: BlipFill; } ``` ## ObjectPosition Object position configuration. Supports cell-anchored and absolute positioning modes. ```typescript type ObjectPosition = { /** Anchor type determines how object moves/resizes with cells */ anchorType: ObjectAnchorType; /** Start anchor (top-left corner) - required for all anchor types */ from: CellAnchor; /** End anchor (bottom-right corner) - only for twoCell anchor */ to?: CellAnchor; /** Absolute X position in pixels (only for absolute anchor) */ x?: number; /** Absolute Y position in pixels (only for absolute anchor) */ y?: number; /** Width in pixels (for oneCell and absolute anchors) */ width?: number; /** Height in pixels (for oneCell and absolute anchors) */ height?: number; /** Rotation angle in degrees (0-360) */ rotation?: number; /** Flip horizontally (mirror along vertical axis) */ flipH?: boolean; /** Flip vertically (mirror along horizontal axis) */ flipV?: boolean; } ``` ## OleObjectObject OLE (Object Linking and Embedding) floating object. Represents embedded or linked objects from other applications (e.g., Word documents, PDF files, Visio drawings). The object may have a preview image (PNG/JPEG) or display as an icon. EMF/WMF previews are not supported and will have a null previewImageSrc. Architecture Notes: - Preview image is extracted during OOXML parsing and stored as a blob URL - Linked objects reference external files (isLinked); embedded objects are self-contained - dvAspect determines whether the object renders as content or as an icon - progId identifies the source application (e.g., "Word.Document.12", "AcroExch.Document") ```typescript type OleObjectObject = { type: 'oleObject'; /** OLE ProgID identifying the source application (e.g., "Word.Document.12") */ progId: string; /** Display aspect: 'content' renders the object preview, 'icon' shows an application icon */ dvAspect: 'content' | 'icon'; /** Whether the object links to an external file */ isLinked: boolean; /** Whether the object data is embedded in the workbook */ isEmbedded: boolean; /** Blob URL for the preview image (PNG/JPEG), null for EMF/WMF or missing previews */ previewImageSrc: string | null; /** Descriptive text for accessibility */ altText: string; } ``` ## OperationWarning Non-fatal warning attached to an operation result. ```typescript type OperationWarning = { /** Machine-readable warning code */ code: string; /** Human-readable description */ message: string; /** Optional structured context for programmatic handling */ context?: Record; } ``` ## OriginalCellValue A saved original cell value from before scenario application. ```typescript type OriginalCellValue = { sheetId: SheetId; cellId: string; value: string | number | boolean | null; /** Original formula, if the cell had one. */ formula?: string; } ``` ## OuterShadowEffect Outer shadow effect (shadow cast outside the text). Creates a shadow behind the text that appears to be cast by a light source. The shadow can be positioned, blurred, scaled, and skewed for various effects including simple drop shadows and perspective shadows. @example // Simple drop shadow (bottom-right) const shadow: OuterShadowEffect = { blurRadius: 50800, // 4pt blur distance: 38100, // 3pt offset direction: 45, // 45 degrees (down-right) color: '#000000', opacity: 0.4 }; @see ECMA-376 Part 1, Section 20.1.8.52 (outerShdw) ```typescript type OuterShadowEffect = { /** Blur radius in EMUs (English Metric Units). Higher values create a softer, more diffuse shadow. 1 point = 12700 EMUs. @example 50800 // 4pt blur */ blurRadius: number; /** Shadow distance from text in EMUs. How far the shadow is offset from the text. @example 38100 // 3pt offset */ distance: number; /** Shadow direction in degrees. Angle measured clockwise from the positive x-axis. - 0 = right - 90 = down - 180 = left - 270 = up */ direction: number; /** Shadow color (CSS color string). Typically black or dark gray for standard shadows. @example '#000000' */ color: string; /** Shadow opacity (0-1). 0 = fully transparent, 1 = fully opaque. Typical values range from 0.3 to 0.6 for natural-looking shadows. */ opacity: number; /** Horizontal scale factor for perspective shadows. Values less than 1.0 compress the shadow horizontally. Values greater than 1.0 stretch the shadow horizontally. @default 1.0 (no scaling) */ scaleX?: number; /** Vertical scale factor for perspective shadows. Values less than 1.0 compress the shadow vertically. Values greater than 1.0 stretch the shadow vertically. @default 1.0 (no scaling) */ scaleY?: number; /** Skew angle X in degrees (for perspective shadows). Shears the shadow horizontally. @default 0 (no skew) */ skewX?: number; /** Skew angle Y in degrees (for perspective shadows). Shears the shadow vertically. @default 0 (no skew) */ skewY?: number; /** Shadow alignment relative to the text bounding box. Determines the anchor point for shadow positioning. @default 'b' (bottom) */ alignment?: ShadowAlignment; /** Whether shadow rotates with text when text is rotated. If true, the shadow direction is relative to the text. If false, the shadow direction is absolute (relative to the page). @default true */ rotateWithShape?: boolean; } ``` ## OutlineSettings Outline display settings for grouping. ```typescript type OutlineSettings = { /** Whether outline symbols (+/-) are visible */ showOutlineSymbols: boolean; /** Whether outline level buttons (1,2,3...) are visible */ showOutlineLevelButtons: boolean; /** Whether summary rows appear below detail rows */ summaryRowsBelow: boolean; /** Whether summary columns appear to the right of detail */ summaryColumnsRight: boolean; } ``` ## PageMargins Page margins in inches. Full OOXML representation including header/footer margins. ```typescript type PageMargins = { top: number; bottom: number; left: number; right: number; header: number; footer: number; } ``` ## Path A geometric path composed of segments. ```typescript type Path = { segments: PathSegment[]; closed: boolean; subPaths?: SubPath[]; } ``` ## PathSegment A single segment in a path. ```typescript type PathSegment = MoveTo | LineTo | CurveTo | QuadraticTo | ClosePath ``` ## PatternFill Pattern fill definition. ```typescript type PatternFill = { preset: string; foregroundColor?: string; backgroundColor?: string; } ``` ## PatternType Spreadsheet pattern fill types. XLSX supports 18 pattern types for cell backgrounds. These patterns combine a foreground color (the pattern) with a background color. Pattern visualization (8x8 pixels): - none: No fill (transparent) - solid: Solid fill (fgColor only) - darkGray/mediumGray/lightGray/gray125/gray0625: Dot density patterns - darkHorizontal/lightHorizontal: Horizontal stripe patterns - darkVertical/lightVertical: Vertical stripe patterns - darkDown/lightDown: Diagonal stripes (top-left to bottom-right) - darkUp/lightUp: Diagonal stripes (bottom-left to top-right) - darkGrid/lightGrid: Grid patterns (horizontal + vertical) - darkTrellis/lightTrellis: Cross-hatch patterns (both diagonals) ```typescript type PatternType = | 'none' | 'solid' | 'darkGray' | 'mediumGray' | 'lightGray' | 'gray125' | 'gray0625' | 'darkHorizontal' | 'darkVertical' | 'darkDown' | 'darkUp' | 'darkGrid' | 'darkTrellis' | 'lightHorizontal' | 'lightVertical' | 'lightDown' | 'lightUp' | 'lightGrid' | 'lightTrellis' ``` ## PercentNegativePattern Percent negative pattern. 0 = -n % 1 = -n% 2 = -%n 3 = %-n 4 = %n- 5 = n-% 6 = n%- 7 = -% n 8 = n %- 9 = % n- 10 = % -n 11 = n- % ```typescript type PercentNegativePattern = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 ``` ## PercentPositivePattern Percent positive pattern. 0 = n % - number, space, percent 1 = n% - number, percent (most common) 2 = %n - percent, number 3 = % n - percent, space, number ```typescript type PercentPositivePattern = 0 | 1 | 2 | 3 ``` ## PersistedLinkTarget ```typescript type PersistedLinkTarget = | { readonly kind: 'document-ref'; readonly documentId: DocumentId } | { readonly kind: 'open-session'; readonly sessionId: WorkbookSessionId } | { readonly kind: 'path'; readonly path: string } | { readonly kind: 'url'; readonly url: string } | { readonly kind: 'excel-external-path'; readonly target: string } | { readonly kind: 'opaque-host-ref'; readonly provider: string; readonly ref: string } ``` ## PersistedWorkbookLinkRecord ```typescript type PersistedWorkbookLinkRecord = { linkId: LinkId; expectedWorkbookId: WorkbookId | null; target: PersistedLinkTarget; displayName: string; sourceKind: WorkbookLinkSourceKind; importedExcelIdentity?: ImportedExternalLinkIdentity; materializedCacheMetadata?: AuthorizedMaterializedCacheMetadata; } ``` ## PhantomNode Phantom - Invisible element for spacing ```typescript type PhantomNode = { type: 'phant'; /** Show content (false = invisible) */ show?: boolean; /** Zero width */ zeroWid?: boolean; /** Zero ascent */ zeroAsc?: boolean; /** Zero descent */ zeroDesc?: boolean; /** Transparent (show but don't contribute to size) */ transp?: boolean; /** Content */ e: MathNode[]; } ``` ## PictureAdjustments Image adjustment settings. Values mirror Excel's picture format options. ```typescript type PictureAdjustments = { /** Brightness adjustment (-100 to 100, 0 = normal) */ brightness?: number; /** Contrast adjustment (-100 to 100, 0 = normal) */ contrast?: number; /** Transparency (0 = opaque, 100 = fully transparent) */ transparency?: number; } ``` ## PictureConfig Configuration for creating a new picture. ```typescript type PictureConfig = { /** Image source: data URL, blob URL, or file path. */ src: string; /** X position in pixels. */ x?: number; /** Y position in pixels. */ y?: number; /** Width in pixels (defaults to original image width). */ width?: number; /** Height in pixels (defaults to original image height). */ height?: number; /** Accessibility alt text. */ altText?: string; /** Display name. */ name?: string; /** Image crop settings (percentage from each edge). */ crop?: PictureCrop; /** Image adjustments (brightness, contrast, transparency). */ adjustments?: PictureAdjustments; /** Border around the picture. */ border?: ObjectBorder; /** Full floating-object position update. Used by Format Picture dialogs. */ position?: Partial; /** Whether the picture is locked when sheet protection is active. */ locked?: boolean; /** Whether the picture prints with the worksheet. */ printable?: boolean; /** Anchor cell as `{row, col}`. When set, `x`/`y` become offsets from this cell instead of from cell `(0, 0)`. Used by paste-image to anchor at the active cell. */ anchorCell?: { row: number; col: number }; } ``` ## PictureCrop Image crop settings. Values are percentages (0-100) of original dimension to crop from each side. ```typescript type PictureCrop = { /** Percentage to crop from top (0-100) */ top: number; /** Percentage to crop from right (0-100) */ right: number; /** Percentage to crop from bottom (0-100) */ bottom: number; /** Percentage to crop from left (0-100) */ left: number; } ``` ## PictureHandle ```typescript type PictureHandle = { update(props: Partial): Promise;; duplicate(offsetX?: number, offsetY?: number): Promise;; getData(): Promise;; } ``` ## PictureObject Picture/image floating object. Supports images from various sources with cropping and adjustments. ```typescript type PictureObject = { type: 'picture'; /** Image source (data URL, blob URL, or external URL) */ src: string; /** Original image width in pixels (before scaling) */ originalWidth: number; /** Original image height in pixels (before scaling) */ originalHeight: number; /** Crop settings (percentage-based) */ crop?: PictureCrop; /** Image adjustments (brightness, contrast, transparency) */ adjustments?: PictureAdjustments; /** Border around the image */ border?: ObjectBorder; /** Image color transform type */ colorType?: ImageColorType; } ``` ## PieSliceConfig Pie/doughnut slice configuration (matches PieSliceData wire type) ```typescript type PieSliceConfig = { explosion?: number; explodedIndices?: number[]; explodeOffset?: number; /** Explode all slices simultaneously */ explodeAll?: boolean; } ``` ## PivotCalculatedFieldSpec ```typescript type PivotCalculatedFieldSpec = { calculatedFieldId?: CalculatedFieldId; name: string; formula: string; } ``` ## PivotChartOptions Pivot chart display options (field button visibility). ```typescript type PivotChartOptions = { /** Show axis field buttons on the chart. */ showAxisFieldButtons?: boolean; /** Show legend field buttons on the chart. */ showLegendFieldButtons?: boolean; /** Show report filter field buttons on the chart. */ showReportFilterFieldButtons?: boolean; /** Show value field buttons on the chart. */ showValueFieldButtons?: boolean; } ``` ## PivotColumnHeader ```typescript type PivotColumnHeader = { headers: PivotHeader[]; fieldId: string; } ``` ## PivotCommandReceipt ```typescript type PivotCommandReceipt = { receiptId: string; kernelReceiptId: string; action: string; pivotId: string; effects: PivotMutationEffect[]; updateReason: string; refreshPolicy: 'dirtyOnly' | 'refreshAndMaterialize'; materialized: boolean; configRevision: number; resultRevision: number; projectionRevision: number; materializedRevision?: number; renderFrame: number; status: 'complete' | 'failed' | 'cancelled' | 'timeout'; error?: PivotKernelMutationError | { code: 'UI_TIMEOUT' | 'UI_CANCELLED'; message: string }; } ``` ## PivotCreateConfig Input config for pivot creation — accepts either the simple ergonomic format (dataSource string + field name arrays) or the full wire format (sourceSheetName, sourceRange, fields[], placements[]). Simple format example: ```ts { name: "Sales", dataSource: "Sheet1!A1:D100", rowFields: ["Region"], columnFields: ["Year"], valueFields: [{ field: "Amount", aggregation: "sum" }] } ``` Full format example: ```ts { name: "Sales", sourceSheetName: "Sheet1", sourceRange: { startRow: 0, startCol: 0, endRow: 99, endCol: 3 }, outputSheetName: "Sheet1", outputLocation: { row: 0, col: 5 }, fields: [...], placements: [...], filters: [] } ``` ```typescript type PivotCreateConfig = | SimplePivotTableConfig | Omit ``` ## PivotDataHierarchyInfo Identifies which data hierarchy (value field) a pivot cell belongs to. ```typescript type PivotDataHierarchyInfo = { /** The field ID of the value field. */ fieldId: string; /** Stable placement ID of the value field. */ measurePlacementId?: PlacementId; /** The display name of the value field (e.g., "Sum of Sales"). */ displayName: string; /** The aggregate function applied. */ aggregateFunction: AggregateFunction; /** The 0-based index of this value field in the value placements. */ index: number; } ``` ## PivotExpansionKey ```typescript type PivotExpansionKey = { axis: 'row' | 'column'; axisPlacementId: PlacementId; memberPath: PivotMemberKey[]; } ``` ## PivotExpansionState Tracks which headers are expanded/collapsed. Uses Record for TS ergonomics; Rust side uses HashSet with custom serde that accepts both array and map formats. ```typescript type PivotExpansionState = { keys?: PivotExpansionKey[]; /** @deprecated Legacy expansion map keyed by rendered header strings. */ expandedRows: Record; /** @deprecated Legacy expansion map keyed by rendered header strings. */ expandedColumns: Record; } ``` ## PivotFieldArea ```typescript type PivotFieldArea = 'row' | 'column' | 'value' | 'filter' ``` ## PivotFieldItems Collection of pivot items for a single field. Mirrors the Rust PivotFieldItems type. ```typescript type PivotFieldItems = { fieldId: string; fieldName: string; area: PivotFieldArea; items: PivotItemInfo[]; } ``` ## PivotFilter ```typescript type PivotFilter = { fieldId: string; includeValues?: CellValue[]; excludeValues?: CellValue[]; condition?: PivotFilterConditionFlat; topBottom?: PivotTopBottomFilter; showItemsWithNoData?: boolean; } ``` ## PivotFilterConditionFlat ```typescript type PivotFilterConditionFlat = { operator: FilterOperator; value?: CellValue; value2?: CellValue; } ``` ## PivotGrandTotals ```typescript type PivotGrandTotals = { row?: CellValue[]; column?: CellValue[][]; grand?: CellValue[]; rowLabel?: string; } ``` ## PivotHeader ```typescript type PivotHeader = { key: PivotMemberKey; value: CellValue; fieldId: string; axisPlacementId?: PlacementId; depth: number; span: number; isExpandable: boolean; isExpanded: boolean; isSubtotal: boolean; isGrandTotal: boolean; parentKey?: PivotMemberKey; childKeys?: PivotMemberKey[]; } ``` ## PivotItemInfo A PivotItem represents a unique value within a pivot field. Mirrors the Rust PivotItemInfo type. ```typescript type PivotItemInfo = { key: PivotMemberKey; value: CellValue; fieldId: string; axisPlacementId?: PlacementId; area: PivotFieldArea; depth: number; isExpandable: boolean; isExpanded: boolean; isVisible: boolean; isSubtotal: boolean; isGrandTotal: boolean; childKeys?: PivotMemberKey[]; parentKey?: PivotMemberKey; } ``` ## PivotItemLocation Identifies which pivot items (row/column group values) intersect at a given cell. ```typescript type PivotItemLocation = { /** The field ID. */ fieldId: string; /** Stable placement ID of the axis field, when available. */ axisPlacementId?: PlacementId; /** The display value of the item. */ value: CellValue; /** The compound key identifying this item in the pivot result tree. */ key: PivotMemberKey; } ``` ## PivotKernelMutationError ```typescript type PivotKernelMutationError = { code: | 'PIVOT_NOT_FOUND' | 'PLACEMENT_NOT_FOUND' | 'DUPLICATE_PLACEMENT_ID' | 'AMBIGUOUS_SELECTOR' | 'INVALID_PLACEMENT_SOURCE' | 'CALCULATED_FIELD_NOT_FOUND' | 'DUPLICATE_CALCULATED_FIELD_ID' | 'DUPLICATE_CALCULATED_FIELD_NAME' | 'INVALID_CALCULATED_FIELD_FORMULA' | 'INVALID_CALCULATED_FIELD_REFERENCE' | 'CALCULATED_FIELD_DEPENDENCY_CYCLE' | 'INVALID_CALCULATED_FIELD_STATE' | 'INVALID_EXPANSION_KEY' | 'UNRESOLVABLE_EXPANSION_KEY' | 'STALE_EXPANSION_TARGET' | 'REFRESH_FAILED' | 'MATERIALIZATION_FAILED'; stage: PivotMutationStage; message: string; } ``` ## PivotKernelMutationReceipt ```typescript type PivotKernelMutationReceipt = { kernelReceiptId: string; pivotId: string; effects: PivotMutationEffect[]; mutationResult: unknown; updateReason: string; refreshPolicy: 'dirtyOnly' | 'refreshAndMaterialize'; materialized: boolean; configRevision: number; resultRevision?: number; materializedRevision?: number; status: PivotMutationStatus; error?: PivotKernelMutationError; } ``` ## PivotMeasureDescriptor ```typescript type PivotMeasureDescriptor = { placementId: PlacementId; source: | { type: 'field'; fieldId: string } | { type: 'calculatedField'; calculatedFieldId: CalculatedFieldId }; aggregateFunction: AggregateFunction; name: string; numberFormat?: string; } ``` ## PivotMemberKey ```typescript type PivotMemberKey = string & { readonly __brand: 'PivotMemberKey' } ``` ## PivotMemberRef ```typescript type PivotMemberRef = { key: PivotMemberKey; value: CellValue; displayText: string; fieldId?: string; groupingBucketId?: string; } ``` ## PivotMutationEffect ```typescript type PivotMutationEffect = { type: | 'placementAdded' | 'placementUpdated' | 'placementRemoved' | 'calculatedFieldAdded' | 'calculatedFieldUpdated' | 'calculatedFieldRemoved' | 'calculatedFieldInvalidated' | 'expansionChanged' | 'expansionKeyDropped'; placementId?: PlacementId; calculatedFieldId?: CalculatedFieldId; expansionKey?: PivotExpansionKey; } ``` ## PivotMutationStage ```typescript type PivotMutationStage = | 'validate' | 'configWrite' | 'refresh' | 'materialize' ``` ## PivotMutationStatus ```typescript type PivotMutationStatus = 'applied' | 'noOp' | 'failed' ``` ## PivotPlacementMutationReceipt ```typescript type PivotPlacementMutationReceipt = | (PivotKernelMutationReceipt & { status: 'applied'; placementId: PlacementId }) | (PivotKernelMutationReceipt & { status: 'noOp' | 'failed'; placementId?: never }) ``` ## PivotPlacementPatch ```typescript type PivotPlacementPatch = Partial> ``` ## PivotPlacementSpec ```typescript type PivotPlacementSpec = { placementId?: PlacementId; fieldId?: string; area: PivotFieldArea; position?: number; source?: { type: 'field'; fieldId: string } | { type: 'calculatedField'; calculatedFieldId: CalculatedFieldId }; aggregateFunction?: AggregateFunction; sortOrder?: SortOrder; displayName?: string; showValuesAs?: ShowValuesAsConfig; numberFormat?: string; } ``` ## PivotQueryRecord A single flat record from a pivot query result. ```typescript type PivotQueryRecord = { /** Dimension values keyed by field name (e.g., { Region: "North", Year: 2021 }) */ dimensions: Record; /** Aggregated values keyed by value field label (e.g., { "Sum of Amount": 110 }) */ values: Record; /** Measure-aware values with stable placement provenance. */ valueRecords?: PivotValueRecord[]; rowMemberPath?: PivotMemberRef[]; columnMemberPath?: PivotMemberRef[]; } ``` ## PivotQueryResult Result of queryPivot() — flat, agent-friendly records instead of hierarchy trees. ```typescript type PivotQueryResult = { /** Pivot table name */ pivotName: string; /** Row dimension field names */ rowFields: string[]; /** Column dimension field names */ columnFields: string[]; /** Value field labels */ valueFields: string[]; /** Flat records — one per data intersection, excluding subtotals and grand totals */ records: PivotQueryRecord[]; /** Total source row count */ sourceRowCount: number; } ``` ## PivotRefreshReceipt Receipt for a pivot table refresh mutation. ```typescript type PivotRefreshReceipt = { kind: 'pivotRefresh'; pivotId: string; } ``` ## PivotRenderedBounds ```typescript type PivotRenderedBounds = { totalRows: number; totalCols: number; firstDataRow: number; firstDataCol: number; /** Number of data columns reserved for the pivot body — `column_leaves * max(v, 1)`. Distinct from `totalCols`, which adds row-header columns and grand-total columns. Computed from the column-axis structure (sum of depth-0 column-header spans), not from per-row value vectors, so it stays correct when measures or rows are empty. */ numDataCols: number; } ``` ## PivotRow ```typescript type PivotRow = { key: PivotTupleKey; headers: PivotHeader[]; values: CellValue[]; valueRecords?: PivotValueRecord[]; depth: number; isSubtotal: boolean; isGrandTotal: boolean; /** Source row indices from the original data that contribute to this row's values. Indices are 0-based into the source data rows (excluding the header row). */ sourceRowIndices?: number[]; } ``` ## PivotTableConfig Configuration for creating or describing a pivot table. ```typescript type PivotTableConfig = { /** Pivot table name */ name: string; /** Source data range in A1 notation (e.g., "Sheet1!A1:E100") */ dataSource: string; /** Target sheet name (defaults to a new sheet) */ targetSheet?: string; /** Target cell address (defaults to A1) */ targetAddress?: string; /** Field names for the row area */ rowFields?: string[]; /** Field names for the column area */ columnFields?: string[]; /** Value field configurations */ valueFields?: PivotValueField[]; /** Field names for the filter area */ filterFields?: string[]; /** When true, allows multiple filter criteria on a single field. */ allowMultipleFiltersPerField?: boolean; /** Controls whether the pivot table auto-formats when refreshed. */ autoFormat?: boolean; /** Controls whether custom formatting is preserved on refresh. */ preserveFormatting?: boolean; } ``` ## PivotTableHandle Handle for interacting with an existing pivot table. Returned by `worksheet.getPivotTable()`. Provides methods to query and modify the pivot table's field configuration. ```typescript type PivotTableHandle = { /** Unique pivot table identifier (readonly) */ id: string; /** Get the pivot table name */ getName(): string;; /** Get the current configuration including all fields */ getConfig(): PivotTableConfig;; /** Add a field to the row, column, or filter area */ addField(field: string, area: 'row' | 'column' | 'filter', position?: number): void;; /** Add a value field with aggregation */ addValueField(field: string, aggregation: PivotValueField['aggregation'], label?: string): void;; /** Remove a field by name */ removeField(fieldName: string): void;; /** Change the aggregation function of a value field */ changeAggregation(valueFieldLabel: string, newAggregation: PivotValueField['aggregation']): void;; /** Rename a value field's display label */ renameValueField(currentLabel: string, newLabel: string): void;; /** Refresh the pivot table from its data source */ refresh(): Promise;; /** Get all items for all non-value fields */ getAllItems(): Promise;; /** Set the "Show Values As" calculation for a value field. Pass null to clear. */ setShowValuesAs(valueFieldLabel: string, showValuesAs: ShowValuesAsConfig | null): void;; /** Set item visibility by value string -> boolean map */ setItemVisibility(fieldId: string, visibleItems: Record): void;; /** Get the data source type (range, table, or external). */ getDataSourceType(): DataSourceType;; /** Change the source data range without refreshing/materializing. */ setDataSource(dataSource: string): Promise;; } ``` ## PivotTableInfo Summary information about an existing pivot table. ```typescript type PivotTableInfo = { /** Pivot table name */ name: string; /** Source data range (e.g., "Sheet1!A1:D100") */ dataSource: string; /** Range occupied by the pivot table content */ contentArea: string; /** Range occupied by filter dropdowns (if any) */ filterArea?: string; /** Output anchor location as A1 reference (e.g., "G1") */ location?: string; /** Row dimension field names */ rowFields?: string[]; /** Column dimension field names */ columnFields?: string[]; /** Value fields with aggregation info */ valueFields?: PivotValueField[]; /** Filter field names */ filterFields?: string[]; } ``` ## PivotTableLayout ```typescript type PivotTableLayout = { showRowGrandTotals?: boolean; showColumnGrandTotals?: boolean; layoutForm?: LayoutForm; subtotalLocation?: SubtotalLocation; repeatRowLabels?: boolean; insertBlankRowAfterItem?: boolean; showRowHeaders?: boolean; showColumnHeaders?: boolean; classicLayout?: boolean; grandTotalCaption?: string; rowHeaderCaption?: string; colHeaderCaption?: string; dataCaption?: string; gridDropZones?: boolean; errorCaption?: string; showError?: boolean; missingCaption?: string; showMissing?: boolean; } ``` ## PivotTableResult ```typescript type PivotTableResult = { columnHeaders: PivotColumnHeader[]; rows: PivotRow[]; records?: PivotQueryRecord[]; grandTotals: PivotGrandTotals; sourceRowCount: number; renderedBounds: PivotRenderedBounds; measureDescriptors?: PivotMeasureDescriptor[]; valueRecords?: PivotValueRecord[]; errors?: string[]; } ``` ## PivotTableStyle ```typescript type PivotTableStyle = { styleName?: string; showRowStripes?: boolean; showColumnStripes?: boolean; } ``` ## PivotTableStyleInfo WorkbookPivotTableStyles -- Pivot table style presets and default style management. Provides access to the workbook-level default pivot table style preset. Equivalent API shape: `workbook.pivotTableStyles`. ```typescript type PivotTableStyleInfo = { name: string; isDefault: boolean; } ``` ## PivotTopBottomFilter ```typescript type PivotTopBottomFilter = { type: TopBottomType; n: number; by: TopBottomBy; valueFieldId?: string; } ``` ## PivotTupleKey ```typescript type PivotTupleKey = string & { readonly __brand: 'PivotTupleKey' } ``` ## PivotValueField A value field in a pivot table. ```typescript type PivotValueField = { /** Stable value placement ID once the field is placed. */ placementId?: PlacementId; /** Source field name */ field: string; /** Aggregation function */ aggregation: 'sum' | 'count' | 'average' | 'max' | 'min'; /** Custom label for the value field */ label?: string; } ``` ## PivotValueRecord ```typescript type PivotValueRecord = { rowKey: PivotTupleKey; columnKey: PivotTupleKey; measureIndex: number; value: CellValue; sourceRowIndices?: number[]; } ``` ## PlacementId ```typescript type PlacementId = string & { readonly __brand: 'PlacementId' } ``` ## Platform Supported operating system platforms. Canonical type for OS identity — used by PlatformIdentity, keyboard shortcut resolution, and any code that branches on the host OS. ```typescript type Platform = 'macos' | 'windows' | 'linux' ``` ## PlotAreaConfig Plot area configuration ```typescript type PlotAreaConfig = { fill?: ChartFill; border?: ChartBorder; format?: ChartFormat; } ``` ## PointFormat Per-point formatting for individual data points (matches PointFormatData wire type) ```typescript type PointFormat = { idx: number; fill?: string; border?: ChartBorder; dataLabel?: DataLabelConfig; visualFormat?: ChartFormat; /** Readonly: computed value at this point (populated by get, ignored on set). */ value?: number | string; /** Per-point marker fill color. */ markerBackgroundColor?: ChartColor; /** Per-point marker border color. */ markerForegroundColor?: ChartColor; /** Per-point marker size (2-72 points). */ markerSize?: number; /** Per-point marker style. */ markerStyle?: MarkerStyle; } ``` ## PolicyId Branded policy identifier. ```typescript type PolicyId = string & { readonly __brand?: 'PolicyId' } ``` ## PreScriptNode Pre-scripts - Subscript and superscript before base ```typescript type PreScriptNode = { type: 'sPre'; /** Subscript */ sub: MathNode[]; /** Superscript */ sup: MathNode[]; /** Base */ e: MathNode[]; } ``` ## PresetShadowType Preset shadow types (20 predefined shadows). These map to DrawingML's preset shadow definitions (shdw1-shdw20). Each preset defines a complete shadow configuration including distance, direction, blur, color, and opacity. Use these for consistent, quick shadow application rather than configuring OuterShadowEffect manually. Preset categories: - shdw1-shdw4: Outer shadows (basic drop shadows) - shdw5-shdw8: Perspective shadows (cast at an angle) - shdw9-shdw12: Offset shadows (shifted significantly from text) - shdw13-shdw16: Inner shadows (shadow inside text edges) - shdw17-shdw20: Special effects (reflection-like, soft shadows) @see ECMA-376 Part 1, Section 20.1.10.56 (ST_PresetShadowVal) ```typescript type PresetShadowType = | 'shdw1' // Outer offset diagonal bottom right | 'shdw2' // Outer offset bottom | 'shdw3' // Outer offset diagonal bottom left | 'shdw4' // Outer offset right | 'shdw5' // Outer offset center | 'shdw6' // Outer offset left | 'shdw7' // Outer offset diagonal top right | 'shdw8' // Outer offset top | 'shdw9' // Outer offset diagonal top left | 'shdw10' // Perspective diagonal upper left | 'shdw11' // Perspective diagonal upper right | 'shdw12' // Perspective diagonal lower left | 'shdw13' // Perspective diagonal lower right | 'shdw14' // Perspective below | 'shdw15' // Perspective above | 'shdw16' // Perspective left | 'shdw17' // Perspective right | 'shdw18' // Perspective upper left | 'shdw19' // Perspective upper right | 'shdw20' ``` ## PrintSettings Full print settings for a sheet, matching the Rust domain-types canonical type. Replaces the old lossy SheetPrintSettings. All fields are nullable where the underlying OOXML attribute is optional, using `null` to mean "not set / use default". Distinct from PrintOptions (runtime-only configuration in print-export). ```typescript type PrintSettings = { /** OOXML paper size code (1=Letter, 9=A4, etc.), null = not set */ paperSize: number | null; /** Page orientation, null = not set (defaults to portrait) */ orientation: string | null; /** Scale percentage (10-400), null = not set */ scale: number | null; /** Fit to N pages wide, null = not set */ fitToWidth: number | null; /** Fit to N pages tall, null = not set */ fitToHeight: number | null; /** Print cell gridlines */ gridlines: boolean; /** Print row/column headings */ headings: boolean; /** Center content horizontally on page */ hCentered: boolean; /** Center content vertically on page */ vCentered: boolean; /** Page margins in inches (with header/footer margins) */ margins: PageMargins | null; /** Header/footer configuration */ headerFooter: HeaderFooter | null; /** Print in black and white */ blackAndWhite: boolean; /** Draft quality */ draft: boolean; /** First page number override, null = auto */ firstPageNumber: number | null; /** Page order: "downThenOver" or "overThenDown", null = default */ pageOrder: string | null; /** Use printer defaults */ usePrinterDefaults: boolean | null; /** Horizontal DPI, null = not set */ horizontalDpi: number | null; /** Vertical DPI, null = not set */ verticalDpi: number | null; /** Relationship ID for printer settings binary, null = not set */ rId: string | null; /** Whether the sheet had printOptions element in OOXML */ hasPrintOptions: boolean; /** Whether the sheet had pageSetup element in OOXML */ hasPageSetup: boolean; /** Whether to use firstPageNumber (vs auto) */ useFirstPageNumber: boolean; /** How to print cell comments: "none" | "atEnd" | "asDisplayed", null = not set (defaults to none) */ printComments: string | null; /** How to print cell errors: "displayed" | "blank" | "dash" | "NA", null = not set (defaults to displayed) */ printErrors: string | null; } ``` ## ProtectionConfig Full protection configuration for a sheet. ```typescript type ProtectionConfig = { /** Whether the sheet is protected */ isProtected: boolean; /** Whether a password is set for protection (does not expose the hash) */ hasPasswordSet?: boolean; /** Allow selecting locked cells */ allowSelectLockedCells?: boolean; /** Allow selecting unlocked cells */ allowSelectUnlockedCells?: boolean; /** Allow formatting cells */ allowFormatCells?: boolean; /** Allow formatting columns */ allowFormatColumns?: boolean; /** Allow formatting rows */ allowFormatRows?: boolean; /** Allow inserting columns */ allowInsertColumns?: boolean; /** Allow inserting rows */ allowInsertRows?: boolean; /** Allow inserting hyperlinks */ allowInsertHyperlinks?: boolean; /** Allow deleting columns */ allowDeleteColumns?: boolean; /** Allow deleting rows */ allowDeleteRows?: boolean; /** Allow sorting */ allowSort?: boolean; /** Allow using auto-filter */ allowAutoFilter?: boolean; /** Allow using pivot tables */ allowPivotTables?: boolean; /** Allow editing objects such as charts, shapes, and images */ allowEditObjects?: boolean; /** Allow editing scenarios */ allowEditScenarios?: boolean; } ``` ## ProtectionOperation Valid operations for structural protection checks. ```typescript type ProtectionOperation = | 'insertRows' | 'insertColumns' | 'deleteRows' | 'deleteColumns' | 'formatCells' | 'formatRows' | 'formatColumns' | 'sort' | 'filter' | 'editObject' ``` ## ProtectionOptions Granular options for sheet protection. ```typescript type ProtectionOptions = { /** Allow selecting locked cells */ allowSelectLockedCells?: boolean; /** Allow selecting unlocked cells */ allowSelectUnlockedCells?: boolean; /** Allow formatting cells */ allowFormatCells?: boolean; /** Allow formatting columns */ allowFormatColumns?: boolean; /** Allow formatting rows */ allowFormatRows?: boolean; /** Allow inserting columns */ allowInsertColumns?: boolean; /** Allow inserting rows */ allowInsertRows?: boolean; /** Allow inserting hyperlinks */ allowInsertHyperlinks?: boolean; /** Allow deleting columns */ allowDeleteColumns?: boolean; /** Allow deleting rows */ allowDeleteRows?: boolean; /** Allow sorting */ allowSort?: boolean; /** Allow using auto-filter */ allowAutoFilter?: boolean; /** Allow using pivot tables */ allowPivotTables?: boolean; /** Allow editing objects such as charts, shapes, and images */ allowEditObjects?: boolean; /** Allow editing scenarios */ allowEditScenarios?: boolean; } ``` ## RadarSubType Radar chart sub-types ```typescript type RadarSubType = 'basic' | 'filled' ``` ## RadicalNode Radical - Square root or n-th root ```typescript type RadicalNode = { type: 'rad'; /** Hide degree (for square root) */ degHide?: boolean; /** Degree (n in n-th root) */ deg: MathNode[]; /** Radicand (content under root) */ e: MathNode[]; } ``` ## RangePixelPosition Pixel bounds of a range (top/left offset from worksheet origin, height, width). ```typescript type RangePixelPosition = { /** Pixel offset of the range's top edge from the worksheet origin */ top: number; /** Pixel offset of the range's left edge from the worksheet origin */ left: number; /** Height of the range in pixels */ height: number; /** Width of the range in pixels */ width: number; } ``` ## RangeValueType Per-cell value type classification. Matches the workbook range value-type enum values. ```typescript enum RangeValueType { Empty = 'Empty', String = 'String', Double = 'Double', Boolean = 'Boolean', Error = 'Error', } ``` ## RawCellData Complete raw cell data including formula, formatting, and metadata. Unlike `CellData` from core (which is the minimal read type), `RawCellData` includes all optional cell metadata useful for bulk reads and LLM presentation. ```typescript type RawCellData = { /** The computed cell value */ value: CellValue; /** The formula string with "=" prefix, if the cell contains a formula */ formula?: FormulaA1; /** Cell formatting */ format?: CellFormat; /** Cell borders */ borders?: CellBorders; /** Cell comment/note text */ comment?: string; /** Hyperlink URL */ hyperlink?: string; /** Whether the cell is part of a merged region */ isMerged?: boolean; /** The merged region this cell belongs to (A1 notation, e.g., "A1:B2") */ mergedRegion?: string; } ``` ## RecognitionResult Union type for all recognition results. ```typescript type RecognitionResult = RecognizedShape | RecognizedText ``` ## RecognizedShape A shape recognized from one or more ink strokes. Recognition converts freehand strokes into clean geometric shapes while preserving the original strokes for undo/redo. ```typescript type RecognizedShape = { /** Type discriminator */ type: 'shape'; /** Recognized shape type */ shapeType: RecognizedShapeType; /** Shape parameters (position, dimensions, etc.) */ params: ShapeParams; /** IDs of the source strokes that were recognized as this shape. Used for: - Undo: Can restore original strokes - Styling: Shape inherits color/width from source strokes */ sourceStrokeIds: StrokeId[]; /** Confidence score [0, 1] for the recognition */ confidence: number; /** Timestamp when recognition occurred */ recognizedAt: number; } ``` ## RecognizedText Text recognized from handwritten ink strokes. Handwriting recognition converts ink to text with multiple alternative interpretations ranked by confidence. ```typescript type RecognizedText = { /** Type discriminator */ type: 'text'; /** Primary recognized text (highest confidence) */ text: string; /** Alternative interpretations ranked by confidence. First element is same as `text` field. */ alternatives: TextAlternative[]; /** IDs of the source strokes that were recognized as this text. Used for undo and re-recognition. */ sourceStrokeIds: StrokeId[]; /** Bounding box for the recognized text */ bounds: { x: number; y: number; width: number; height: number; }; /** Timestamp when recognition occurred */ recognizedAt: number; } ``` ## RedoReceipt Receipt for a redo operation. ```typescript type RedoReceipt = { kind: 'redo'; success: boolean; } ``` ## ReflectionEffect Reflection effect configuration. ```typescript type ReflectionEffect = { /** Blur amount for the reflection */ blur: number; /** Distance from the shape to the reflection */ distance: number; /** Opacity of the reflection (0 = transparent, 1 = opaque) */ opacity: number; /** Size of the reflection relative to the shape (0-1) */ size: number; } ``` ## RegionBounds Region rectangle dimensions in cells. Together with `anchorRow` / `anchorCol` describes the full region rectangle. ```typescript type RegionBounds = { rows: number; cols: number; } ``` ## RegionKind Region kind discriminant — string union matching Rust's `serde(rename_all = "camelCase")` serialization of `enum RegionKind`. - `arraySpill` — modern dynamic-array spill (e.g. `=SEQUENCE(5)`). The formula bar does NOT brace-wrap members. - `cseArray` — legacy Ctrl+Shift+Enter array formula. Formula bar brace-wraps (`{=…}`). - `dataTable` — XLSX ``. Formula bar brace-wraps (`{=TABLE(…)}`). Mirrors `kernel/src/bridges/compute/types.ts::RegionKind` and Rust's `snapshot_types::properties::RegionKind`. Re-exported from the bridge to keep the wire types in one place. ```typescript type RegionKind = 'arraySpill' | 'cseArray' | 'dataTable' ``` ## RegionMapConfig Region map chart configuration ```typescript type RegionMapConfig = { /** Geographic region scope */ region?: 'world' | 'us' | 'europe' | 'asia' | 'africa' | 'oceania' | 'southAmerica'; /** Color scale for region fills */ colorScale?: string[]; /** Show region labels */ showLabels?: boolean; /** Projection type */ projection?: 'mercator' | 'equalEarth' | 'naturalEarth'; } ``` ## RegionMeta Region membership shape carried on `StoreCellData.region`. `isAnchor` distinguishes the formula-owning cell (CSE anchor / Data Table master) from members. **No `source` field** — formula text lives on `StoreCellData.formula`; brace policy is a per-`kind` switch. ```typescript type RegionMeta = { kind: RegionKind; isAnchor: boolean; anchorRow: number; anchorCol: number; bounds: RegionBounds; } ``` ## RemoveDuplicatesResult Result of a remove-duplicates operation. ```typescript type RemoveDuplicatesResult = { /** Number of duplicate rows removed */ removedCount: number; /** Number of unique rows remaining */ remainingCount: number; } ``` ## RenderScheduler Scheduler that bridges buffer writes to canvas layer invalidation. Implements the "Write = Invalidate" contract: when viewport buffers receive patches, they call these methods to mark the appropriate canvas layers dirty and wake the render loop. This is a contracts-level mirror of the canvas-engine RenderScheduler so that contracts does not depend on @mog/canvas-engine at runtime. ```typescript type RenderScheduler = { /** Cell value or format changed — mark cells layer dirty. */ markCellsDirty(cells?: { row: number; col: number }[]): void;; /** Row/col dimensions changed — mark cells + headers + selection dirty. */ markGeometryDirty(): void;; /** Full buffer swap or theme change — mark all layers dirty. */ markAllDirty(): void;; } ``` ## ResolvedCellFormat Dense cell format where every property is explicitly present (null when unset). Returned by formats.get(). ```typescript type ResolvedCellFormat = { [K in keyof CellFormat]-?: CellFormat[K] | null; } ``` ## RetargetWorkbookLinkInput ```typescript type RetargetWorkbookLinkInput = { target: PersistedLinkTarget; expectedWorkbookId?: WorkbookId | null; displayName?: string; sourceKind?: WorkbookLinkSourceKind; materializedCacheMetadata?: AuthorizedMaterializedCacheMetadata; } ``` ## RichTextRun ```typescript type RichTextRun = { text: string; fontName: string | null; fontSize: number | null; bold: boolean; italic: boolean; underline: boolean; strikethrough: boolean; color: string | null; colorIndexed?: number; colorTheme?: number; colorTint?: number; charset: number | null; family: number | null; scheme: string | null; vertAlign?: string; preserveSpace?: boolean; } ``` ## Scenario A saved scenario with metadata. ```typescript type Scenario = { /** Unique scenario ID */ id: string; /** Creation timestamp (Unix ms) */ createdAt: number; } ``` ## ScenarioConfig Configuration for creating a what-if scenario. ```typescript type ScenarioConfig = { /** Scenario name */ name: string; /** Cell addresses that change (A1 notation) */ changingCells: string[]; /** Values for the changing cells, in the same order */ values: (string | number | boolean | null)[]; /** Optional description */ comment?: string; } ``` ## Schema A schema is a record of field names to their definitions. This is the single source of truth for a Yjs structure's shape. Example: ```typescript const SHEET_MAPS_SCHEMA = { meta: { type: 'Y.Map', required: true, copy: 'deep', lazyInit: false }, cells: { type: 'Y.Map', valueType: 'SerializedCellData', required: true, copy: 'deep', lazyInit: false }, // ... etc } as const satisfies Schema; ``` ```typescript type Schema = Record ``` ## ScreenshotOptions Options for capturing a sheet screenshot as a PNG image. ```typescript type ScreenshotOptions = { /** Device pixel ratio (1 = standard, 2 = Retina). Default: 1. */ dpr?: number; /** Whether to render row/column headers. Default: true. */ showHeaders?: boolean; /** Whether to render gridlines. Default: true. */ showGridlines?: boolean; /** Maximum pixel width — scales down if exceeded. */ maxWidth?: number; /** Maximum pixel height — scales down if exceeded. */ maxHeight?: number; } ``` ## ScrollPosition Scroll position (cell-level, not pixel-level). ```typescript type ScrollPosition = { /** Top visible row index (0-based). */ topRow: number; /** Left visible column index (0-based). */ leftCol: number; } ``` ## SearchOptions Options for cell search operations. ```typescript type SearchOptions = { /** Whether the search is case-sensitive */ matchCase?: boolean; /** Whether to match the entire cell value */ entireCell?: boolean; /** Whether to search formula text instead of computed values */ searchFormulas?: boolean; /** Limit search to this range (A1 notation). Used by regexSearch; ignored by findInRange (use its range parameter instead). */ range?: string; } ``` ## SearchResult A single search result. ```typescript type SearchResult = { /** Cell address in A1 notation */ address: string; /** The cell's display value */ value: string; /** The cell's formula (if any) */ formula?: string; } ``` ## SerializedCellData Serialized cell data for Yjs storage. Uses short keys for compact CRDT storage. NOTE: The DiffCellData type (previously in contracts/src/versioning.ts) was removed when the versioning package was deleted. ```typescript type SerializedCellData = { /** Stable cell identity */ id: CellId; /** Row position */ row: number; /** Column position */ col: number; /** Raw value (CellRawValue). Can be a primitive (string, number, boolean, null) or RichText array. Rich text is only valid for literal values, not formula results. Use isRichText() from @mog-sdk/contracts to discriminate. Use rawToCellValue() to convert to CellValue when needed. */ r: CellRawValue; /** A1-style formula string without '=' prefix (backward compatible) */ f?: string; /** Parsed identity formula */ idf?: IdentityFormula; /** Computed value (omit if same as raw) */ c?: CellValue; /** Note (omit if empty) */ n?: string; /** Hyperlink URL (omit if none) */ h?: string; /** For spill anchor cells: the dimensions of the spill range. { rows, cols } where rows >= 1 and cols >= 1. Only present on the cell containing the array formula. */ spillRange?: { rows: number; cols: number }; /** For spill member cells: CellId of the anchor cell containing the formula. Points back to the cell that owns this spill range. Used for: - Determining if editing this cell should be blocked - Finding the formula when clicking a spill cell - Clearing old spill when anchor formula result changes size */ spillAnchor?: CellId; /** True if this is a legacy CSE (Ctrl+Shift+Enter) array formula. CSE formulas have fixed size and show {=formula} in the formula bar. Only present on anchor cells when isCSE is true. */ isCSE?: boolean; } ``` ## SeriesConfig Individual series configuration (matches ChartSeriesData wire type) ```typescript type SeriesConfig = { name?: string; type?: string; color?: string; values?: string; categories?: string; bubbleSize?: string; smooth?: boolean; explosion?: number; invertIfNegative?: boolean; yAxisIndex?: number; showMarkers?: boolean; markerSize?: number; markerStyle?: string; lineWidth?: number; points?: PointFormat[]; dataLabels?: DataLabelConfig; trendlines?: TrendlineConfig[]; errorBars?: ErrorBarConfig; xErrorBars?: ErrorBarConfig; yErrorBars?: ErrorBarConfig; idx?: number; order?: number; format?: ChartFormat; barShape?: string; /** Color to use when a data point is inverted (negative) */ invertColor?: ChartColor; /** Marker fill color. */ markerBackgroundColor?: ChartColor; /** Marker border color. */ markerForegroundColor?: ChartColor; /** Whether this series is hidden/filtered from the chart. */ filtered?: boolean; /** Show drop shadow on series. */ showShadow?: boolean; /** Show connector lines between pie slices (bar-of-pie, pie-of-pie). */ showConnectorLines?: boolean; /** Gap width between bars/columns as percentage (per-series override) */ gapWidth?: number; /** Overlap between bars/columns (-100 to 100, per-series override) */ overlap?: number; /** Hole size for doughnut charts as percentage (per-series override) */ doughnutHoleSize?: number; /** First slice angle for pie/doughnut charts in degrees (per-series override) */ firstSliceAngle?: number; /** Split type for of-pie charts (per-series override) */ splitType?: string; /** Split value threshold for of-pie charts (per-series override) */ splitValue?: number; /** Bubble scale as percentage (per-series override) */ bubbleScale?: number; leaderLineFormat?: ChartFormat; showLeaderLines?: boolean; /** Per-series histogram bin options (overrides chart-level histogram config) */ binOptions?: HistogramConfig; /** Per-series box/whisker options (overrides chart-level boxplot config) */ boxwhiskerOptions?: BoxplotConfig; /** @deprecated Use trendlines[] instead */ trendline?: TrendlineConfig; } ``` ## SeriesOrientation Data series orientation ```typescript type SeriesOrientation = 'rows' | 'columns' ``` ## SetCellsResult Result of a bulk setCells() operation. ```typescript type SetCellsResult = { /** Number of cells successfully written */ cellsWritten: number; /** Per-cell errors, if any (omitted when all succeed) */ errors?: Array<{ addr: string; error: string }> | null; /** Non-fatal warnings (e.g., deduplication, coercion) */ warnings?: OperationWarning[]; } ``` ## ShadowAlignment Shadow alignment options. Specifies the alignment of the shadow relative to the text. The shadow is positioned based on this anchor point. @see ECMA-376 Part 1, Section 20.1.10.3 (ST_RectAlignment) ```typescript type ShadowAlignment = | 'tl' // Top-left | 't' // Top-center | 'tr' // Top-right | 'l' // Middle-left | 'ctr' // Center | 'r' // Middle-right | 'bl' // Bottom-left | 'b' // Bottom-center | 'br' ``` ## ShadowEffect Drop shadow effect configuration. ```typescript type ShadowEffect = { /** Shadow color (CSS color string) */ color: string; /** Blur radius in pixels */ blur: number; /** Horizontal offset in pixels */ offsetX: number; /** Vertical offset in pixels */ offsetY: number; /** Opacity (0 = transparent, 1 = opaque) */ opacity: number; } ``` ## Shape Shape as returned by get/list operations. Extends ShapeConfig with identity and metadata fields. Same pattern as Chart extends ChartConfig. ```typescript type Shape = { /** Unique shape ID */ id: string; /** Sheet ID the shape belongs to */ sheetId: string; /** Z-order within the sheet */ zIndex: number; /** Creation timestamp (Unix ms) */ createdAt?: number; /** Last update timestamp (Unix ms) */ updatedAt?: number; } ``` ## ShapeConfig Shape configuration for creating/updating shapes. Uses simple integer positions (anchorRow/anchorCol) for the public API. Internal storage uses CellId-based ObjectPosition. Preserves full fidelity: gradient fills, arrowhead outlines, rich text. ```typescript type ShapeConfig = { /** Shape type (rect, ellipse, triangle, etc.) */ type: ShapeType; /** Anchor row (0-based) */ anchorRow: number; /** Anchor column (0-based) */ anchorCol: number; /** X offset from anchor cell in pixels */ xOffset?: number; /** Y offset from anchor cell in pixels */ yOffset?: number; /** Width in pixels */ width: number; /** Height in pixels */ height: number; /** Absolute pixel X on the sheet. When set, Rust resolves to anchorCol + xOffset. */ pixelX?: number; /** Absolute pixel Y on the sheet. When set, Rust resolves to anchorRow + yOffset. */ pixelY?: number; /** Optional name for the shape */ name?: string; /** Fill configuration (solid, gradient with stops/angle, or none) */ fill?: ObjectFill; /** Outline/stroke configuration (with optional arrowheads) */ outline?: ShapeOutline; /** Rich text content inside the shape (with CellFormat) */ text?: ShapeText; /** Shadow effect */ shadow?: OuterShadowEffect; /** Rotation angle in degrees (0-360) */ rotation?: number; /** Whether the shape is locked */ locked?: boolean; /** Shape-specific adjustments (e.g., cornerRadius for roundRect) */ adjustments?: Record; /** Whether the shape is visible (default: true). */ visible?: boolean; /** Anchor mode: how the shape anchors to cells (twoCell/oneCell/absolute). */ anchorMode?: ObjectAnchorType; /** Whether to preserve aspect ratio when resizing */ lockAspectRatio?: boolean; /** Accessibility title for the shape (distinct from alt text description) */ altTextTitle?: string; /** User-visible display name (may differ from internal name) */ displayName?: string; } ``` ## ShapeEffects Visual effects that can be applied to shapes. ```typescript type ShapeEffects = { /** Drop shadow effect */ shadow?: ShadowEffect; /** Glow effect around the shape */ glow?: GlowEffect; /** Reflection effect below the shape */ reflection?: ReflectionEffect; /** 3D bevel effect */ bevel?: BevelEffect; /** 3D transformation effect */ transform3D?: Transform3DEffect; } ``` ## ShapeHandle ```typescript type ShapeHandle = { shapeType: ShapeType; update(props: Partial): Promise;; duplicate(offsetX?: number, offsetY?: number): Promise;; getData(): Promise;; } ``` ## ShapeObject Shape floating object. A geometric shape with optional fill, outline, and text. ```typescript type ShapeObject = { type: 'shape'; /** Type of shape to render */ shapeType: ShapeType; /** Fill configuration */ fill?: ObjectFill; /** Outline/stroke configuration */ outline?: ShapeOutline; /** Text content inside the shape */ text?: ShapeText; /** Shadow effect (outer shadow / drop shadow) */ shadow?: OuterShadowEffect; /** Shape-specific adjustments. Keys depend on shape type (e.g., 'cornerRadius' for roundRect, 'arrowHeadSize' for arrows, 'starPoints' for stars). */ adjustments?: Record; } ``` ## ShapeOutline Shape outline/stroke configuration. ```typescript type ShapeOutline = { /** Outline style */ style: 'none' | 'solid' | 'dashed' | 'dotted'; /** Outline color (CSS color string) */ color: string; /** Outline width in pixels */ width: number; /** Head (start) arrowhead configuration */ headEnd?: { type: LineEndType; width?: LineEndSize; length?: LineEndSize }; /** Tail (end) arrowhead configuration */ tailEnd?: { type: LineEndType; width?: LineEndSize; length?: LineEndSize }; /** Detailed dash pattern (overrides coarse `style` when set). Matches OOXML dash styles. */ dash?: LineDash; /** Outline transparency (0 = opaque, 1 = fully transparent). */ transparency?: number; /** Compound line style (e.g., double, thickThin). */ compound?: CompoundLineStyle; /** Whether the outline is visible. */ visible?: boolean; } ``` ## ShapeText ```typescript type ShapeText = { /** Text content */ content: string; /** Text formatting */ format?: CellFormat; /** Rich text runs for per-run formatting. When present, authoritative over content+format. */ runs?: TextRun[]; /** Vertical alignment of text within shape */ verticalAlign?: 'top' | 'middle' | 'bottom' | 'justified' | 'distributed'; /** Horizontal alignment of text within shape */ horizontalAlign?: 'left' | 'center' | 'right' | 'justify' | 'distributed'; /** Text margins within the container */ margins?: TextMargins; /** Auto-size behavior */ autoSize?: TextAutoSize; /** Text orientation */ orientation?: TextOrientation; /** Reading order / directionality */ readingOrder?: TextReadingOrder; /** Horizontal overflow behavior */ horizontalOverflow?: TextOverflow; /** Vertical overflow behavior */ verticalOverflow?: TextOverflow; } ``` ## ShapeType Available shape types. Matches common common spreadsheet shape categories. Extracted here (rather than in `floating-objects.ts`) so that diagram and other subtype modules can reference a subset without creating a cycle back into `floating-objects.ts`. ```typescript type ShapeType = | 'rect' | 'roundRect' | 'ellipse' | 'triangle' | 'rtTriangle' | 'diamond' | 'pentagon' | 'hexagon' | 'octagon' | 'parallelogram' | 'trapezoid' | 'nonIsoscelesTrapezoid' | 'heptagon' | 'decagon' | 'dodecagon' | 'teardrop' | 'pie' | 'pieWedge' | 'blockArc' | 'donut' | 'noSmoking' | 'plaque' // Rectangle variants (rounded/snipped) | 'round1Rect' | 'round2SameRect' | 'round2DiagRect' | 'snip1Rect' | 'snip2SameRect' | 'snip2DiagRect' | 'snipRoundRect' // Arrows | 'rightArrow' | 'leftArrow' | 'upArrow' | 'downArrow' | 'leftRightArrow' | 'upDownArrow' | 'quadArrow' | 'chevron' // Arrow Callouts | 'leftArrowCallout' | 'rightArrowCallout' | 'upArrowCallout' | 'downArrowCallout' | 'leftRightArrowCallout' | 'upDownArrowCallout' | 'quadArrowCallout' // Curved/Special Arrows | 'bentArrow' | 'uturnArrow' | 'circularArrow' | 'leftCircularArrow' | 'leftRightCircularArrow' | 'curvedRightArrow' | 'curvedLeftArrow' | 'curvedUpArrow' | 'curvedDownArrow' | 'swooshArrow' // Stars and banners | 'star4' | 'star5' | 'star6' | 'star7' | 'star8' | 'star10' | 'star12' | 'star16' | 'star24' | 'star32' | 'ribbon' | 'ribbon2' | 'ellipseRibbon' | 'ellipseRibbon2' | 'leftRightRibbon' | 'banner' // Callouts | 'wedgeRectCallout' | 'wedgeRoundRectCallout' | 'wedgeEllipseCallout' | 'cloud' | 'callout1' | 'callout2' | 'callout3' | 'borderCallout1' | 'borderCallout2' | 'borderCallout3' | 'accentCallout1' | 'accentCallout2' | 'accentCallout3' | 'accentBorderCallout1' | 'accentBorderCallout2' | 'accentBorderCallout3' // Lines and connectors | 'line' | 'lineArrow' | 'lineDoubleArrow' | 'curve' | 'arc' | 'connector' | 'bentConnector2' | 'bentConnector3' | 'bentConnector4' | 'bentConnector5' | 'curvedConnector2' | 'curvedConnector3' | 'curvedConnector4' | 'curvedConnector5' // Flowchart shapes | 'flowChartProcess' | 'flowChartDecision' | 'flowChartInputOutput' | 'flowChartPredefinedProcess' | 'flowChartInternalStorage' | 'flowChartDocument' | 'flowChartMultidocument' | 'flowChartTerminator' | 'flowChartPreparation' | 'flowChartManualInput' | 'flowChartManualOperation' | 'flowChartConnector' | 'flowChartPunchedCard' | 'flowChartPunchedTape' | 'flowChartSummingJunction' | 'flowChartOr' | 'flowChartCollate' | 'flowChartSort' | 'flowChartExtract' | 'flowChartMerge' | 'flowChartOfflineStorage' | 'flowChartOnlineStorage' | 'flowChartMagneticTape' | 'flowChartMagneticDisk' | 'flowChartMagneticDrum' | 'flowChartDisplay' | 'flowChartDelay' | 'flowChartAlternateProcess' | 'flowChartOffpageConnector' // Decorative symbols | 'heart' | 'lightningBolt' | 'sun' | 'moon' | 'smileyFace' | 'foldedCorner' | 'bevel' | 'frame' | 'halfFrame' | 'corner' | 'diagStripe' | 'chord' | 'can' | 'cube' | 'plus' | 'cross' | 'irregularSeal1' | 'irregularSeal2' | 'homePlate' | 'funnel' | 'verticalScroll' | 'horizontalScroll' // Action Buttons | 'actionButtonBlank' | 'actionButtonHome' | 'actionButtonHelp' | 'actionButtonInformation' | 'actionButtonForwardNext' | 'actionButtonBackPrevious' | 'actionButtonEnd' | 'actionButtonBeginning' | 'actionButtonReturn' | 'actionButtonDocument' | 'actionButtonSound' | 'actionButtonMovie' // Brackets and Braces | 'leftBracket' | 'rightBracket' | 'leftBrace' | 'rightBrace' | 'bracketPair' | 'bracePair' // Math shapes | 'mathPlus' | 'mathMinus' | 'mathMultiply' | 'mathDivide' | 'mathEqual' | 'mathNotEqual' // Miscellaneous | 'gear6' | 'gear9' | 'cornerTabs' | 'squareTabs' | 'plaqueTabs' | 'chartX' | 'chartStar' | 'chartPlus' ``` ## Sheet Minimal Sheet interface for selector functions. This represents the deserialized view of sheet data used by selectors. The floatingObjects array is the deserialized form of the Y.Map storage. ```typescript type Sheet = { /** Array of floating objects on the sheet (deserialized from Y.Map) */ floatingObjects?: FloatingObject[]; } ``` ## SheetDataBindingInfo Information about an existing sheet data binding. ```typescript type SheetDataBindingInfo = { /** Unique binding identifier */ id: string; /** Connection providing the data */ connectionId: string; /** Maps data fields to columns */ columnMappings: ColumnMapping[]; /** Auto-insert/delete rows to match data length */ autoGenerateRows: boolean; /** Row index for headers (-1 = no header row) */ headerRow: number; /** First row of data (0-indexed) */ dataStartRow: number; /** Preserve header row formatting on refresh */ preserveHeaderFormatting: boolean; /** Last refresh timestamp */ lastRefresh?: number; } ``` ## SheetHideReceipt Receipt for a sheet hide mutation. ```typescript type SheetHideReceipt = { kind: 'sheetHide'; name: string; } ``` ## SheetId ```typescript type SheetId = string & { readonly [__sheetId]: true } ``` ## SheetMoveReceipt Receipt for a sheet move mutation. ```typescript type SheetMoveReceipt = { kind: 'sheetMove'; name: string; newIndex: number; } ``` ## SheetRange ```typescript type SheetRange = { startRow: number; startCol: number; endRow: number; endCol: number; } ``` ## SheetRangeDescribeResult Result entry for one sheet range in a batch read. ```typescript type SheetRangeDescribeResult = { /** Sheet name (as resolved). */ sheet: string; /** The range that was actually read. */ range: string; /** The LLM-formatted description (same format as ws.describeRange). Empty string if error. */ description: string; /** Set if this entry failed (bad sheet name, empty sheet, etc.). */ error?: string; } ``` ## SheetRangeRequest A request for a range read on a specific sheet (used by wb.describeRanges). ```typescript type SheetRangeRequest = { /** Sheet name (case-insensitive lookup). */ sheet: string; /** A1-style range, e.g. "A1:M50". If omitted, reads used range. */ range?: string; } ``` ## SheetRemoveReceipt Receipt for a sheet remove mutation. ```typescript type SheetRemoveReceipt = { kind: 'sheetRemove'; removedName: string; remainingCount: number; } ``` ## SheetRenameReceipt Receipt for a sheet rename mutation. ```typescript type SheetRenameReceipt = { kind: 'sheetRename'; oldName: string; newName: string; } ``` ## SheetSettingsInfo Full sheet settings (mirrors SheetSettings from core contracts). ```typescript type SheetSettingsInfo = { /** Default row height in pixels */ defaultRowHeight: number; /** Default column width in pixels */ defaultColWidth: number; /** Whether gridlines are shown */ showGridlines: boolean; /** Whether row headers are shown */ showRowHeaders: boolean; /** Whether column headers are shown */ showColumnHeaders: boolean; /** Whether zero values are displayed (false = blank) */ showZeroValues: boolean; /** Gridline color (hex string) */ gridlineColor: string; /** Whether the sheet is protected */ isProtected: boolean; /** Whether the sheet uses right-to-left layout */ rightToLeft: boolean; } ``` ## SheetShowReceipt Receipt for a sheet show mutation. ```typescript type SheetShowReceipt = { kind: 'sheetShow'; name: string; } ``` ## SheetSnapshot A summary snapshot of a single sheet. ```typescript type SheetSnapshot = { /** Sheet ID */ id: string; /** Sheet name */ name: string; /** Sheet index (0-based) */ index: number; /** Range containing all non-empty cells, or null if sheet is empty */ usedRange: CellRange | null; /** Number of cells with data */ cellCount: number; /** Number of cells with formulas */ formulaCount: number; /** Number of charts in this sheet */ chartCount: number; /** Sheet dimensions */ dimensions: { rows: number; cols: number }; } ``` ## ShowValuesAs ```typescript type ShowValuesAs = 'noCalculation' | 'percentOfGrandTotal' | 'percentOfColumnTotal' | 'percentOfRowTotal' | 'percentOfParentRowTotal' | 'percentOfParentColumnTotal' | 'difference' | 'percentDifference' | 'runningTotal' | 'percentRunningTotal' | 'rankAscending' | 'rankDescending' | 'index' ``` ## ShowValuesAsConfig ```typescript type ShowValuesAsConfig = { type: ShowValuesAs; baseField?: string; baseItem?: { type: 'relative'; position: 'previous' | 'next' } | { type: 'specific'; value: CellValue }; } ``` ## SignAnomaly A single cell whose sign disagrees with its neighbors. ```typescript type SignAnomaly = { /** A1 address of the anomalous cell. */ cell: string; /** The cell's computed numeric value. */ value: number; /** Fraction of neighbors with the opposite sign (0.0–1.0). 1.0 = every neighbor disagrees. Sorted descending. */ disagreement: number; /** The neighboring cells that were considered. */ neighbors: { cell: string; value: number }[]; } ``` ## SignCheckOptions Options for sign anomaly detection. ```typescript type SignCheckOptions = { /** Which axis to check sign consistency along. - `'column'`: compare cells vertically within each column (default). - `'row'`: compare cells horizontally within each row. - `'both'`: run both checks, merge results. */ axis?: 'column' | 'row' | 'both'; /** How many non-empty numeric neighbors to consider in each direction. Default: 3 (up to 6 neighbors total per axis). */ window?: number; } ``` ## SignCheckResult Result of a signCheck call. ```typescript type SignCheckResult = { /** Total non-zero numeric cells examined. */ cellsChecked: number; /** Cells whose sign disagrees with the majority of their neighbors. */ anomalies: SignAnomaly[]; } ``` ## SingleAxisConfig Single axis configuration (matches SingleAxisData wire type). ```typescript type SingleAxisConfig = { title?: string; visible: boolean; min?: number; max?: number; axisType?: string; gridLines?: boolean; minorGridLines?: boolean; majorUnit?: number; minorUnit?: number; tickMarks?: string; minorTickMarks?: string; numberFormat?: string; reverse?: boolean; position?: string; logBase?: number; displayUnit?: string; format?: ChartFormat; titleFormat?: ChartFormat; gridlineFormat?: ChartLineFormat; minorGridlineFormat?: ChartLineFormat; crossBetween?: string; tickLabelPosition?: string; baseTimeUnit?: string; majorTimeUnit?: string; minorTimeUnit?: string; customDisplayUnit?: number; displayUnitLabel?: string; labelAlignment?: string; labelOffset?: number; noMultiLevelLabels?: boolean; /** Scale type: linear or logarithmic */ scaleType?: 'linear' | 'logarithmic'; /** Category axis type */ categoryType?: 'automatic' | 'textAxis' | 'dateAxis'; /** Where the axis crosses */ crossesAt?: 'automatic' | 'max' | 'min' | 'custom'; /** Custom crossing value when crossesAt is 'custom' */ crossesAtValue?: number; /** Whether the axis title is visible (separate from title text content). */ titleVisible?: boolean; /** Interval between tick labels (e.g., 1 = every label, 2 = every other). */ tickLabelSpacing?: number; /** Interval between tick marks. */ tickMarkSpacing?: number; /** Whether the number format is linked to the source data cell format. */ linkNumberFormat?: boolean; /** Whether tick marks are between categories (true) or on categories (false) */ isBetweenCategories?: boolean; /** Text orientation angle in degrees (-90 to 90) */ textOrientation?: number; /** Label alignment (alias for labelAlignment) */ alignment?: string; /** @deprecated Alias for axisType — kept for backward compat with charts package */ type?: AxisType; /** @deprecated Alias for visible — kept for backward compat with charts package */ show?: boolean; } ``` ## Size A 2D size (width and height). ```typescript type Size = { width: number; height: number; } ``` ## Slicer Full slicer state including selection and position. ```typescript type Slicer = { /** Currently selected filter items */ selectedItems: CellValue[]; /** Position and dimensions in pixels */ position: { x: number; y: number; width: number; height: number }; } ``` ## SlicerConfig Configuration for creating a new slicer. ```typescript type SlicerConfig = { /** Slicer ID (generated if omitted) */ id?: string; /** Sheet ID the slicer belongs to */ sheetId?: string; /** Name of the table to connect the slicer to */ tableName?: string; /** Column name within the table to filter on */ columnName?: string; /** Display name for the slicer (auto-generated if omitted) */ name?: string; /** Position and dimensions in pixels */ position?: { x: number; y: number; width: number; height: number }; /** Data source connection (rich alternative to tableName/columnName) */ source?: SlicerSource; /** Slicer caption (header text) */ caption?: string; /** Style configuration */ style?: SlicerStyle; /** Show slicer header */ showHeader?: boolean; /** Z-order within the sheet */ zIndex?: number; /** Whether slicer position is locked */ locked?: boolean; /** Whether multi-select is enabled */ multiSelect?: boolean; /** Initial selected values */ selectedValues?: CellValue[]; /** Currently selected date range start (timeline slicers) */ selectedStartDate?: number; /** Currently selected date range end (timeline slicers) */ selectedEndDate?: number; /** Current aggregation level (timeline slicers) */ timelineLevel?: TimelineLevel; } ``` ## SlicerCustomStyle Custom slicer style definition. Canonical source: compute-types.gen.ts (Rust domain-types) ```typescript type SlicerCustomStyle = { /** Header background color */ headerBackgroundColor?: string; /** Header text color */ headerTextColor?: string; /** Header font size */ headerFontSize?: number; /** Selected item background color */ selectedBackgroundColor?: string; /** Selected item text color */ selectedTextColor?: string; /** Available item background color */ availableBackgroundColor?: string; /** Available item text color */ availableTextColor?: string; /** Unavailable item background color */ unavailableBackgroundColor?: string; /** Unavailable item text color */ unavailableTextColor?: string; /** Border color */ borderColor?: string; /** Border width in pixels */ borderWidth?: number; /** Corner radius for items */ itemBorderRadius?: number; } ``` ## SlicerInfo Summary information about a slicer. ```typescript type SlicerInfo = { /** Unique slicer ID */ id: string; /** Programmatic name (unique within workbook). Falls back to caption if not set. */ name: string; /** Display caption (header text). */ caption: string; /** Connected table name */ tableName: string; /** Connected column name */ columnName: string; /** Source type — 'table' for table slicers, 'pivot' for pivot table slicers */ source?: { type: 'table' | 'pivot' }; /** Discriminator for timeline slicers (matches TimelineSlicerConfig.sourceType) */ sourceType?: 'timeline'; } ``` ## SlicerItem A single item in a slicer's value list. ```typescript type SlicerItem = { /** The display value */ value: CellValue; /** Whether this item is currently selected */ selected: boolean; /** Number of matching records (if available) */ count?: number; } ``` ## SlicerPivotSource Reference to a pivot field for slicer binding. ```typescript type SlicerPivotSource = { type: 'pivot'; /** Pivot table ID to connect to */ pivotId: string; /** Field name in the pivot (row/column/filter field) */ fieldName: string; /** Which area the field is in */ fieldArea: 'row' | 'column' | 'filter'; } ``` ## SlicerSortOrder Slicer sort order. Canonical source: compute-types.gen.ts ```typescript type SlicerSortOrder = 'ascending' | 'descending' | 'dataSourceOrder' ``` ## SlicerSource Union type for slicer data sources. Canonical source: compute-types.gen.ts (Rust domain-types) Generated version uses intersection with helper interfaces: `{ type: "table" } & SlicerSource_table | { type: "pivot" } & SlicerSource_pivot` Contracts uses named interface variants. Both are structurally identical (same internally-tagged discriminated union shape). No bridge conversion needed. ```typescript type SlicerSource = SlicerTableSource | SlicerPivotSource ``` ## SlicerState Enriched runtime state for a slicer (includes computed items, connection status). ```typescript type SlicerState = { /** Computed items with selection state */ items: SlicerItem[]; /** Whether the slicer is connected to its data source */ isConnected: boolean; /** Selected values */ selectedValues: CellValue[]; /** Timeline periods (for timeline slicers) */ periods?: TimelinePeriod[]; } ``` ## SlicerStyle Complete slicer style configuration. Canonical source: compute-types.gen.ts (Rust domain-types) ```typescript type SlicerStyle = { /** Style preset (mutually exclusive with custom) */ preset?: SlicerStylePreset; /** Custom style (mutually exclusive with preset) */ custom?: SlicerCustomStyle; /** Number of columns for item layout (default: 1) */ columnCount: number; /** Button height in pixels */ buttonHeight: number; /** Show item selection indicators */ showSelectionIndicator: boolean; /** ST_SlicerCacheCrossFilter — controls cross-filtering visual indication. Replaces the previous showItemsWithNoData boolean. Default: 'showItemsWithDataAtTop' */ crossFilter: CrossFilterMode; /** Whether to use custom sort list. Default: true */ customListSort: boolean; /** Whether to show items with no matching data (x14 pivot-backed slicers). Default: true */ showItemsWithNoData: boolean; /** 'dataSourceOrder' is internal-only; never read from or written to OOXML. Import defaults to 'ascending'. */ sortOrder: SlicerSortOrder; } ``` ## SlicerStyleInfo ```typescript type SlicerStyleInfo = { name: string; isDefault: boolean; } ``` ## SlicerStylePreset Slicer style presets matching Excel's slicer style gallery. Canonical source: compute-types.gen.ts (Rust domain-types) ```typescript type SlicerStylePreset = | 'light1' | 'light2' | 'light3' | 'light4' | 'light5' | 'light6' | 'dark1' | 'dark2' | 'dark3' | 'dark4' | 'dark5' | 'dark6' | 'other1' | 'other2' ``` ## SlicerTableSource Reference to a table field for slicer binding. Uses column header CellId for Cell Identity Model compliance. **Graceful Degradation:** If the column header cell is deleted, the slicer becomes "disconnected" and shows a placeholder state. This matches Excel behavior where slicers become invalid when their source column is deleted. ```typescript type SlicerTableSource = { type: 'table'; /** Table ID to connect to */ tableId: string; /** Column header CellId - stable across column moves. If this CellId becomes orphaned (column deleted), slicer shows disconnected state. */ columnCellId: CellId; } ``` ## SmartArtCategory diagram categories matching Excel. Each category represents a different type of visual representation: - list: Sequential or grouped items - process: Steps or stages in a workflow - cycle: Continuous or circular processes - hierarchy: Organization charts, tree structures - relationship: Connections between concepts - matrix: Grid-based relationships - pyramid: Proportional or hierarchical layers - picture: Image-centric layouts ```typescript type SmartArtCategory = | 'list' | 'process' | 'cycle' | 'hierarchy' | 'relationship' | 'matrix' | 'pyramid' | 'picture' ``` ## SmartArtConfig Configuration for creating a new diagram. ```typescript type SmartArtConfig = { /** Layout ID (e.g., 'hierarchy/org-chart', 'process/basic-process'). */ layoutId: string; /** X position in pixels. */ x?: number; /** Y position in pixels. */ y?: number; /** Width in pixels. */ width?: number; /** Height in pixels. */ height?: number; /** Initial nodes to create. */ nodes?: SmartArtNodeConfig[]; /** Display name. */ name?: string; } ``` ## SmartArtDiagram diagram model (deserialized TypeScript view). IMPORTANT: This interface represents the runtime/API view of the data. Actual Yjs storage uses Y.Map and Y.Array types as defined in SMARTART_DIAGRAM_SCHEMA. The bridge handles conversion between formats. NOTE: computedLayout is NOT part of this interface because it's a runtime cache managed by the bridge, not persisted data. COPY SEMANTICS: When copying a diagramDiagram, the bridge must: 1. Generate new NodeIds for all nodes (using createNodeId()) 2. Build oldId -> newId mapping 3. Deep-copy node data (text, styling, level, siblingOrder) 4. Remap parentId and childIds references using mapping 5. Update rootNodeIds array with new IDs 6. Preserve tree structure with new identity ```typescript type SmartArtDiagram = { /** Layout ID (e.g., 'hierarchy/org-chart', 'process/basic-process') */ layoutId: string; /** Category of the diagram */ category: SmartArtCategory; /** Map of all nodes by their ID */ nodes: Map; /** Top-level (root) node IDs in display order */ rootNodeIds: NodeId[]; /** Quick style ID (e.g., 'subtle-effect', 'moderate-effect') */ quickStyleId: string; /** Color theme ID (e.g., 'colorful-1', 'accent-1') */ colorThemeId: string; /** Layout-specific options (varies by layout type) */ layoutOptions: Record; } ``` ## SmartArtNode Single node in a diagram. Nodes form a tree structure with parent-child relationships. Each node can have optional per-node styling that overrides diagram defaults. ```typescript type SmartArtNode = { /** Unique node identifier */ id: NodeId; /** Text content displayed in the node */ text: string; /** Hierarchy level (0 = root, 1 = child, 2 = grandchild, etc.) */ level: number; /** Parent node ID (null for root nodes) */ parentId: NodeId | null; /** Ordered child node IDs */ childIds: NodeId[]; /** Order among siblings (used for layout ordering) */ siblingOrder: number; /** Fill/background color (CSS color string) */ fillColor?: string; /** Border/stroke color (CSS color string) */ borderColor?: string; /** Text color (CSS color string) */ textColor?: string; /** Font family for node text */ fontFamily?: string; /** Font size in points */ fontSize?: number; /** Font weight */ fontWeight?: 'normal' | 'bold'; /** Font style */ fontStyle?: 'normal' | 'italic'; /** Image URL for picture layouts */ imageUrl?: string; /** How the image fits within the node bounds */ imageFit?: 'cover' | 'contain' | 'fill'; } ``` ## SmartArtNodeConfig Configuration for a diagram node. ```typescript type SmartArtNodeConfig = { /** Node text content. */ text: string; /** Hierarchy level (0 = root). */ level?: number; /** Insertion position relative to a reference node. */ position?: 'before' | 'after' | 'child'; /** Reference node ID for positioning. */ referenceNodeId?: string; } ``` ## SmartArtNodeId Diagram node ID type. ```typescript type SmartArtNodeId = string ``` ## SmartArtObject Diagram floating object. Diagrams provide visual representations of information like organization charts, process flows, relationship diagrams, and hierarchies. The diagram data contains the nodes and their relationships, while layout/styling is computed at render time. Architecture Notes: - Diagram data (nodes, relationships) is persisted in Yjs via the bridge layer - Selection state (selectedNodeIds, editingNodeId) lives in XState context, NOT here - Computed layout is a runtime cache, managed by the bridge - Uses existing object-interaction-machine for selection/drag/resize ```typescript type SmartArtObject = { type: 'smartart'; /** The diagram data including nodes, relationships, and styling. This is the persisted data - layout is computed at runtime. */ diagram: SmartArtDiagram; } ``` ## SmartArtShapeType diagram-specific shape types. This is a subset of the full ShapeType union from floating-objects.ts that diagram layouts commonly use. The names match exactly with the ShapeType definitions to ensure compatibility. ```typescript type SmartArtShapeType = | 'rect' | 'roundRect' | 'ellipse' | 'diamond' | 'hexagon' | 'chevron' | 'rightArrow' | 'pentagon' | 'trapezoid' | 'parallelogram' | 'plus' | 'star5' | 'cloud' | 'wedgeRectCallout' ``` ## SoftEdgeEffect Soft edge effect (feathered edges). Creates a gradual fade-out at the edges of the text, making the text appear to blend into the background. The effect creates a smooth transition from fully opaque text to fully transparent at the edges. @example // Soft fade at edges const softEdge: SoftEdgeEffect = { radius: 25400 // 2pt feather radius }; @see ECMA-376 Part 1, Section 20.1.8.57 (softEdge) ```typescript type SoftEdgeEffect = { /** Soft edge radius in EMUs. How far inward from the text edge the fade begins. Larger values create a more gradual fade. @example 25400 // 2pt radius */ radius: number; } ``` ## SolidFill Solid fill — post-theme-resolution using CSS color strings. The OOXML raw version (with DrawingColor) is in the generated ooxml-types.ts bridge. @see ECMA-376 Part 1, Section 20.1.8.51 (CT_SolidColorFillProperties) ```typescript type SolidFill = { type: 'solid'; /** Fill color (CSS color string: hex, rgb, rgba, hsl, named) */ color: string; /** Opacity (0-1, where 0 is fully transparent, 1 is fully opaque) */ opacity?: number; } ``` ## SortByColorOptions Options for {@link Worksheet.sortByColor}. Sorts the rows of a range by a color predicate on a single column. Matched-color rows are placed on top (`position: 'top'`) or bottom (`position: 'bottom'`) of the range; ties fall through to natural row order (stable sort). ```typescript type SortByColorOptions = { /** Column index (0-based, absolute) whose color drives the sort. */ column: number; /** Whether to compare against fill (cell background) or font color. */ colorType: 'fill' | 'font'; /** Hex color to match (e.g. '#FFFF00'). Case-insensitive. */ color: string; /** Place matched-color rows on top of the range or at the bottom. */ position: 'top' | 'bottom'; /** Whether the first row of the range is a header row (default: false). */ hasHeaders?: boolean; /** Sort only currently visible row slots, preserving hidden row positions. */ visibleRowsOnly?: boolean; } ``` ## SortColumn A single column sort specification. Discriminated on `sortBy`. The default ('value') accepts an optional Workbook `customList`. Color sorts (`cellColor` / `fontColor`) require a `targetColor` and `colorPosition` so invalid combinations cannot be expressed. ```typescript type SortColumn = { /** Column index (0-based, relative to the sort range) */ column: number; /** Sort direction: 'asc' (default) or 'desc'. */ direction?: 'asc' | 'desc'; /** Case sensitive comparison (default: false) */ caseSensitive?: boolean; } & ( | { /** What to sort by (default: 'value' if omitted) */ sortBy?: 'value'; /** * Optional Excel custom-list sort: values present in the list * sort by their list position; values not in the list sort * *after* list members (spreadsheet compatibility). */ customList?: CellValue[]; } | { sortBy: 'cellColor' | 'fontColor'; /** Hex color to match (e.g. '#FFFF00'). */ targetColor: string; /** Whether matched rows go to top or bottom of the sorted range. */ colorPosition: 'top' | 'bottom'; } ) ``` ## SortOptions Options for sorting a range of cells. ```typescript type SortOptions = { /** Columns to sort by, in priority order */ columns: SortColumn[]; /** Whether the first row of the range contains headers (default: false) */ hasHeaders?: boolean; /** Sort only currently visible row slots, preserving hidden row positions. */ visibleRowsOnly?: boolean; } ``` ## SortOrder Sort order for pivot fields. "none" means no explicit sort — uses natural order. Maps to Option on the Rust side (None = "none"). ```typescript type SortOrder = 'asc' | 'desc' | 'none' ``` ## Sparkline ```typescript type Sparkline = { id: string; sheetId: SheetId; cell: SparklineCellAddress; dataRange: SparklineDataRange; type: SparklineType; dataInRows: boolean; groupId?: string; visual: SparklineVisualSettings; axis: SparklineAxisSettings; createdAt?: number; updatedAt?: number; } ``` ## SparklineAxisSettings ```typescript type SparklineAxisSettings = { minValue: AxisBound; maxValue: AxisBound; showAxis?: boolean; axisColor?: string; displayEmptyCells: EmptyCellDisplay; rightToLeft?: boolean; } ``` ## SparklineCellAddress ```typescript type SparklineCellAddress = { sheetId: string; row: number; col: number; } ``` ## SparklineDataRange ```typescript type SparklineDataRange = { startRow: number; startCol: number; endRow: number; endCol: number; } ``` ## SparklineGroup ```typescript type SparklineGroup = { id: string; sheetId: string; sparklineIds: string[]; type: SparklineType; visual: SparklineVisualSettings; axis: SparklineAxisSettings; createdAt?: number; updatedAt?: number; } ``` ## SparklineType ```typescript type SparklineType = "line" | "column" | "winLoss" ``` ## SparklineVisualSettings ```typescript type SparklineVisualSettings = { color: string; negativeColor?: string; showMarkers?: boolean; markerColor?: string; highPointColor?: string; lowPointColor?: string; firstPointColor?: string; lastPointColor?: string; lineWeight?: number; columnGap?: number; barGap?: number; } ``` ## SplitViewportConfig Split view: 2-4 independently scrolling viewports. Split view creates independent panes that can each scroll separately, allowing users to compare distant regions of the spreadsheet. Viewport IDs by direction: - 'horizontal': 'top', 'bottom' (split along a row) - 'vertical': 'left', 'right' (split along a column) - 'both': 'topLeft', 'topRight', 'bottomLeft', 'bottomRight' (4 quadrants) @see plans/active/excel-parity/01-split-view-not-implemented.md ```typescript type SplitViewportConfig = { type: 'split'; /** Direction of the split */ direction: 'horizontal' | 'vertical' | 'both'; /** Row index for horizontal split line. Used when direction is 'horizontal' or 'both'. Defaults to 0 (ignored) when direction is 'vertical'. */ horizontalPosition: number; /** Column index for vertical split line. Used when direction is 'vertical' or 'both'. Defaults to 0 (ignored) when direction is 'horizontal'. */ verticalPosition: number; } ``` ## StockSubType Stock chart sub-types (OHLC = Open-High-Low-Close) ```typescript type StockSubType = 'hlc' | 'ohlc' | 'volume-hlc' | 'volume-ohlc' ``` ## StripePattern ```typescript type StripePattern = { stripeSize: number; stripe1Fill?: string; stripe2Fill?: string; } ``` ## StrokeId Unique identifier for a stroke within a drawing. Branded type provides type safety - prevents accidentally using string IDs where StrokeId is expected (and vice versa). Uses UUID v7 (time-sortable) for: - Uniqueness across clients (no coordination needed) - Time-sortability for undo/redo ordering - Compact string representation ```typescript type StrokeId = string & { readonly __brand: 'StrokeId' } ``` ## StrokeTransformParams Transform parameters for stroke transformations. ```typescript type StrokeTransformParams = { /** Transform type */ type: StrokeTransformType; /** Center point X for rotation/scale */ centerX?: number; /** Center point Y for rotation/scale */ centerY?: number; /** Rotation angle in radians (for 'rotate') */ angle?: number; /** Scale factor X (for 'scale') */ scaleX?: number; /** Scale factor Y (for 'scale') */ scaleY?: number; } ``` ## StrokeTransformType Transform type for stroke transformations. ```typescript type StrokeTransformType = 'rotate' | 'scale' | 'flip-horizontal' | 'flip-vertical' ``` ## StyleCategory Style category for grouping styles in the UI gallery. ```typescript type StyleCategory = | 'good-bad-neutral' // Good, Bad, Neutral | 'data-model' // Calculation, Check Cell, etc. | 'titles-headings' // Title, Heading 1-4 | 'themed' // Accent1-6 variations | 'number-format' // Currency, Percent, Comma | 'custom' ``` ## SubPath A single subpath within a compound path. ```typescript type SubPath = { segments: PathSegment[]; closed: boolean; } ``` ## SubSupNode Sub-Superscript - ```typescript type SubSupNode = { type: 'sSubSup'; /** Align scripts */ alnScr?: boolean; /** Base */ e: MathNode[]; /** Subscript */ sub: MathNode[]; /** Superscript */ sup: MathNode[]; } ``` ## SubscriptNode Subscript - ```typescript type SubscriptNode = { type: 'sSub'; /** Base */ e: MathNode[]; /** Subscript */ sub: MathNode[]; } ``` ## SubtotalConfig Configuration for the subtotal operation. ```typescript type SubtotalConfig = { /** Target range to subtotal */ range: CellRange; /** Whether the target range includes a header row */ hasHeaders: boolean; /** Column index to group by (0-based) */ groupByColumn: number; /** Columns to subtotal (0-based indices) */ subtotalColumns: number[]; /** Aggregation function to use */ aggregation: 'sum' | 'count' | 'average' | 'max' | 'min'; /** Whether to replace existing subtotals */ replace?: boolean; /** Whether summary rows appear below their detail rows */ summaryBelowData?: boolean; } ``` ## SubtotalLocation ```typescript type SubtotalLocation = 'top' | 'bottom' ``` ## SubtotalResult Result of creating subtotals. ```typescript type SubtotalResult = { /** Number of row groups created */ groupsCreated: number; /** Number of subtotal rows inserted */ subtotalRowsInserted: number; /** Range affected by the subtotal operation */ affectedRange: CellRange; } ``` ## SummaryOptions Options for the `worksheet.summarize()` method. ```typescript type SummaryOptions = { /** Whether to include sample data in the summary */ includeData?: boolean; /** Maximum number of rows to include in sample data */ maxRows?: number; /** Maximum number of columns to include in sample data */ maxCols?: number; } ``` ## SunburstConfig Sunburst chart configuration ```typescript type SunburstConfig = { /** Number of hierarchy levels to display */ levels?: number; /** Show category labels on each arc */ showLabels?: boolean; /** Color scale for sunburst arcs */ colorScale?: string[]; /** Inner radius as fraction of outer radius (0-1) */ innerRadius?: number; } ``` ## SuperscriptNode Superscript - ```typescript type SuperscriptNode = { type: 'sSup'; /** Base */ e: MathNode[]; /** Superscript */ sup: MathNode[]; } ``` ## TableAddColumnReceipt Receipt for a table addColumn mutation. ```typescript type TableAddColumnReceipt = { kind: 'tableAddColumn'; tableName: string; columnName: string; position: number; } ``` ## TableAddRowReceipt Receipt for a table addRow mutation. ```typescript type TableAddRowReceipt = { kind: 'tableAddRow'; tableName: string; index: number; } ``` ## TableColumn A single column in a table. Field names match the Rust-generated `TableColumn` type (compute-types.gen.ts). ```typescript type TableColumn = { /** Unique column ID */ id: string; /** Column header name */ name: string; /** Column index within the table (0-based) */ index: number; /** Total row function type */ totalsFunction: TotalsFunction | null; /** Total row label */ totalsLabel: string | null; /** Calculated column formula */ calculatedFormula?: string; } ``` ## TableDeleteRowReceipt Receipt for a table deleteRow mutation. ```typescript type TableDeleteRowReceipt = { kind: 'tableDeleteRow'; tableName: string; index: number; } ``` ## TableElementStyle ```typescript type TableElementStyle = { fill?: string; fontColor?: string; fontBold?: boolean; borderTop?: string; borderBottom?: string; borderLeft?: string; borderRight?: string; } ``` ## TableInfo Information about an existing table. Field names match the Rust-generated `Table` type (compute-types.gen.ts) except `range` which is converted from `SheetRange` to A1 notation string. ```typescript type TableInfo = { /** Internal table identifier */ id: string; /** Table name */ name: string; /** Display name */ displayName: string; /** Sheet the table belongs to */ sheetId: string; /** Table range in A1 notation (converted from Rust SheetRange) */ range: string; /** Column definitions */ columns: TableColumn[]; /** Whether the table has a header row */ hasHeaderRow: boolean; /** Whether the totals row is visible */ hasTotalsRow: boolean; /** Table style name */ style: string; /** Whether banded rows are shown */ bandedRows: boolean; /** Whether banded columns are shown */ bandedColumns: boolean; /** Whether first column is emphasized */ emphasizeFirstColumn: boolean; /** Whether last column is emphasized */ emphasizeLastColumn: boolean; /** Whether filter buttons are shown */ showFilterButtons: boolean; /** Whether the table automatically expands when adjacent user input is entered */ autoExpand: boolean; /** Whether formulas entered in table data columns automatically create/fill calculated columns */ autoCalculatedColumns: boolean; } ``` ## TableOptions Options for creating a new table. ```typescript type TableOptions = { /** Table name (auto-generated if omitted) */ name?: string; /** Whether the first row of the range contains headers (default: true) */ hasHeaders?: boolean; /** Table style preset name */ style?: string; /** Whether the table automatically expands when adjacent user input is entered (default: true) */ autoExpand?: boolean; /** Whether formulas entered in table data columns automatically create/fill calculated columns (default: true) */ autoCalculatedColumns?: boolean; } ``` ## TableRemoveColumnReceipt Receipt for a table removeColumn mutation. ```typescript type TableRemoveColumnReceipt = { kind: 'tableRemoveColumn'; tableName: string; columnIndex: number; } ``` ## TableResizeReceipt Receipt for a table resize mutation. ```typescript type TableResizeReceipt = { kind: 'tableResize'; tableName: string; newRange: string; } ``` ## TableRowCollection A collection-like wrapper around a table's data rows. Returned by `WorksheetTables.getRows()`. The `count` property is a snapshot taken at construction time and does NOT live-update. ```typescript type TableRowCollection = { /** Number of data rows (snapshot, not live). */ count: number; /** Get the cell values of a data row by index. */ getAt(index: number): Promise;; /** Add a data row. If index is omitted, appends to the end. */ add(index?: number, values?: CellValue[]): Promise;; /** Delete a data row by index. */ deleteAt(index: number): Promise;; /** Get the cell values of a data row by index. */ getValues(index: number): Promise;; /** Set the cell values of a data row by index. */ setValues(index: number, values: CellValue[]): Promise;; /** Get the A1-notation range for a data row by index. */ getRange(index: number): Promise;; } ``` ## TableStyleConfig Configuration for creating/updating a custom table style. ```typescript type TableStyleConfig = { /** Optional legacy style name. `WorkbookTableStyles.add(name, style)` owns the canonical name through its first argument. */ name?: string; headerRow?: TableElementStyle; totalRow?: TableElementStyle; firstColumn?: TableElementStyle; lastColumn?: TableElementStyle; rowStripes?: StripePattern; columnStripes?: StripePattern; wholeTable?: TableElementStyle; } ``` ## TableStyleInfo ```typescript type TableStyleInfo = { id: string; name: string; createdAt: number; updatedAt: number; headerRow: TableElementStyle; totalRow: TableElementStyle; firstColumn: TableElementStyle; lastColumn: TableElementStyle; rowStripes: StripePattern; columnStripes: StripePattern; wholeTable: TableElementStyle; } ``` ## TableStyleInfoWithReadOnly A table style with a computed `readOnly` flag (built-in styles are read-only). ```typescript type TableStyleInfoWithReadOnly = TableStyleInfo & { readOnly: boolean } ``` ## TableUpdateOptions Options for updating a table's properties via `WorksheetTables.update()`. ```typescript type TableUpdateOptions = { /** Table style preset name (e.g. "TableStyleLight1"). */ style?: string; /** New table name (renames the table). */ name?: string; /** Whether the first column is emphasized. */ emphasizeFirstColumn?: boolean; /** Whether the last column is emphasized. */ emphasizeLastColumn?: boolean; /** Whether banded columns are shown. */ bandedColumns?: boolean; /** Whether banded rows are shown. */ bandedRows?: boolean; /** Whether filter buttons are shown on the header row. */ showFilterButtons?: boolean; /** Whether the header row is visible. */ hasHeaderRow?: boolean; /** Whether the totals row is visible. */ hasTotalsRow?: boolean; /** Whether the table automatically expands when adjacent user input is entered. */ autoExpand?: boolean; /** Whether formulas entered in table data columns automatically create/fill calculated columns. */ autoCalculatedColumns?: boolean; } ``` ## TagMatcher Glob-matchable tag pattern for matching against principal tags. Examples: - `"agent:copilot"` — exact match - `"agent:*"` — all agents - `"sf:role:*"` — all Salesforce roles - `"*"` — everyone ```typescript type TagMatcher = string ``` ## TargetMatcher Target matcher — same structure as AccessTarget but allows `'*'` wildcards for IDs to match any resource of that kind. ```typescript type TargetMatcher = | { readonly kind: 'workbook' } | { readonly kind: 'sheet'; readonly sheetId: SheetId | '*' } | { readonly kind: 'column'; readonly colId: ColId | '*'; readonly sheetId: SheetId | '*' } ``` ## TextAutoSize How text auto-sizes within its container. ```typescript type TextAutoSize = | { type: 'none' } | { type: 'textToFitShape'; fontScale?: number; lineSpacingReduction?: number } | { type: 'shapeToFitText' } ``` ## TextBoxBorder Text box border with optional corner radius. ```typescript type TextBoxBorder = { /** Corner radius in pixels (for rounded corners) */ radius?: number; } ``` ## TextBoxConfig Configuration for creating a new text box. ```typescript type TextBoxConfig = { /** Text content and formatting — shared model with ShapeData. */ text?: ShapeText; /** Anchor cell as `{row, col}`. When set, `x`/`y` are offsets from this cell instead of from cell `(0, 0)`. */ anchorCell?: { row: number; col: number }; /** X position in pixels. */ x?: number; /** Y position in pixels. */ y?: number; /** Width in pixels (default: 200). */ width?: number; /** Height in pixels (default: 100). */ height?: number; /** Display name. */ name?: string; } ``` ## TextBoxHandle ```typescript type TextBoxHandle = { update(props: Partial): Promise;; duplicate(offsetX?: number, offsetY?: number): Promise;; getData(): Promise;; } ``` ## TextBoxObject Text box floating object. A rectangular container for rich text content. ```typescript type TextBoxObject = { type: 'textbox'; /** Text content and formatting — shared model with ShapeData. */ text?: ShapeText; /** Fill color/gradient for the text box background */ fill?: ObjectFill; /** Border around the text box */ border?: TextBoxBorder; /** Optional text-effect configuration for styled text effects */ wordArt?: WordArtConfig; } ``` ## TextEffects Container for all text effects. Groups all visual effects that can be applied to text-effect text. Effects are applied in a specific order to ensure correct visual stacking: **Effect Application Order:** 1. Text fill and outline (base rendering) 2. Outer shadow (rendered behind text) 3. Glow (rendered around text edges) 4. Inner shadow (rendered inside text) 5. Soft edges (feathers text edges) 6. Reflection (rendered below text) 7. 3D bevel (adds depth to edges) 8. 3D rotation and perspective (transforms entire result) Note: You can use either `presetShadow` for quick shadow application, or `outerShadow`/`innerShadow` for custom shadow configuration. Using both may produce unexpected results. @example // Dramatic text effects const effects: TextEffects = { outerShadow: { blurRadius: 50800, distance: 38100, direction: 45, color: '#000000', opacity: 0.4 }, glow: { radius: 63500, color: '#FFD700', opacity: 0.6 }, bevel: { topPreset: 'circle', topWidth: 38100, topHeight: 38100 } }; @see ECMA-376 Part 1, Section 20.1.8 (DrawingML - Effect) ```typescript type TextEffects = { /** Outer shadow effect. Creates a shadow behind and offset from the text. For quick shadow setup, consider using `presetShadow` instead. */ outerShadow?: OuterShadowEffect; /** Inner shadow effect. Creates a shadow inside the text edges for an embossed look. */ innerShadow?: InnerShadowEffect; /** Preset shadow (alternative to custom shadow). Use this for quick application of standard shadow styles. Choose from 20 predefined shadow configurations (shdw1-shdw20). If both `presetShadow` and `outerShadow`/`innerShadow` are specified, the custom shadow settings take precedence. */ presetShadow?: PresetShadowType; /** Glow effect. Creates a soft colored glow around the text. */ glow?: GlowEffect; /** Soft edge effect. Creates feathered/faded edges on the text. */ softEdge?: SoftEdgeEffect; /** Reflection effect. Creates a mirror reflection below the text. */ reflection?: ReflectionEffect; /** Bevel effect. Creates 3D beveled edges on the text. Can apply different bevels to top and bottom edges. */ bevel?: BevelEffect; /** 3D rotation effect. Rotates text in 3D space and applies perspective. Includes lighting and material settings for realistic 3D rendering. */ transform3D?: Transform3DEffect; } ``` ## TextMargins Text margins within a text box or shape. ```typescript type TextMargins = { /** Top margin in pixels */ top: number; /** Right margin in pixels */ right: number; /** Bottom margin in pixels */ bottom: number; /** Left margin in pixels */ left: number; } ``` ## TextOrientation Text orientation within a shape. ```typescript type TextOrientation = | 'horizontal' | 'vertical' | 'vertical270' | 'wordArtVertical' | 'eastAsianVertical' | 'mongolianVertical' ``` ## TextOverflow Text overflow behavior. ```typescript type TextOverflow = 'overflow' | 'clip' | 'ellipsis' ``` ## TextReadingOrder Text reading order / directionality. ```typescript type TextReadingOrder = 'leftToRight' | 'rightToLeft' ``` ## TextRun A single text run within a paragraph. Corresponds to the `a:r` element. Contains text content and run-level formatting properties. @see ECMA-376 Part 1, Section 21.1.2.3.8 (a:r) ```typescript type TextRun = { /** The actual text content of this run. */ text: string; /** Run-level formatting properties. */ properties?: TextRunProperties; } ``` ## TextRunProperties Text run properties (a:rPr). Controls character-level formatting such as font, size, color, bold, italic, underline, etc. @see ECMA-376 Part 1, Section 21.1.2.3.9 (a:rPr) ```typescript type TextRunProperties = { /** Bold text. */ bold?: boolean; /** Italic text. */ italic?: boolean; /** Underline style. */ underline?: TextUnderlineType; /** Strikethrough style. */ strikethrough?: 'noStrike' | 'sngStrike' | 'dblStrike'; /** Font family name (Latin script). */ fontFamily?: string; /** East Asian font family name. */ fontFamilyEastAsian?: string; /** Complex script font family name. */ fontFamilyComplexScript?: string; /** Font size in hundredths of a point. For example, 1200 = 12pt. */ fontSize?: number; /** Text color. */ color?: DmlColorValue; /** Character spacing (tracking) in hundredths of a point. */ spacing?: number; /** Baseline shift as a percentage (positive = superscript, negative = subscript). */ baseline?: number; /** Whether text is capitalized. */ cap?: 'none' | 'small' | 'all'; /** Text language (BCP 47 language tag, e.g., "en-US"). */ lang?: string; /** Whether the run is a hyperlink. */ hyperlink?: HyperlinkInfo; } ``` ## TextStyle Text styling properties for node labels. ```typescript type TextStyle = { /** Font family name */ fontFamily: string; /** Font size in points */ fontSize: number; /** Font weight */ fontWeight: 'normal' | 'bold'; /** Font style */ fontStyle: 'normal' | 'italic'; /** Text color (CSS color string) */ color: string; /** Horizontal text alignment */ align: 'left' | 'center' | 'right'; /** Vertical text alignment */ verticalAlign: 'top' | 'middle' | 'bottom'; } ``` ## TextToColumnsDelimiters Delimiter set for text-to-columns splitting. Multiple delimiters may be enabled. ```typescript type TextToColumnsDelimiters = { /** Split on tab characters. */ tab?: boolean; /** Split on semicolons. */ semicolon?: boolean; /** Split on commas. */ comma?: boolean; /** Split on spaces. */ space?: boolean; /** Split on this custom delimiter character/string. */ other?: string; } ``` ## TextToColumnsDestination Destination cell for text-to-columns output. ```typescript type TextToColumnsDestination = { /** Zero-based row index. */ row: number; /** Zero-based column index. */ col: number; } ``` ## TextToColumnsOptions Options for text-to-columns splitting. ```typescript type TextToColumnsOptions = { /** Split mode. Defaults to 'delimited' when omitted. */ type?: 'delimited' | 'fixedWidth'; /** Legacy single delimiter selector. Defaults to 'comma' when `delimiters` is omitted. Use `delimiters` when more than one delimiter is selected. */ delimiter?: 'comma' | 'tab' | 'semicolon' | 'space' | 'custom'; /** Custom delimiter character (when delimiter is 'custom') */ customDelimiter?: string; /** Full delimiter set. Takes precedence over `delimiter` when provided. */ delimiters?: TextToColumnsDelimiters; /** Destination cell. Defaults to the top-left source cell. */ destination?: string | TextToColumnsDestination; /** Whether to treat consecutive delimiters as one */ treatConsecutiveAsOne?: boolean; /** Text qualifier character */ textQualifier?: '"' | "'" | 'none'; /** Zero-based character offsets at which to split (fixedWidth mode). */ fixedWidthBreaks?: number[]; } ``` ## TextToColumnsResult Result of a text-to-columns operation. ```typescript type TextToColumnsResult = { /** Number of source rows processed. */ rowsProcessed: number; /** Maximum number of destination columns produced by any processed row. */ columnsCreated: number; } ``` ## TextWarpPreset Text-Effect Types Implements DrawingML text warp and effects from ECMA-376 Part 1. Decorative text is NOT a separate floating object type - it's a configuration that can be applied to TextBoxObject to add warping and effects. @see ECMA-376 Part 1, Section 20.1.10 (Text Body Properties) @see ECMA-376 Part 1, Section 20.1.10.78 (ST_TextShapeType) ```typescript type TextWarpPreset = | 'textNoShape' // OOXML compatibility - no shape transformation | 'textPlain' // Plain text with no transformation // Arc paths (text follows curved arc) | 'textArchUp' | 'textArchDown' | 'textCircle' | 'textButton' // Arc paths with fill (poured effect) | 'textArchUpPour' | 'textArchDownPour' | 'textCirclePour' | 'textButtonPour' // Curve effects (upward/downward Bezier curves) | 'textCurveUp' | 'textCurveDown' // Wave effects (sinusoidal distortion) | 'textWave1' | 'textWave2' | 'textDoubleWave1' | 'textWave4' // Inflate/deflate effects (bulge/pinch) | 'textInflate' | 'textDeflate' | 'textInflateBottom' | 'textDeflateBottom' | 'textInflateTop' | 'textDeflateTop' | 'textDeflateInflate' | 'textDeflateInflateDeflate' // Fade effects (perspective scaling) | 'textFadeRight' | 'textFadeLeft' | 'textFadeUp' | 'textFadeDown' // Slant effects (shear transformation) | 'textSlantUp' | 'textSlantDown' // Cascade effects (stair-step) | 'textCascadeUp' | 'textCascadeDown' // Additional geometric warps | 'textTriangle' | 'textTriangleInverted' | 'textChevron' | 'textChevronInverted' | 'textRingInside' | 'textRingOutside' | 'textStop' | 'textCanUp' | 'textCanDown' ``` ## ThemeColorSlot All valid theme color slot names ```typescript type ThemeColorSlot = keyof ThemeColors ``` ## ThemeColors Theme Contracts Type definitions and utilities for workbook themes. Themes define color palettes and font pairs that cells can reference. Issue 4: Page Layout - Themes ```typescript type ThemeColors = { /** Primary dark color - typically black/near-black for text */ dark1: string; /** Primary light color - typically white for backgrounds */ light1: string; /** Secondary dark color */ dark2: string; /** Secondary light color */ light2: string; /** Accent color 1 - primary accent (blue in Office default) */ accent1: string; /** Accent color 2 - typically orange */ accent2: string; /** Accent color 3 - typically gray */ accent3: string; /** Accent color 4 - typically yellow/gold */ accent4: string; /** Accent color 5 - typically blue-gray */ accent5: string; /** Accent color 6 - typically green */ accent6: string; /** Hyperlink color */ hyperlink: string; /** Followed hyperlink color */ followedHyperlink: string; } ``` ## ThemeDefinition Complete theme definition including colors and fonts. ```typescript type ThemeDefinition = { /** Unique theme identifier (e.g., 'office', 'slice', 'custom-abc123') */ id: string; /** Display name shown in UI (e.g., 'Office', 'Slice') */ name: string; /** Theme color palette */ colors: ThemeColors; /** Theme font pair */ fonts: ThemeFonts; /** True for built-in themes, false for user-created */ builtIn: boolean; } ``` ## ThemeFonts Theme font pair - major (headings) and minor (body) fonts. ```typescript type ThemeFonts = { /** Font for headings (e.g., 'Calibri Light') */ majorFont: string; /** Font for body text (e.g., 'Calibri') */ minorFont: string; } ``` ## TileSettings Tile settings for picture/texture fills. ```typescript type TileSettings = { tx?: number; ty?: number; sx?: number; sy?: number; flip?: string; algn?: string; } ``` ## TimelineLevel Timeline aggregation level. Determines how dates are grouped in the timeline display. ```typescript type TimelineLevel = 'years' | 'quarters' | 'months' | 'days' ``` ## TimelinePeriod A period in a timeline slicer. ```typescript type TimelinePeriod = { /** Period label */ label: string; /** Period start date (ISO string) */ start: string; /** Period end date (ISO string) */ end: string; /** Whether this period is selected */ selected: boolean; } ``` ## TimelineSlicerConfig Timeline slicer specific configuration. Extends base slicer for date-range filtering. ```typescript type TimelineSlicerConfig = { /** Source must be table or pivot with date column */ sourceType: 'timeline'; /** Current aggregation level */ timelineLevel: TimelineLevel; /** Start date of the data range */ dataStartDate?: number; /** End date of the data range */ dataEndDate?: number; /** Currently selected date range start */ selectedStartDate?: number; /** Currently selected date range end */ selectedEndDate?: number; /** Show the level selector in the header */ showLevelSelector: boolean; /** Show the date range label */ showDateRangeLabel: boolean; } ``` ## TimelineStyleInfo ```typescript type TimelineStyleInfo = { name: string; isDefault: boolean; } ``` ## TitleConfig Rich title configuration ```typescript type TitleConfig = { text?: string; visible?: boolean; position?: 'top' | 'bottom' | 'left' | 'right' | 'overlay'; font?: ChartFont; format?: ChartFormat; overlay?: boolean; /** Text orientation angle in degrees (-90 to 90) */ textOrientation?: number; richText?: ChartFormatString[]; formula?: string; /** Horizontal text alignment. */ horizontalAlignment?: 'left' | 'center' | 'right'; /** Vertical text alignment. */ verticalAlignment?: 'top' | 'middle' | 'bottom'; /** Show drop shadow on title. */ showShadow?: boolean; /** Height in points (read-only, populated from render engine). */ height?: number; /** Width in points (read-only, populated from render engine). */ width?: number; /** Left position in points (read-only, populated from render engine). */ left?: number; /** Top position in points (read-only, populated from render engine). */ top?: number; } ``` ## TopBottomBy ```typescript type TopBottomBy = 'items' | 'percent' | 'sum' ``` ## TopBottomType ```typescript type TopBottomType = 'top' | 'bottom' ``` ## TotalsFunction Totals function type (matches Rust TotalsFunction). ```typescript type TotalsFunction = | 'average' | 'count' | 'countNums' | 'max' | 'min' | 'stdDev' | 'sum' | 'var' | 'custom' | 'none' ``` ## Transform3DEffect 3D transformation effect configuration. ```typescript type Transform3DEffect = { /** Rotation around X axis in degrees */ rotationX: number; /** Rotation around Y axis in degrees */ rotationY: number; /** Rotation around Z axis in degrees */ rotationZ: number; /** Perspective distance for 3D effect */ perspective: number; } ``` ## TreemapConfig Treemap chart configuration ```typescript type TreemapConfig = { /** Number of hierarchy levels to display */ levels?: number; /** Show category labels on each rectangle */ showLabels?: boolean; /** Color scale for treemap rectangles */ colorScale?: string[]; /** Layout algorithm */ layoutAlgorithm?: 'squarified' | 'slice' | 'dice' | 'sliceDice'; } ``` ## TrendlineConfig Trendline configuration (matches TrendlineData wire type) ```typescript type TrendlineConfig = { show?: boolean; type?: string; color?: string; lineWidth?: number; order?: number; period?: number; forward?: number; backward?: number; intercept?: number; displayEquation?: boolean; displayRSquared?: boolean; name?: string; lineFormat?: ChartLineFormat; label?: TrendlineLabelConfig; /** @deprecated Use displayEquation instead */ showEquation?: boolean; /** @deprecated Use displayRSquared instead */ showR2?: boolean; /** @deprecated Use forward instead */ forwardPeriod?: number; /** @deprecated Use backward instead */ backwardPeriod?: number; } ``` ## TrendlineLabelConfig Trendline label configuration. ```typescript type TrendlineLabelConfig = { text?: string; format?: ChartFormat; numberFormat?: string; } ``` ## UndoHistoryEntry An entry in the undo history. ```typescript type UndoHistoryEntry = { /** Unique identifier for this entry. */ id: string; /** Description of the operation. */ description: string; /** Timestamp of the operation (Unix ms). */ timestamp: number; } ``` ## UndoReceipt Receipt for an undo operation. ```typescript type UndoReceipt = { kind: 'undo'; success: boolean; } ``` ## UndoServiceState Undo service state ```typescript type UndoServiceState = { /** Whether undo is available */ canUndo: boolean; /** Whether redo is available */ canRedo: boolean; /** Number of items in undo stack */ undoStackSize: number; /** Number of items in redo stack */ redoStackSize: number; /** Description of next undo operation */ nextUndoDescription: string | null; /** Description of next redo operation */ nextRedoDescription: string | null; } ``` ## UndoState Full undo/redo state from the compute engine. ```typescript type UndoState = { /** Whether undo is available. */ canUndo: boolean; /** Whether redo is available. */ canRedo: boolean; /** Number of operations that can be undone. */ undoDepth: number; /** Number of operations that can be redone. */ redoDepth: number; /** Description of the next undo operation, if set. */ nextUndoDescription: string | null; /** Description of the next redo operation, if set. */ nextRedoDescription: string | null; } ``` ## UndoStateChangeEvent Undo state change event ```typescript type UndoStateChangeEvent = { /** Current state */ state: UndoServiceState; /** What triggered this change */ trigger: 'undo' | 'redo' | 'push' | 'clear' | 'external'; } ``` ## UnmergeReceipt Receipt for an unmerge mutation. ```typescript type UnmergeReceipt = { kind: 'unmerge'; range: string; } ``` ## UpdateWorkbookLinkInput ```typescript type UpdateWorkbookLinkInput = { expectedWorkbookId?: WorkbookId | null; target?: PersistedLinkTarget; displayName?: string; sourceKind?: WorkbookLinkSourceKind; importedExcelIdentity?: ImportedExternalLinkIdentity; materializedCacheMetadata?: AuthorizedMaterializedCacheMetadata; } ``` ## ValidationCheckResult Result of validating a single cell value against the rules covering it. Uses the public `errorStyle` vocabulary ("stop" | "warning" | "information") rather than the internal `enforcement` vocabulary. "none" indicates that no validation rule covers the cell (the value is trivially valid). ```typescript type ValidationCheckResult = { /** Whether the value satisfies the covering rule. */ valid: boolean; /** Error message (only meaningful when `valid` is false). */ errorMessage?: string; /** Error title for dialog display (only meaningful when `valid` is false). */ errorTitle?: string; /** Error style from the covering rule. "none" means no rule covers the cell, in which case the result is trivially valid. */ errorStyle: 'stop' | 'warning' | 'information' | 'none'; } ``` ## ValidationRule A data validation rule for cells. ```typescript type ValidationRule = { /** Schema ID — populated when reading, optional when creating (auto-generated if omitted) */ id?: string; /** The cell range this rule applies to in A1 notation (e.g., "A1:B5") — populated when reading */ range?: string; /** The validation type. 'none' indicates no validation rule is set. */ type: 'none' | 'list' | 'wholeNumber' | 'decimal' | 'date' | 'time' | 'textLength' | 'custom'; /** Comparison operator */ operator?: | 'equal' | 'notEqual' | 'greaterThan' | 'lessThan' | 'greaterThanOrEqual' | 'lessThanOrEqual' | 'between' | 'notBetween'; /** Primary constraint value or formula */ formula1?: string | number; /** Secondary constraint value or formula (for 'between' / 'notBetween') */ formula2?: string | number; /** Explicit list of allowed values (for 'list' type) */ values?: string[]; /** Source reference for list validation: A1 range (e.g., "=Sheet1!A1:A10") or formula (e.g., "=INDIRECT(A1)"). Prefixed with "=" for formulas. */ listSource?: string; /** Whether blank cells pass validation (default: true) */ allowBlank?: boolean; /** Whether to show a dropdown arrow for list validations */ showDropdown?: boolean; /** Whether to show an input message when the cell is selected */ showInputMessage?: boolean; /** Title for the input message */ inputTitle?: string; /** Body text for the input message */ inputMessage?: string; /** Whether to show an error alert on invalid input */ showErrorAlert?: boolean; /** Error alert style */ errorStyle?: 'stop' | 'warning' | 'information'; /** Title for the error alert */ errorTitle?: string; /** Body text for the error alert */ errorMessage?: string; } ``` ## ValidationSetReceipt Receipt for setting a validation rule. ```typescript type ValidationSetReceipt = { kind: 'validationSet'; address: string; } ``` ## ViewOptions Sheet view options (gridlines, headings). ```typescript type ViewOptions = { /** Whether gridlines are shown */ showGridlines: boolean; /** Whether row headers are shown */ showRowHeaders: boolean; /** Whether column headers are shown */ showColumnHeaders: boolean; } ``` ## ViewportBounds ```typescript type ViewportBounds = { startRow: number; startCol: number; endRow: number; endCol: number; } ``` ## ViewportChangeEvent Events emitted by the viewport coordinator when viewport state changes. Consumers subscribe to these events to react to data changes without polling. ```typescript type ViewportChangeEvent = | { type: 'fetch-committed' } | { type: 'cells-patched'; cells: { row: number; col: number }[] } | { type: 'dimensions-patched'; axis: 'row' | 'col' } ``` ## ViewportRegion Handle for a registered viewport region. Created by `wb.viewport.createRegion()`. The kernel tracks cell data for this region and delivers incremental updates. Dispose when the region is no longer needed (e.g., component unmount, sheet switch). Supports TC39 Explicit Resource Management: using region = wb.viewport.createRegion(sheetId, bounds); ```typescript type ViewportRegion = { /** Unique ID for this region (auto-generated). */ id: string; /** Sheet this region is tracking. */ sheetId: string; /** Update the locally-tracked visible bounds (e.g., on scroll or resize). **Important:** This updates local state only. It does NOT push bounds to the Rust compute engine. Rust-side viewport bounds (the prefetch range) are exclusively managed by the fetch manager via {@link refresh}. Pushing visible bounds here would overwrite the wider prefetch range on every scroll, causing off-screen mutations to be silently dropped. @see plans/completed/plans/fix-offscreen-mutation-display.md — Phase 5 */ updateBounds(bounds: ViewportBounds): void;; /** Request a data refresh for this region. */ refresh(scrollBehavior?: unknown): Promise;; } ``` ## ViolinConfig Violin plot configuration ```typescript type ViolinConfig = { showBox?: boolean; bandwidth?: number; side?: 'both' | 'left' | 'right'; } ``` ## VisibleRangeView The result of `getVisibleView()` — only visible (non-hidden) rows from a range. Matches the visible range-view concept: a filtered view of a range that excludes hidden rows (e.g., rows hidden by AutoFilter). ```typescript type VisibleRangeView = { /** Cell values for visible rows only (2D array, same column count as input range). */ values: CellValue[][]; /** The 0-based row indices (absolute, within the sheet) of the visible rows. */ visibleRowIndices: number[]; } ``` ## WaterfallConfig Waterfall chart configuration for special bars ```typescript type WaterfallConfig = { /** Indices that are "total" bars (drawn from zero) */ totalIndices?: number[]; /** Color for positive values */ increaseColor?: string; /** Color for negative values */ decreaseColor?: string; /** Color for total bars */ totalColor?: string; } ``` ## WordArtConfig text-effect configuration for a TextBoxObject. When applied to a TextBoxObject, this config transforms regular text into stylized text effects with warping, fills, and effects. This is the main configuration type for text effects - it contains all the settings needed to render text with decorative styling. @see ECMA-376 Part 1, Section 21.1.2.2.33 (txBody - Text Body) @example // Basic text effects with arch warp const config: WordArtConfig = { warpPreset: 'textArchUp', warpAdjustments: { adj1: 50 }, fill: { type: 'gradient', gradientType: 'linear', angle: 90, stops: [...] }, outline: { width: 1.5, color: '#000000' } }; @example // text effects with effects const config: WordArtConfig = { warpPreset: 'textWave1', fill: { type: 'solid', color: '#FF6600' }, effects: { outerShadow: { blurRadius: 40000, distance: 25000, direction: 45, color: '#000000', opacity: 0.35 } } }; ```typescript type WordArtConfig = { /** Text warp preset type. Determines the geometric transformation applied to the text. */ warpPreset: TextWarpPreset; /** Fine-tune warp parameters. Values depend on the preset type. */ warpAdjustments?: AdjustmentValues; /** Text fill (solid, gradient, pattern, or none). Defines how the interior of text characters is colored. */ fill: WordArtFill; /** Text outline/stroke. Defines the border around text characters. */ outline?: WordArtOutline; /** Text effects (shadow, glow, reflection, bevel, 3D). Adds visual effects to the text. */ effects?: TextEffects; /** Whether text follows the warp path exactly (true) or flows naturally (false). - `true` (default): Each glyph is positioned and rotated to follow the warp path tangent. Used for arc, circle, and path-following effects where text should curve with the path. The rotation of each character matches the path direction. - `false`: Text maintains its baseline orientation while the overall shape is warped. Used for inflate/deflate effects where text distorts but doesn't rotate. Characters remain upright even as they are scaled/positioned along the path. */ followPath?: boolean; /** Text anchoring within the warp bounds. Controls where text is positioned within the warped area. */ anchor?: 'top' | 'middle' | 'bottom'; /** Text direction. Affects how text flows within the warp. */ textDirection?: 'ltr' | 'rtl'; /** Normalize letter heights across different characters. When true, all characters are scaled to have the same height. */ normalizeHeights?: boolean; } ``` ## WordArtConfigUpdate Typed patch for updating an existing text-effect configuration. ```typescript type WordArtConfigUpdate = Partial< Omit > & { /** Warp adjustment values. Explicit undefined removes stored adjustments. */ warpAdjustments?: AdjustmentValues | undefined; /** Text outline configuration. Explicit undefined removes the outline. */ outline?: WordArtOutline | undefined; /** Text effects. Explicit undefined removes stored effects. */ effects?: TextEffects | undefined; } ``` ## WordArtDefaults Fully normalized text effects defaults used by Worksheet text effects creation. ```typescript type WordArtDefaults = { /** Fully populated default visual text-effect configuration. */ config: WordArtObjectConfig; /** Default text-effect object width in pixels. */ width: number; /** Default text-effect object height in pixels. */ height: number; } ``` ## WordArtFill Union type for all fill types. Used for text-effect text fill configuration. ```typescript type WordArtFill = SolidFill | GradientFill | PatternFill | NoFill ``` ## WordArtHandle Decorative text-effect objects are text boxes with text-effect configuration. ```typescript type WordArtHandle = { update(props: WordArtUpdates): Promise;; duplicate(offsetX?: number, offsetY?: number): Promise;; getData(): Promise;; } ``` ## WordArtObjectConfig Persisted visual text-effect configuration stored on a TextBoxObject. ```typescript type WordArtObjectConfig = DomainWordArtConfig ``` ## WordArtOutline text-effect text outline configuration. Defines the stroke/border around text characters. @see ECMA-376 Part 1, Section 20.1.8.38 (CT_LineProperties) ```typescript type WordArtOutline = { /** Outline width in points (1pt = 1/72 inch). Typical values range from 0.5 to 6 points. */ width: number; /** Outline color (CSS color string: hex, rgb, rgba, hsl, named) */ color: string; /** Opacity (0-1, where 0 is fully transparent, 1 is fully opaque) */ opacity?: number; /** Dash style (default: 'solid') */ dash?: LineDash; /** Line cap style (default: 'flat') */ cap?: LineCap; /** Line join style (default: 'round') */ join?: LineJoin; /** Miter limit for miter joins. When the miter length exceeds this ratio of the line width, the join is rendered as a bevel instead. */ miterLimit?: number; /** Compound line type for multi-stroke outlines */ compound?: CompoundLine; } ``` ## WordArtTextFormatUpdate Text-format fields accepted by text-effect text formatting updates. ```typescript type WordArtTextFormatUpdate = Partial> ``` ## WordArtUpdates Updates for existing text effects. ```typescript type WordArtUpdates = { /** Updated text content. */ text?: string; /** Warp preset name (text geometric transformation). */ warp?: TextWarpPreset; /** Warp adjustment values. */ warpAdjustments?: AdjustmentValues; /** Fill configuration. */ fill?: WordArtFill; /** Outline configuration. Explicit undefined removes the outline. */ outline?: WordArtOutline | undefined; /** Text effects (shadow, glow, reflection, etc.). */ effects?: TextEffects; /** Full text-effect configuration batch update. */ config?: WordArtConfigUpdate; /** Text formatting update. */ textFormat?: WordArtTextFormatUpdate; } ``` ## WorkbookChangeRecord A single cell-level change observed by a workbook tracker. Includes sheet name. ```typescript type WorkbookChangeRecord = { /** Sheet name where the change occurred. */ sheet: string; /** Cell address in A1 notation (e.g., "B1"). */ address: string; /** 0-based row index. */ row: number; /** 0-based column index. */ col: number; /** What caused this change. */ origin: ChangeOrigin; /** Type of change. */ type: 'modified'; /** Value before the change (undefined if cell was previously empty). */ oldValue?: unknown; /** Value after the change (undefined if cell was cleared). */ newValue?: unknown; } ``` ## WorkbookChangeTracker A handle that accumulates change records across all sheets. ```typescript type WorkbookChangeTracker = { /** Drain accumulated changes since creation or last collect() call. */ collect(): WorkbookCollectResult;; /** Async version of collect() that resolves sheet names across the Rust bridge. Preferred over collect() when called from async context. Falls back to raw sheet IDs if name resolution fails. */ collectAsync(): Promise;; /** Stop tracking and release internal resources. */ close(): void;; /** Whether this tracker is still active (not closed). */ active: boolean; } ``` ## WorkbookCollectResult Result from collecting workbook-level changes. ```typescript type WorkbookCollectResult = { /** Accumulated change records. */ records: WorkbookChangeRecord[]; /** True if the tracker hit its limit and stopped accumulating. */ truncated: boolean; /** Total changes observed (may exceed records.length when truncated). */ totalObserved: number; } ``` ## WorkbookCustomListInput ```typescript type WorkbookCustomListInput = { /** Display name for the user-defined list. */ name: string; /** Ordered values used by fill and custom sort operations. */ values: readonly string[]; } ``` ## WorkbookCustomListUpdate ```typescript type WorkbookCustomListUpdate = { /** Updated display name. Omit to keep the current name. */ name?: string; /** Updated ordered values. Omit to keep the current values. */ values?: readonly string[]; } ``` ## WorkbookId ```typescript type WorkbookId = string ``` ## WorkbookLinkSourceKind ```typescript type WorkbookLinkSourceKind = 'mog-workbook' | 'excel-workbook' | 'dde-link' | 'ole-link' ``` ## WorkbookProtectionOptions Workbook protection options - matches Excel behavior. Workbook protection prevents structural changes to sheets. When a workbook is protected: - Users cannot add, delete, rename, hide, unhide, or move sheets - Sheet content can still be edited (unless sheet is also protected) Plan 08: Dialogs - Task 4 (Protect Workbook Dialog) ```typescript type WorkbookProtectionOptions = { /** Protect workbook structure (prevents sheet add/delete/move/rename/hide/unhide). Default: true when protection is enabled. */ structure: boolean; } ``` ## WorkbookSessionId ```typescript type WorkbookSessionId = string ``` ## WorkbookSettings Workbook-level settings (persisted in Yjs workbook metadata). These apply globally to the entire workbook, not per-sheet. Stream L: Settings & Toggles ```typescript type WorkbookSettings = { /** Whether horizontal scrollbar is visible (default: true) */ showHorizontalScrollbar: boolean; /** Whether vertical scrollbar is visible (default: true) */ showVerticalScrollbar: boolean; /** Whether scrollbars auto-hide when not scrolling (default: false). When true, scrollbars fade out after scroll ends and reappear on hover or scroll. Plan 09 Group 7.2: Auto-Hide Scroll Bars */ autoHideScrollBars: boolean; /** Whether the tab strip is visible (default: true) */ showTabStrip: boolean; /** Whether sheets can be reordered by dragging (default: true) */ allowSheetReorder: boolean; /** Whether the formula bar is visible (default: true) */ showFormulaBar: boolean; /** Whether to auto-fit column width on header double-click (default: true) */ autoFitOnDoubleClick: boolean; /** ID of active theme. Built-in theme IDs: 'office', 'slice', 'vapor-trail', etc. Use 'custom' to indicate a custom theme is stored in customTheme. Issue 4: Page Layout - Themes */ themeId: string; /** Override for theme fonts. When set, uses this font theme instead of the fonts from the selected theme. Built-in font theme IDs: 'office', 'arial', 'times', 'calibri', etc. undefined means use fonts from themeId. Plan 12: Fonts/Typography - Theme Font UI */ themeFontsId?: string; /** Locale/culture for number, date, and currency formatting. Uses IETF language tags: 'en-US', 'de-DE', 'ja-JP', etc. Default: 'en-US' This affects: - Decimal and thousands separators (1,234.56 vs 1.234,56) - Currency symbol position ($100 vs 100 €) - Date format patterns (MM/DD/YYYY vs DD.MM.YYYY) - Month and day name translations - AM/PM designators Stream G: Culture & Localization */ culture: string; /** Whether to show cut/copy indicator (marching ants). Default: true */ showCutCopyIndicator: boolean; /** Whether fill handle dragging is enabled. Default: true */ allowDragFill: boolean; /** Direction to move after pressing Enter. Default: 'down' */ enterKeyDirection: EnterKeyDirection; /** Whether cell drag-and-drop to move cells is enabled. Default: false (not yet implemented) */ allowCellDragDrop: boolean; /** Currently selected sheet IDs for multi-sheet operations. Default: undefined (falls back to [activeSheetId]) This is collaborative state - other users can see which sheets you have selected. Used for operations that broadcast to multiple sheets (formatting, structure changes). When multiple sheets are selected: - Formatting operations apply to all selected sheets - Structure operations (insert/delete rows/cols) apply to all selected sheets - The active sheet is always included in the selection */ selectedSheetIds?: SheetId[]; /** Whether the workbook structure is protected. When true, prevents adding, deleting, renaming, hiding, unhiding, or moving sheets. Default: false Plan 08: Dialogs - Task 4 (Protect Workbook Dialog) */ isWorkbookProtected?: boolean; /** Hashed protection password for workbook (optional). Uses XLSX-compatible XOR hash algorithm for round-trip compatibility. Empty string or undefined means no password protection. */ workbookProtectionPasswordHash?: string; /** Workbook protection options (what operations are prevented). Only relevant when isWorkbookProtected is true. If not set, defaults to DEFAULT_WORKBOOK_PROTECTION_OPTIONS. @see WorkbookProtectionOptions in protection.ts */ workbookProtectionOptions?: import('./document/protection').WorkbookProtectionOptions; /** Calculation settings including iterative calculation for circular references. If not set, defaults to DEFAULT_CALCULATION_SETTINGS. @see plans/active/spreadsheet-compatibility/04-EDITING-BEHAVIORS-PLAN.md - G.3 */ calculationSettings?: CalculationSettings; /** Whether the workbook uses the 1904 date system (affects all date calculations). Default: false (1900 date system). */ date1904?: boolean; /** Default table style ID for new tables created in this workbook. Can be a built-in style preset name (e.g., 'medium2', 'dark1') or a custom style ID (e.g., 'custom-abc123'). When undefined, new tables use the 'medium2' preset by default. Plan 15: Tables spreadsheet compatibility - P1-8 (Set as default style) */ defaultTableStyleId?: string; /** Whether chart data points track cell movement when cells are inserted/deleted. When true, chart data series follow their original data points even if the underlying cells shift due to row/column insertion or deletion. Default: true (matches the spreadsheet default). Mirrors the workbook chart data point tracking behavior. */ chartDataPointTrack?: boolean; } ``` ## WorkbookSnapshot A summary snapshot of the entire workbook state. ```typescript type WorkbookSnapshot = { /** All sheets in the workbook */ sheets: SheetSnapshot[]; /** ID of the currently active sheet */ activeSheetId: string; /** Total number of sheets */ sheetCount: number; } ``` ## WorkbookTrackOptions Options for creating a workbook-level change tracker. ```typescript type WorkbookTrackOptions = { /** Filter by origin type. Omit to track all origins. */ origins?: ChangeOrigin[]; /** Max records before auto-truncation (default: 10000). */ limit?: number; } ``` ## WorksheetCreateCheckboxOptions ```typescript type WorksheetCreateCheckboxOptions = Omit ``` ## WorksheetCreateComboBoxOptions ```typescript type WorksheetCreateComboBoxOptions = Omit ```