Skip to content

Overview

Source code
src/components/formula/Formula.ts
import { controlAttributes, createControl } from '@revolist/ui';
import { Switch } from '@revolist/ui/preact';
import { h as createSwitchVNode, render as renderNamesSwitch } from 'preact';
import { defineCustomElements } from '@revolist/revogrid/loader';
defineCustomElements();
import {
AutoFillPlugin,
AutoFillPreviewPlugin,
ColumnDropdown,
ColumnStretchPlugin,
FormulaPlugin,
FormulaBarPlugin,
FormulaDependencyHighlightPlugin,
NamedRangesPlugin,
RangeSelectionLimitPlugin,
ExportExcelPlugin,
RowOddPlugin,
type ExportExcelEvent,
createFormulaConditionalCellProperties,
createNamedRangeDropdown,
defineFormulaNameManager,
} from '@revolist/revogrid-pro';
import { currentTheme, useRandomData } from '../composables/useRandomData';
import './formula.scss';
import {
EXTERNAL_SHEET_LOAD_DELAY_MS,
SERVICE_LOOKUP_FORMULA,
registerServiceLookup,
} from './formula-async-service';
const { createRandomData } = useRandomData();
const { isDark } = currentTheme();
const fileExcelSvg =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path fill="currentColor" d="M0 64C0 28.7 28.7 0 64 0L213.5 0c17 0 33.3 6.7 45.3 18.7L365.3 125.3c12 12 18.7 28.3 18.7 45.3L384 448c0 35.3-28.7 64-64 64L64 512c-35.3 0-64-28.7-64-64L0 64zm208-5.5l0 93.5c0 13.3 10.7 24 24 24L325.5 176 208 58.5zM164 266.7c-7.4-11-22.3-14-33.3-6.7s-14 22.3-6.7 33.3L163.2 352 124 410.7c-7.4 11-4.4 25.9 6.7 33.3s25.9 4.4 33.3-6.7l28-42 28 42c7.4 11 22.3 14 33.3 6.7s14-22.3 6.7-33.3L220.8 352 260 293.3c7.4-11 4.4-25.9-6.7-33.3s-25.9-4.4-33.3 6.7l-28 42-28-42z"/></svg>';
const lookupFormula =
"=INDEX('Product List'!$B$1:$B$2,MATCH(B1,'Product List'!$A$1:$A$2,0))";
export function load(parentSelector: string) {
const parent = document.querySelector(parentSelector);
if (!parent) return;
const shell = document.createElement('div');
shell.className = 'formula-example';
const toolbar = document.createElement('div');
toolbar.className = 'formula-toolbar';
const namesToggle = document.createElement('div');
const insertButton = createControl(document, 'button');
insertButton.className = controlAttributes('button', {
class: 'rv-btn',
}).class;
const managerButton = createControl(document, 'button');
managerButton.className = controlAttributes('button', {
class: 'rv-btn',
}).class;
const catalogButton = createControl(document, 'button', { type: 'button' });
catalogButton.className = controlAttributes('button', {
class: 'rv-btn',
}).class;
catalogButton.type = 'button';
const serviceButton = createControl(document, 'button', { type: 'button' });
serviceButton.className = controlAttributes('button', {
class: 'rv-btn',
}).class;
serviceButton.type = 'button';
serviceButton.textContent = 'Reload service lookup';
const targetInput = createControl(document, 'input', { type: 'number' });
targetInput.type = 'number';
targetInput.min = '0';
targetInput.step = '50';
targetInput.setAttribute('aria-label', 'Target price');
targetInput.className = controlAttributes('input', {
type: targetInput.type,
class: 'formula-target-input',
}).class;
const formulaBarInput = createControl(document, 'input', { type: 'text' });
formulaBarInput.type = 'text';
formulaBarInput.placeholder = 'Formula or value';
formulaBarInput.setAttribute('aria-label', 'Formula bar');
formulaBarInput.className = controlAttributes('input', {
type: formulaBarInput.type,
class: 'formula-bar-input',
}).class;
const formulaBarBadge = document.createElement('span');
formulaBarBadge.className = 'formula-bar-badge';
formulaBarBadge.hidden = true;
const formulaBarControl = document.createElement('div');
formulaBarControl.className = 'formula-bar-control';
formulaBarControl.append(formulaBarBadge, formulaBarInput);
const exportButton = createControl(document, 'button', { type: 'button' });
exportButton.className = controlAttributes('button', {
class: 'rv-btn',
}).class;
exportButton.type = 'button';
exportButton.title = 'Export to Excel';
exportButton.setAttribute('aria-label', 'Export to Excel');
const exportIcon = document.createElement('span');
exportIcon.className = 'formula-toolbar-icon';
exportIcon.innerHTML = fileExcelSvg;
exportButton.append(exportIcon);
const exportConfig: ExportExcelEvent = {
sheetName: 'RevoGrid Formula',
workbookName: 'formula-example.xlsx',
};
const exportToExcel = async () => {
const plugins = await grid.getPlugins();
const exportPlugin = plugins.find(
(plugin) => plugin instanceof ExportExcelPlugin,
) as ExportExcelPlugin | undefined;
exportPlugin?.export(exportConfig);
};
toolbar.append(namesToggle, formulaBarControl, exportButton);
const options = document.createElement('details');
options.className = 'formula-options';
const optionsSummary = createControl(document, 'summary', {
class: 'rv-disclosure-summary--compact',
});
optionsSummary.textContent = 'More options';
const optionsControls = document.createElement('div');
optionsControls.className = 'formula-options-controls';
const targetLabel = document.createElement('label');
targetLabel.className = 'formula-target-label';
targetLabel.append('Target price', targetInput);
optionsControls.append(
insertButton,
managerButton,
catalogButton,
serviceButton,
targetLabel,
);
options.append(optionsSummary, optionsControls);
const workbookMap = document.createElement('section');
workbookMap.className = 'formula-workbook-map';
workbookMap.setAttribute('aria-label', 'Cross-sheet lookup setup');
workbookMap.innerHTML = `
<div class="formula-workbook-flow">
<span class="formula-sheet-pill"><strong>Orders</strong><small>mounted RevoGrid</small></span>
<span class="formula-workbook-arrow" aria-hidden="true">looks up →</span>
<span class="formula-sheet-pill formula-sheet-pill-external"><strong>Product List</strong><small data-testid="formula-external-sheet-status">not loaded · no grid mounted</small></span>
</div>
<div class="formula-workbook-reference">
<span>Formula stored in Orders!D1</span>
<code data-testid="formula-cross-sheet-formula">${lookupFormula}</code>
</div>
<div class="formula-external-sheet" data-testid="formula-external-sheet">
<span class="formula-external-sheet-title">Product List is not loaded yet</span>
<span class="formula-external-sheet-pending" data-testid="formula-external-sheet-pending">Waiting for backend data…</span>
</div>
`;
const externalSheetStatus = workbookMap.querySelector<HTMLElement>(
'[data-testid="formula-external-sheet-status"]',
);
const externalSheet = workbookMap.querySelector<HTMLElement>(
'[data-testid="formula-external-sheet"]',
);
shell.append(toolbar, options, workbookMap);
const grid = document.createElement('revo-grid');
grid.rowHeaders = true;
grid.range = true;
grid.stretch = 'last';
grid.hideAttribution = true;
grid.theme = isDark() ? 'darkCompact' : 'compact';
grid.className = 'formula-grid';
grid.plugins = [
AutoFillPlugin,
AutoFillPreviewPlugin,
RangeSelectionLimitPlugin,
FormulaBarPlugin,
FormulaDependencyHighlightPlugin,
NamedRangesPlugin,
FormulaPlugin,
RowOddPlugin,
ColumnStretchPlugin,
ExportExcelPlugin,
];
grid.rangeSelectionLimit = { mode: 'column' };
const managerPanel = document.createElement('div');
managerPanel.className = 'formula-manager';
managerPanel.hidden = true;
shell.append(grid, managerPanel);
parent.appendChild(shell);
let namesEnabled = true;
let targetPrice = 500;
let catalogHardwarePrice = 650;
let catalogLoaded = false;
let rowId = 100;
let managerMounted = false;
let disposeServiceLookup: (() => void) | undefined;
let externalSheetLoadTimer: number | undefined;
let disposed = false;
const formulaDependencyHighlight = {
dependencyClass: 'formula-dependency-cell',
formulaCellClass: 'formula-dependency-active-cell',
dependencyColors: [
'#2563eb',
'#dc2626',
'#16a34a',
'#9333ea',
'#ea580c',
'#0891b2',
],
includeNamedRanges: true,
};
const source = createRandomData(100).map((row, index) => ({
id: index,
price: row.price,
category: index % 2 === 0 ? 'Hardware' : 'Software',
}));
const productSheet = {
id: 'Product List',
rowIdProp: 'id',
columns: [{ prop: 'category' }, { prop: 'price' }],
rows: [
{ id: 'product-hardware', category: 'Hardware', price: 650 },
{ id: 'product-software', category: 'Software', price: 450 },
],
};
const formulaWorkbook = {
sheetId: 'Orders',
rowIdProp: 'id',
externalSheets: [],
};
const buildFormulaNames = () => ({
names: namesEnabled
? [
{
name: 'PriceList',
scope: 'workbook' as const,
kind: 'range' as const,
ref: `A1:A${source.length}`,
},
{
name: 'TargetPrice',
scope: 'workbook' as const,
kind: 'constant' as const,
value: targetPrice,
},
{
name: 'CategoryList',
scope: 'workbook' as const,
kind: 'range' as const,
ref: 'B1:B2',
},
]
: [],
});
const readTargetPrice = (
names: Array<{ name: string; kind?: string; value?: unknown }>,
) => {
const targetName = names.find(
(name) => name.name === 'TargetPrice' && name.kind === 'constant',
);
const nextTarget = Number(targetName?.value);
return Number.isFinite(nextTarget) ? nextTarget : undefined;
};
const categoryOptions = ['Hardware', 'Software'];
const targetFormulaRef = () =>
namesEnabled ? 'TargetPrice' : String(targetPrice);
const priceListRef = () =>
namesEnabled ? 'PriceList' : `A1:A${source.length}`;
const summaryCategoryLabel = () =>
namesEnabled ? 'Total (named range)' : 'Total (direct refs)';
const categoryDropdown = (
columns: any[],
formulaNames: ReturnType<typeof buildFormulaNames>,
) => {
const dropdown = namesEnabled
? createNamedRangeDropdown('CategoryList', {
allSources: source,
columns,
names: formulaNames.names,
})
: { source: categoryOptions.map((value) => ({ value, label: value })) };
const extraOptions = categoryOptions.filter(
(value) => !dropdown.source.some((option) => option.value === value),
);
return {
...dropdown,
syncCellTemplate: true,
source: [
...dropdown.source,
...extraOptions.map((value) => ({ value, label: value })),
],
};
};
const buildGridSource = () =>
source.map((row, index) => ({
...row,
forecast: `=A${index + 1}+${targetFormulaRef()}`,
catalogPrice: `=INDEX('Product List'!$B$1:$B$2,MATCH(B${index + 1},'Product List'!$A$1:$A$2,0))`,
servicePrice: index === 0 ? SERVICE_LOOKUP_FORMULA : '',
}));
const buildColumns = (formulaNames: ReturnType<typeof buildFormulaNames>) => {
const columns: any[] = [
{
name: 'Price',
prop: 'price',
cellTemplate: (_, { value }) => parseFloat(value).toFixed(2),
},
{
name: 'Category',
prop: 'category',
size: 200,
columnType: 'categoryDropdown',
readonly: ({ type }) => type === 'rowPinEnd',
cellProperties({ type }) {
return type === 'rowPinEnd'
? { class: 'formula-category-pinned' }
: undefined;
},
},
{
name: 'Formula',
prop: 'forecast',
cellProperties: () => ({ class: 'formula-cell' }),
},
{
name: 'Catalog (INDEX/MATCH)',
prop: 'catalogPrice',
cellProperties: () => ({ class: 'formula-cell' }),
},
{
name: 'Service (async VLOOKUP)',
prop: 'servicePrice',
cellProperties: () => ({ class: 'formula-cell' }),
},
];
const priceConditional = createFormulaConditionalCellProperties(
`=cellvalue>${targetFormulaRef()}`,
{ class: 'formula-above-target' },
{ allSources: source, columns, names: formulaNames.names },
);
columns[0].cellProperties = (props) => {
if (props.type === 'rowPinEnd') {
return { class: { 'formula-cell': true, 'formula-cell-pinned': true } };
}
return priceConditional(props);
};
columns[1].dropdown = categoryDropdown(columns, formulaNames);
return columns;
};
const applyConfig = () => {
const formulaNames = buildFormulaNames();
renderNamesSwitch(
createSwitchVNode(Switch, {
label: 'Names',
checked: namesEnabled,
onChange: (checked) => {
namesEnabled = checked;
applyConfig();
},
}),
namesToggle,
);
insertButton.textContent = 'Insert row';
managerButton.textContent = managerPanel.hidden
? 'Name manager'
: 'Hide manager';
catalogButton.textContent = catalogLoaded
? catalogHardwarePrice === 650
? 'Raise catalog price'
: 'Reset catalog price'
: 'Load Product List';
targetInput.value = String(targetPrice);
grid.formulaNames = formulaNames;
if (!grid.formulaWorkbook) {
grid.formulaWorkbook = formulaWorkbook;
}
grid.formulaDependencyHighlight = formulaDependencyHighlight;
grid.formulaBar = {
el: formulaBarInput,
badgeEl: formulaBarBadge,
showCellBadge: true,
};
grid.additionalData = { formulaNames };
grid.columns = buildColumns(formulaNames);
grid.columnTypes = { categoryDropdown: ColumnDropdown };
grid.pinnedBottomSource = [
{
price: `=ROUND(SUM(${priceListRef()}),2)`,
category: summaryCategoryLabel(),
forecast: `=ROUND(SUM(${priceListRef()})+${targetFormulaRef()}*${source.length},2)`,
catalogPrice: `=SUM(D1:D${source.length})`,
servicePrice: '',
},
];
grid.source = buildGridSource();
};
targetInput.addEventListener('input', () => {
targetPrice = Number(targetInput.value) || 0;
applyConfig();
});
insertButton.addEventListener('click', () => {
source.splice(1, 0, {
id: rowId++,
price: targetPrice + 75,
category: 'Hardware',
});
applyConfig();
});
managerButton.addEventListener('click', () => {
managerPanel.hidden = !managerPanel.hidden;
if (!managerMounted) {
defineFormulaNameManager(managerPanel, grid, { pageSize: 8 });
managerMounted = true;
}
applyConfig();
});
catalogButton.addEventListener('click', async () => {
const nextPrice = catalogHardwarePrice === 650 ? 725 : 650;
const plugins = await grid.getPlugins();
const formulaPlugin = plugins.find(
(plugin) => plugin instanceof FormulaPlugin,
) as FormulaPlugin | undefined;
if (!catalogLoaded) {
formulaPlugin?.upsertFormulaSheet(productSheet);
if (!formulaPlugin) {
return;
}
catalogLoaded = true;
catalogButton.textContent = 'Raise catalog price';
if (externalSheetStatus) {
externalSheetStatus.textContent = 'externalSheets · no grid mounted';
}
if (externalSheet) {
externalSheet.innerHTML = `
<span class="formula-external-sheet-title">Product List registered after Orders mounted</span>
<span>A1&nbsp; Hardware</span><strong data-testid="formula-external-hardware-price">B1&nbsp; ${catalogHardwarePrice}</strong>
<span>A2&nbsp; Software</span><strong>B2&nbsp; 450</strong>
`;
}
return;
}
formulaPlugin?.updateFormulaSheetCell(
'Product List',
'product-hardware',
'price',
nextPrice,
);
catalogHardwarePrice = nextPrice;
catalogButton.textContent =
catalogHardwarePrice === 650
? 'Raise catalog price'
: 'Reset catalog price';
const externalHardwarePrice = externalSheet?.querySelector<HTMLElement>(
'[data-testid="formula-external-hardware-price"]',
);
if (externalHardwarePrice)
externalHardwarePrice.textContent = `B1 ${catalogHardwarePrice}`;
});
serviceButton.addEventListener('click', async () => {
const plugins = await grid.getPlugins();
const formulaPlugin = plugins.find(
(plugin) => plugin instanceof FormulaPlugin,
) as FormulaPlugin | undefined;
formulaPlugin?.invalidateAsyncFormulaFunction('VLOOKUP');
});
exportButton.addEventListener('click', exportToExcel);
const syncToolbarTarget = (event: Event) => {
const registry = (
event as CustomEvent<{
names?: Array<{ name: string; kind?: string; value?: unknown }>;
}>
).detail;
const nextTarget = readTargetPrice(registry.names ?? []);
if (typeof nextTarget !== 'number' || nextTarget === targetPrice) {
return;
}
targetPrice = nextTarget;
applyConfig();
};
grid.addEventListener('formulanameschange', syncToolbarTarget);
applyConfig();
externalSheetLoadTimer = window.setTimeout(() => {
if (!catalogLoaded) catalogButton.click();
}, EXTERNAL_SHEET_LOAD_DELAY_MS);
void customElements
.whenDefined('revo-grid')
.then(() => grid.getPlugins())
.then((plugins) => {
const formulaPlugin = plugins.find(
(plugin) => plugin instanceof FormulaPlugin,
) as FormulaPlugin | undefined;
if (!formulaPlugin) return;
disposeServiceLookup = registerServiceLookup(formulaPlugin);
if (disposed) disposeServiceLookup();
});
return () => {
disposed = true;
if (externalSheetLoadTimer !== undefined)
window.clearTimeout(externalSheetLoadTimer);
disposeServiceLookup?.();
grid.removeEventListener('formulanameschange', syncToolbarTarget);
renderNamesSwitch(null, namesToggle);
shell.remove();
};
}

