Skip to content

Data Grid formulas

Spreadsheet formulas for the Data Grid: our own parser and evaluator (never eval), in a separate entry point so grids without formulas do not ship them.

  • formulaEngine({ functions, calendar }): pass it as the grid’s formulas option.
  • formulaBar(): an accessory that shows the focused cell’s address and formula.
  • FormulaBook, parseFormula, evaluateFormula, and the helpers around them work without a grid, for your own sheets and validation.
import { DataGrid } from '@absoluteui/components/data-grid';
import { formulaBar, formulaEngine } from '@absoluteui/components/data-grid/formulas';
interface Item {
id: string;
price: number;
qty: number;
note: string | number | null;
}
const host = document.createElement('div');
host.style.setProperty('block-size', '240px');
document.body.append(host);
DataGrid.create<Item>(host, {
label: 'Quote',
rows: [{ id: '1', price: 2, qty: 10, note: '=A1 * 2' }],
rowId: (r) => r.id,
formulas: formulaEngine(),
accessories: [formulaBar()],
columns: [
{ id: 'price', header: 'Price', field: 'price', type: 'number', editable: true },
{ id: 'qty', header: 'Quantity', field: 'qty', type: 'number', editable: true },
{ id: 'note', header: 'Note', field: 'note', editable: true, formulas: true },
{ id: 'total', header: 'Total', type: 'number', formula: '[Price] * [Quantity]' },
],
});
  • Calculated columns: formula: '[Price] * [Quantity]'. [Column] (column id or header, without case) is the same row’s value, or the whole column inside functions (SUM([Total])); [@Column] is always the same row. Results are read-only and sort, filter, group, aggregate, and export as values.
  • Cell formulas: columns with formulas: true evaluate values that are text starting with =, stored in your row data. A1 references use stable addresses: letters by column definition order, numbers by source row order.
  • The editor shows the formula with function and column suggestions, the signature of the function around the caret, and syntax problems; a click on another cell inserts its address. Invalid formulas are refused with the position of the problem. Fill, Ctrl+D / Ctrl+R, and pasting cells copied in the grid move relative references ($ parts stay).
  • Functions: math and aggregates, conditional aggregates (SUMIF, SUMIFS, COUNTIF, COUNTIFS, AVERAGEIF), logic, text, dates (NETWORKDAYS and WORKDAY on the engine’s business calendar; TODAY in the grid time zone), and lookups (XLOOKUP, INDEX, MATCH, VLOOKUP). BUILTIN_FUNCTIONS and FUNCTION_SIGNATURES list them; add your own with functions.
  • Errors show their code and read their meaning (“#DIV/0!, division by zero”); cycles give #CIRCULAR!.
  • Limits give errors, never hangs: 8192 characters per formula, 64 nesting levels, 1,000,000 cells per range, 1,000,000 evaluation steps.
  • parseFormula throws FormulaSyntaxError with a message and the character position of the problem.
  • Evaluation never throws: problems are formula error values (ERROR_CODES: #DIV/0!, #VALUE!, #REF!, #NAME?, #N/A, #NUM!, #NULL!, #CIRCULAR!, #LIMIT!).

formulaBar

A read-only formula bar above the grid (an accessory): the focused cell’s stable address and its formula (or its displayed value).

function formulaBar<Row>(): DataGridAccessory<Row>;

formulaEngine

The formula engine for the grid’s formulas option: the built-in functions plus the application’s.

function formulaEngine(options?: FormulaEngineOptions): DataGridFormulaEngine;

FormulaEngineOptions

interface FormulaEngineOptions {
readonly functions?: Readonly<Record<string, FormulaFunction>>;
readonly calendar?: BusinessCalendarEngine;
}

FormulaBook

class FormulaBook {
constructor(options: FormulaBookOptions);
parse(text: string): ParsedFormula;
value(row: number, column: number): Scalar;
invalidate(row: number, column: number): void;
invalidateAll(): void;
}

FormulaBookOptions

interface FormulaBookOptions {
readonly source: FormulaSource;
readonly functions: ReadonlyMap<string, FormulaFunction>;
readonly today: () => PlainDate;
readonly calendar?: BusinessCalendarEngine;
}

FormulaSource

The cells a book computes over: plain values, formula texts, and column names.

interface FormulaSource {
readonly rowCount: number;
readonly columnCount: number;
column(name: string): number;
formula(row: number, column: number): string | null;
value(row: number, column: number): Scalar;
formulaRows(column: number, top: number, bottom: number): Iterable<number>;
}

ParsedFormula

A parse result: the tree, or the syntax error.

type ParsedFormula = {
readonly node: FormulaNode;
} | {
readonly error: FormulaSyntaxError;
};

callAt

The function call around the caret and the 0-based argument index.

function callAt(text: string, caret: number): {
name: string;
argument: number;
} | null;

createFormulaEditor

A formula editor for a cell of a formulas column.

function createFormulaEditor(context: DataGridEditorContext, names: FormulaEditorNames, messages: FormulaEditorMessages): DataGridCellEditor & {
insertReference(reference: string): boolean;
};

FormulaEditorMessages

interface FormulaEditorMessages {
readonly suggestions: string;
readonly problem: (message: string) => string;
}

FormulaEditorNames

interface FormulaEditorNames {
readonly functions: ReadonlyMap<string, string>;
readonly columns: readonly {
readonly id: string;
readonly header: string;
}[];
}

compareScalars

Spreadsheet ordering: numbers (and dates) < text < booleans; text compares without case; a blank is 0, “”, or FALSE.

function compareScalars(a: Scalar, b: Scalar): number;

dateToSerial

function dateToSerial(d: PlainDate): number;

evaluateFormula

Evaluate a parsed formula for one cell. Never throws for formula problems: they become error values.

function evaluateFormula(node: FormulaNode, options: EvaluateOptions): Scalar;

formulaError

The shared error value of a code.

function formulaError(code: FormulaErrorCode): FormulaError;

serialToDate

function serialToDate(serial: number): PlainDate | null;

toBoolean

function toBoolean(v: Scalar): boolean | FormulaError;

toDate

function toDate(v: Scalar): PlainDate | FormulaError;

toNumber

function toNumber(v: Scalar): number | FormulaError;

toText

function toText(v: Scalar): string | FormulaError;

isFormulaError

const isFormulaError: (v: unknown) => v is FormulaError;

isRange

const isRange: (v: FormulaValue) => v is RangeValue;

EvaluateOptions

interface EvaluateOptions {
readonly sheet: FormulaSheet;
readonly row: number;
readonly column: number;
readonly functions: ReadonlyMap<string, FormulaFunction>;
readonly today: () => PlainDate;
readonly calendar?: BusinessCalendarEngine;
readonly steps?: number;
}

FormulaError

interface FormulaError {
readonly error: FormulaErrorCode;
}

FormulaSheet

Cell values for evaluation (a formula cell’s value is its result).

interface FormulaSheet {
readonly rowCount: number;
readonly columnCount: number;
column(name: string): number;
value(row: number, column: number): Scalar;
}

FunctionContext

interface FunctionContext {
readonly row: number;
readonly column: number;
today(): PlainDate;
readonly calendar: BusinessCalendarEngine | undefined;
scalar(value: FormulaValue): Scalar;
}

RangeValue

A rectangle of cells (ranges and column references), read lazily.

interface RangeValue {
readonly kind: 'range';
readonly top: number;
readonly left: number;
readonly rows: number;
readonly columns: number;
at(row: number, column: number): Scalar;
}

FormulaFunction

A function: evaluated arguments (ranges stay ranges), returns one value. Must be pure.

type FormulaFunction = (args: readonly FormulaValue[], context: FunctionContext) => Scalar;

FormulaValue

type FormulaValue = Scalar | RangeValue;

Scalar

A single value: a number, text, boolean, calendar date, blank (null), or an error.

type Scalar = number | string | boolean | PlainDate | null | FormulaError;

BUILTIN_FUNCTIONS

const BUILTIN_FUNCTIONS: ReadonlyMap<string, FormulaFunction>;

FUNCTION_NAME

Function names: letters, digits, _, and ., starting with a letter; at most 64 characters.

const FUNCTION_NAME: RegExp;

FUNCTION_SIGNATURES

Argument hints for the formula editor (brackets mark optional arguments).

const FUNCTION_SIGNATURES: ReadonlyMap<string, string>;

columnIndex

0-based column index of column letters (A is 0), or -1 past XFD.

function columnIndex(letters: string): number;

columnLetters

Column letters of a 0-based index.

function columnLetters(index: number): string;

formatAddress

function formatAddress(a: CellAddress): string;

parseFormula

Parse a formula (with or without the leading =). Throws FormulaSyntaxError.

function parseFormula(source: string): FormulaNode;

references

Every cell, range, column, and function name a formula refers to (for dependencies and autocomplete).

function references(node: FormulaNode): {
cells: CellAddress[];
ranges: {
from: CellAddress;
to: CellAddress;
}[];
columns: {
name: string;
thisRow: boolean;
}[];
functions: string[];
};

shiftFormula

The formula with relative A1 references moved by rows and columns (fill and paste); $ parts stay. References moved outside the sheet become #REF!. Text, column references, and names are kept as typed.

function shiftFormula(source: string, rows: number, columns: number): string;

FormulaSyntaxError

A parse failure: a message and the 0-based position in the formula text (after =).

class FormulaSyntaxError extends Error {
readonly position: number;
constructor(message: string, position: number);
}

ERROR_CODES

The formula error values, as spreadsheets write them.

const ERROR_CODES: readonly ["#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#N/A", "#NUM!", "#NULL!", "#CIRCULAR!", "#LIMIT!"];

MAX_FORMULA_LENGTH

const MAX_FORMULA_LENGTH = 8192;

CellAddress

A cell address: 0-based column and row with their $ anchors.

interface CellAddress {
readonly column: number;
readonly row: number;
readonly columnAbsolute: boolean;
readonly rowAbsolute: boolean;
}

BinaryOperator

type BinaryOperator = '+' | '-' | '*' | '/' | '^' | '&' | '=' | '<>' | '<' | '>' | '<=' | '>=';

FormulaErrorCode

type FormulaErrorCode = (typeof ERROR_CODES)[number];

FormulaNode

type FormulaNode = {
readonly kind: 'number';
readonly value: number;
} | {
readonly kind: 'text';
readonly value: string;
} | {
readonly kind: 'boolean';
readonly value: boolean;
} | {
readonly kind: 'error';
readonly code: FormulaErrorCode;
} | {
readonly kind: 'cell';
readonly address: CellAddress;
} | {
readonly kind: 'range';
readonly from: CellAddress;
readonly to: CellAddress;
}
| {
readonly kind: 'column';
readonly name: string;
readonly thisRow: boolean;
} | {
readonly kind: 'unary';
readonly operator: '-' | '+' | '%';
readonly operand: FormulaNode;
} | {
readonly kind: 'binary';
readonly operator: BinaryOperator;
readonly left: FormulaNode;
readonly right: FormulaNode;
} | {
readonly kind: 'call';
readonly name: string;
readonly args: readonly FormulaNode[];
};