Formula adds spreadsheet-style calculations to RevoGrid. A source value beginning with = is stored as an expression, while the mounted grid renders its derived result. For example, source data can retain =A1*B1 while the cell displays 30.

The contract is deliberately narrower than Excel:

  • A1 coordinates follow the authored row and column order, not the current sorted, filtered, pinned, or hidden presentation.
  • Formula recalculates mounted cells when configured source or workbook data changes. It does not replace the raw formula in grid.source with the result.
  • Invalid syntax, unknown functions, and circular references resolve to #ERROR. Autofill that moves a relative reference before A1 produces #REF!.
  • Functions come from FormulaJS, but RevoGrid owns the expression parser. Use the documented FormulaJS-backed subset, not assumed full Excel compatibility.

The demo is an Orders grid connected to a Product List dataset. Select a formula cell to inspect its expression, then try the Names switch. Open More options for the workbook actions below.

ControlWhat to observe
Select a formula cellThe Formula Bar shows the raw =... expression while the grid keeps showing the calculated value.
NamesFormulas switch between readable names and direct A1 references without changing their results.
Insert rowReferences below the inserted row update to keep pointing at the same logical data.
Name managerView and edit range, constant, and formula names used by the workbook.
Raise catalog priceProduct List changes through the mounted Formula API and dependent Orders cells recalculate.
Reload service lookupThe async formula is invalidated, briefly shows its loading state, then renders the refreshed service value.
GoalStart hereHelpful first
Add your first calculated columnQuick StartRevoGrid columns and source data
Copy formulas or understand A1 identityA1 References and AutofillQuick Start
Replace coordinates with readable namesNamed RangesA1 references
Add a Formula Bar, highlights, lists, or stylingFormula UI and HelpersQuick Start
Look up values in another datasetCross-sheet FormulasA1 references
Call an application service from a formulaAsync Formula FunctionsQuick Start
Recalculate and persist without a gridBackend Calculation and PersistenceCross-sheet formulas
Check syntax and available functionsSupported FunctionsQuick Start

Next: Quick Start · Deeper reference: Formula API