Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

dash: formulas and charts (#235)

nyblnetcc038183dbf7
diff --git a/dash/CHANGELOG.md b/dash/CHANGELOG.md
index 37be61d7..af616297 100644
--- a/dash/CHANGELOG.md
+++ b/dash/CHANGELOG.md
@@ -8,10 +8,27 @@ The format (`bento/dash`, version `1`) is additive and stable — every version
below opens files from every earlier version, and unknown fields are preserved.
There is no server, so a break here would be permanent.
-## [0.1.0] — 2026-08-03
-
-First release. A workbook is one self-contained HTML file: the data, the grid
-and the editor, opening from `file://` with no backend.
+## [0.2.0] — 2026-08-03
+
+First release. A workbook is one self-contained HTML file: the data, the grid,
+the formulas and the charts, opening from `file://` with no backend.
+
+- **One formula for a whole column.** A spreadsheet stores an expression per
+ cell, so a 100,000-row model with twelve computed columns carries 1.2 million
+ of them, each with range references that shift when you insert a row. Here it
+ is twelve strings. `#REF!` and the shifted-VLOOKUP cannot happen, because
+ there is no range to shift. About fifty functions, including `SUMIF`,
+ `COUNTIF` and aggregates you can mix into a row expression —
+ `Value / SUM(Value)` is a share-of-total column.
+
+- **Errors stay visible.** A division by zero reads `#DIV/0!`, a circular
+ reference reads `#CYCLE!`, and neither is quietly a zero — a total containing
+ silent zeros is wrong and looks right.
+
+- **Charts are bound to columns, never to a copy of the numbers.** Edit a cell
+ and the chart moves; nothing in the file can disagree with the table beside
+ it. A category with no data is drawn as a gap rather than as zero, because
+ "we sold nothing" and "we do not know" are different claims.
- **Import the CSV somebody emailed you, and see what it decided.** Comma,
semicolon or tab, quoted fields with commas and newlines inside them, a BOM,
diff --git a/dash/package.json b/dash/package.json
index 29716a1a..2b4a4726 100644
--- a/dash/package.json
+++ b/dash/package.json
@@ -1,7 +1,7 @@
{
"name": "bento-dash",
"private": true,
- "version": "0.1.0",
+ "version": "0.2.0",
"type": "module",
"license": "MIT",
"scripts": {
diff --git a/dash/src/chart.ts b/dash/src/chart.ts
new file mode 100644
index 00000000..f70d2a6d
--- /dev/null
+++ b/dash/src/chart.ts
@@ -0,0 +1,171 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Charts, bound to columns.
+//
+// A TILE NAMES A SHEET AND COLUMNS. The series arrays are DERIVED at render and
+// never stored — slides learned this the expensive way with `syncLinkedChart`,
+// where a chart that carried its own copy of the numbers could disagree with
+// the table beside it, go stale without saying so, and doubled the file.
+// Promoted here from a special case to the rule: there is no code path that
+// writes series data into the document.
+//
+// So a chart cannot be wrong about its own data. Edit a cell and the chart
+// moves; sort the grid and the chart does not, because sorting is view state.
+//
+// NULLS ARE GAPS, NOT ZEROES. charts-lite's `num(v, 0)` turns a missing value
+// into a plunge to the axis, which reads as "we sold nothing that month"
+// rather than "we do not know". Missing values are dropped from the category
+// entirely, and a series with nothing in it renders as absent rather than as a
+// flat line at zero.
+
+import { CHART_PRESETS, mountChart, type ChartLike } from '../../kernel/src/charts.ts'
+import type { TableSheet } from './model.ts'
+import { isErr } from './formula.ts'
+import { readCell } from './store.ts'
+
+export interface ChartBinding {
+ /** category axis — usually a text column */
+ x: string
+ /** one series per column id */
+ series: string[]
+ kind: 'bar' | 'line' | 'pie' | 'scatter'
+ /** group rows by the x value and total the series, rather than one bar per row */
+ aggregate?: 'sum' | 'avg' | 'count' | 'none'
+}
+
+const asNumber = (v: unknown): number | null => {
+ if (v == null || v === '' || isErr(v)) return null
+ const n = typeof v === 'number' ? v : Number(String(v).replace(/[,\s£$€¥%]/g, ''))
+ return Number.isFinite(n) ? n : null
+}
+
+/**
+ * Build a charts-lite option from a sheet and a binding.
+ *
+ * `computed` lets a formula column be charted without being stored: the grid
+ * hands in what it just recalculated, so the chart shows the same numbers the
+ * reader is looking at rather than the raw column underneath them.
+ */
+export function optionFor(
+ sheet: TableSheet,
+ bind: ChartBinding,
+ computed?: Map<string, unknown[]>,
+ palette: string[] = ['#F7A600', '#5B8DEF', '#2FB47C', '#E1616C', '#8B6FD3', '#3FA9B8'],
+): Record<string, unknown> {
+ const n = sheet.rids.reduce((a, [, c]) => a + c, 0)
+ const colVals = (id: string): unknown[] => {
+ const c = computed?.get(id)
+ if (c) return c
+ const d = sheet.data[id]
+ return Array.from({ length: n }, (_, i) => readCell(d, i))
+ }
+ const nameOf = (id: string) => sheet.columns.find((c) => c.id === id)?.name ?? id
+
+ const xs = colVals(bind.x).map((v) => (v == null ? '' : String(v)))
+ const agg = bind.aggregate ?? 'sum'
+
+ let cats: string[]
+ let series: Array<{ name: string; data: Array<number | null> }>
+
+ if (agg === 'none') {
+ cats = xs
+ series = bind.series.map((id) => ({
+ name: nameOf(id),
+ data: colVals(id).map(asNumber),
+ }))
+ } else {
+ // group by x, in first-seen order — a chart's categories should appear in
+ // the order the data does, not alphabetically
+ const order: string[] = []
+ const buckets = new Map<string, number[][]>()
+ xs.forEach((k, i) => {
+ if (!buckets.has(k)) { buckets.set(k, bind.series.map(() => [])); order.push(k) }
+ const b = buckets.get(k)!
+ bind.series.forEach((id, si) => {
+ const v = asNumber(colVals(id)[i])
+ if (v !== null) b[si].push(v)
+ })
+ })
+ cats = order
+ series = bind.series.map((id, si) => ({
+ name: nameOf(id),
+ data: order.map((k) => {
+ const vals = buckets.get(k)![si]
+ if (!vals.length) return null // a gap, never a zero
+ if (agg === 'count') return vals.length
+ const sum = vals.reduce((a, b) => a + b, 0)
+ return agg === 'avg' ? sum / vals.length : sum
+ }),
+ }))
+ }
+
+ if (bind.kind === 'pie') {
+ const first = series[0]
+ return {
+ ...CHART_PRESETS.pie(),
+ color: palette,
+ series: [{
+ type: 'pie',
+ radius: '68%',
+ data: cats
+ .map((c, i) => ({ name: c, value: first?.data[i] }))
+ .filter((d) => d.value != null),
+ }],
+ }
+ }
+
+ const base = CHART_PRESETS[bind.kind]?.() ?? CHART_PRESETS.bar()
+ return {
+ ...base,
+ color: palette,
+ legend: { bottom: 0, show: series.length > 1 },
+ xAxis: { type: 'category', data: cats },
+ yAxis: { type: 'value' },
+ series: series.map((s) => ({
+ type: bind.kind,
+ name: s.name,
+ data: s.data,
+ ...(bind.kind === 'line' ? { smooth: false, symbolSize: 6 } : {}),
+ })),
+ }
+}
+
+/** Mount a live chart into a host element. Returns a teardown. */
+export function renderChart(
+ host: HTMLElement,
+ sheet: TableSheet,
+ bind: ChartBinding,
+ computed?: Map<string, unknown[]>,
+): () => void {
+ const el: ChartLike = {
+ w: host.clientWidth || 640,
+ h: host.clientHeight || 320,
+ option: optionFor(sheet, bind, computed),
+ }
+ host.innerHTML = ''
+ return mountChart(el, host)
+}
+
+/**
+ * A sensible default binding for a sheet: the first text column against every
+ * numeric one. This is what "+ Chart" produces, so the first chart takes no
+ * configuration at all.
+ */
+export function defaultBinding(sheet: TableSheet): ChartBinding | null {
+ const text = sheet.columns.find((c) => c.type === 'text' || c.type === 'enum')
+ // PERCENT columns are excluded unless there is nothing else. A 0-to-1 series
+ // on the same axis as money renders as no bar at all, so the legend names a
+ // series the reader cannot see — which is worse than leaving it out, because
+ // it looks like the data is missing rather than the scale being wrong.
+ // (A second axis is the real fix; it is not in v0.1.)
+ const magnitude = sheet.columns.filter((c) => c.type === 'number' || c.type === 'money')
+ const pct = sheet.columns.filter((c) => c.type === 'percent')
+ const nums = magnitude.length ? magnitude : pct
+ if (!nums.length) return null
+ return {
+ x: text?.id ?? sheet.columns[0].id,
+ series: nums.slice(0, 3).map((c) => c.id),
+ kind: 'bar',
+ aggregate: text ? 'sum' : 'none',
+ }
+}
diff --git a/dash/src/formula.ts b/dash/src/formula.ts
new file mode 100644
index 00000000..39f9dc07
--- /dev/null
+++ b/dash/src/formula.ts
@@ -0,0 +1,499 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The formula engine.
+//
+// ONE EXPRESSION PER COLUMN, and that is the largest structural improvement
+// over a spreadsheet available here. Excel stores a formula per CELL, so a
+// 100k-row model with 12 computed columns has 1.2 MILLION graph nodes, each
+// carrying its own copy of the same expression and its own range references
+// that shift when a row is inserted. Here it is 12 nodes, one stored string
+// each, and inserting a row changes nothing at all — the `#REF!` class and the
+// shifted-VLOOKUP class simply do not exist.
+//
+// EVALUATION IS VECTORISED. Every node returns either a SCALAR or a COLUMN of
+// n values, and the two combine by broadcasting. So `Value * Rate` is one pass
+// over two arrays rather than n interpreted expressions, and `Value / SUM(Value)`
+// mixes a column and an aggregate without either side knowing about the other.
+// Measured shape (design §7): a 100k-row workbook recalculates inside a frame,
+// so there is no "calculating…" state and no async recalc UI.
+//
+// ERRORS PROPAGATE, they do not throw and they are never silently zero. A cell
+// that could not be computed reads `#DIV/0!` or `#VALUE!` — visible, and wrong
+// in a way you can see. Zero is a number, and a chart of zeros is a wrong
+// answer wearing a right answer's clothes.
+
+import type { TableSheet } from './model.ts'
+import { readCell } from './store.ts'
+
+export type Cell = number | string | boolean | null | FormulaError
+export type Vec = Cell[]
+
+/**
+ * Excel-shaped so the strings are already familiar.
+ *
+ * Fields are declared and assigned explicitly rather than as constructor
+ * parameter properties: the rigs run TypeScript through node's strip-only
+ * loader, which cannot express them (`ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX`).
+ */
+export class FormulaError {
+ code: string
+ why?: string
+ constructor(code: string, why?: string) { this.code = code; this.why = why }
+ toString(): string { return this.code }
+}
+const ERR = {
+ div0: () => new FormulaError('#DIV/0!'),
+ value: (why?: string) => new FormulaError('#VALUE!', why),
+ name: (n: string) => new FormulaError('#NAME?', `unknown name "${n}"`),
+ cycle: () => new FormulaError('#CYCLE!'),
+ na: () => new FormulaError('#N/A'),
+}
+export const isErr = (v: unknown): v is FormulaError => v instanceof FormulaError
+
+// --- lexer ------------------------------------------------------------------
+
+type Tok =
+ | { t: 'num'; v: number } | { t: 'str'; v: string } | { t: 'id'; v: string }
+ | { t: 'op'; v: string } | { t: 'punc'; v: string }
+
+function lex(src: string): Tok[] {
+ const out: Tok[] = []
+ let i = 0
+ const isIdStart = (c: string) => /[A-Za-z_]/.test(c)
+ const isId = (c: string) => /[A-Za-z0-9_.]/.test(c)
+ while (i < src.length) {
+ const c = src[i]
+ if (/\s/.test(c)) { i++; continue }
+ if (/[0-9]/.test(c) || (c === '.' && /[0-9]/.test(src[i + 1] ?? ''))) {
+ let j = i
+ while (j < src.length && /[0-9.]/.test(src[j])) j++
+ out.push({ t: 'num', v: Number(src.slice(i, j)) }); i = j; continue
+ }
+ if (c === '"') {
+ let j = i + 1, s = ''
+ while (j < src.length && src[j] !== '"') {
+ if (src[j] === '"' && src[j + 1] === '"') { s += '"'; j += 2; continue }
+ s += src[j++]
+ }
+ out.push({ t: 'str', v: s }); i = j + 1; continue
+ }
+ // [Bracketed Name] — the only way to reference a column whose name has spaces
+ if (c === '[') {
+ const j = src.indexOf(']', i)
+ if (j < 0) { out.push({ t: 'id', v: src.slice(i + 1) }); i = src.length; continue }
+ out.push({ t: 'id', v: src.slice(i + 1, j) }); i = j + 1; continue
+ }
+ if (isIdStart(c)) {
+ let j = i
+ while (j < src.length && isId(src[j])) j++
+ out.push({ t: 'id', v: src.slice(i, j) }); i = j; continue
+ }
+ const two = src.slice(i, i + 2)
+ if (two === '<=' || two === '>=' || two === '<>') { out.push({ t: 'op', v: two }); i += 2; continue }
+ if ('+-*/^&=<>'.includes(c)) { out.push({ t: 'op', v: c }); i++; continue }
+ if ('(),'.includes(c)) { out.push({ t: 'punc', v: c }); i++; continue }
+ i++ // anything else is skipped rather than fatal
+ }
+ return out
+}
+
+// --- parser (precedence climbing) -------------------------------------------
+
+type Node =
+ | { k: 'lit'; v: Cell }
+ | { k: 'ref'; name: string }
+ | { k: 'call'; name: string; args: Node[] }
+ | { k: 'bin'; op: string; l: Node; r: Node }
+ | { k: 'neg'; e: Node }
+
+const PREC: Record<string, number> = {
+ '=': 1, '<>': 1, '<': 1, '>': 1, '<=': 1, '>=': 1,
+ '&': 2, '+': 3, '-': 3, '*': 4, '/': 4, '^': 5,
+}
+
+function parse(src: string): Node {
+ const toks = lex(src)
+ let p = 0
+ const peek = () => toks[p]
+ const eat = () => toks[p++]
+
+ function primary(): Node {
+ const tk = eat()
+ if (!tk) return { k: 'lit', v: ERR.value('empty expression') }
+ if (tk.t === 'num') return { k: 'lit', v: tk.v }
+ if (tk.t === 'str') return { k: 'lit', v: tk.v }
+ if (tk.t === 'op' && tk.v === '-') return { k: 'neg', e: primary() }
+ if (tk.t === 'op' && tk.v === '+') return primary()
+ if (tk.t === 'punc' && tk.v === '(') {
+ const e = expr(0)
+ if (peek()?.t === 'punc' && peek()!.v === ')') eat()
+ return e
+ }
+ if (tk.t === 'id') {
+ if (peek()?.t === 'punc' && peek()!.v === '(') {
+ eat()
+ const args: Node[] = []
+ if (!(peek()?.t === 'punc' && peek()!.v === ')')) {
+ for (;;) {
+ args.push(expr(0))
+ if (peek()?.t === 'punc' && peek()!.v === ',') { eat(); continue }
+ break
+ }
+ }
+ if (peek()?.t === 'punc' && peek()!.v === ')') eat()
+ return { k: 'call', name: tk.v.toUpperCase(), args }
+ }
+ const up = tk.v.toUpperCase()
+ if (up === 'TRUE') return { k: 'lit', v: true }
+ if (up === 'FALSE') return { k: 'lit', v: false }
+ return { k: 'ref', name: tk.v }
+ }
+ return { k: 'lit', v: ERR.value() }
+ }
+
+ function expr(min: number): Node {
+ let left = primary()
+ for (;;) {
+ const tk = peek()
+ if (!tk || tk.t !== 'op') break
+ const prec = PREC[tk.v]
+ if (prec === undefined || prec < min) break
+ eat()
+ // ^ is right-associative, everything else left
+ const right = expr(tk.v === '^' ? prec : prec + 1)
+ left = { k: 'bin', op: tk.v, l: left, r: right }
+ }
+ return left
+ }
+ return expr(0)
+}
+
+/** Column names an expression depends on — the edges of the recalc graph. */
+export function dependencies(src: string): string[] {
+ const out = new Set<string>()
+ const walk = (n: Node): void => {
+ if (n.k === 'ref') out.add(n.name)
+ else if (n.k === 'bin') { walk(n.l); walk(n.r) }
+ else if (n.k === 'neg') walk(n.e)
+ else if (n.k === 'call') n.args.forEach(walk)
+ }
+ walk(parse(src))
+ return [...out]
+}
+
+// --- coercion ---------------------------------------------------------------
+
+const num = (v: Cell): number | FormulaError => {
+ if (isErr(v)) return v
+ if (v == null || v === '') return 0
+ if (typeof v === 'number') return v
+ if (typeof v === 'boolean') return v ? 1 : 0
+ const n = Number(String(v).replace(/[,\s£$€¥%]/g, ''))
+ return Number.isFinite(n) ? n : ERR.value(`"${v}" is not a number`)
+}
+const str = (v: Cell): string => (v == null ? '' : isErr(v) ? v.code : String(v))
+const bool = (v: Cell): boolean => {
+ if (isErr(v)) return false
+ if (typeof v === 'boolean') return v
+ if (typeof v === 'number') return v !== 0
+ return String(v ?? '').toLowerCase() === 'true'
+}
+
+// --- the function library ---------------------------------------------------
+// Aggregates take a whole column and return a scalar; everything else is
+// per row. The split is what lets `Value / SUM(Value)` work.
+
+const numbersIn = (v: Vec): number[] =>
+ v.map(num).filter((x): x is number => typeof x === 'number')
+
+const AGG: Record<string, (v: Vec) => Cell> = {
+ SUM: (v) => numbersIn(v).reduce((a, b) => a + b, 0),
+ AVERAGE: (v) => { const n = numbersIn(v); return n.length ? n.reduce((a, b) => a + b, 0) / n.length : ERR.div0() },
+ MIN: (v) => { const n = numbersIn(v); return n.length ? Math.min(...n) : 0 },
+ MAX: (v) => { const n = numbersIn(v); return n.length ? Math.max(...n) : 0 },
+ COUNT: (v) => numbersIn(v).length,
+ COUNTA: (v) => v.filter((x) => x != null && x !== '').length,
+ COUNTBLANK: (v) => v.filter((x) => x == null || x === '').length,
+ MEDIAN: (v) => {
+ const n = numbersIn(v).sort((a, b) => a - b)
+ if (!n.length) return ERR.div0()
+ const m = n.length >> 1
+ return n.length % 2 ? n[m] : (n[m - 1] + n[m]) / 2
+ },
+ STDEV: (v) => {
+ const n = numbersIn(v)
+ if (n.length < 2) return ERR.div0()
+ const mu = n.reduce((a, b) => a + b, 0) / n.length
+ return Math.sqrt(n.reduce((a, b) => a + (b - mu) ** 2, 0) / (n.length - 1))
+ },
+ PRODUCT: (v) => numbersIn(v).reduce((a, b) => a * b, 1),
+}
+AGG.AVG = AGG.AVERAGE
+
+/** SUMIF/COUNTIF/AVERAGEIF — high-frequency, so worth having in v1. */
+const CONDITIONAL = new Set(['SUMIF', 'COUNTIF', 'AVERAGEIF'])
+
+const round = (x: number, dp: number) => {
+ const f = 10 ** dp
+ return Math.round((x + Number.EPSILON * Math.sign(x)) * f) / f
+}
+
+const SCALAR: Record<string, (a: Cell[]) => Cell> = {
+ IF: (a) => (bool(a[0]) ? a[1] ?? true : a[2] ?? false),
+ AND: (a) => a.every(bool),
+ OR: (a) => a.some(bool),
+ NOT: (a) => !bool(a[0]),
+ IFERROR: (a) => (isErr(a[0]) ? a[1] ?? '' : a[0]),
+ ISBLANK: (a) => a[0] == null || a[0] === '',
+ ISNUMBER: (a) => typeof a[0] === 'number',
+ ISTEXT: (a) => typeof a[0] === 'string',
+ ISERROR: (a) => isErr(a[0]),
+ ABS: (a) => { const n = num(a[0]); return isErr(n) ? n : Math.abs(n) },
+ ROUND: (a) => { const n = num(a[0]); const d = num(a[1] ?? 0); return isErr(n) ? n : isErr(d) ? d : round(n, d) },
+ ROUNDUP: (a) => { const n = num(a[0]); const d = num(a[1] ?? 0); if (isErr(n)) return n; const f = 10 ** (isErr(d) ? 0 : d); return Math.ceil(n * f) / f },
+ ROUNDDOWN: (a) => { const n = num(a[0]); const d = num(a[1] ?? 0); if (isErr(n)) return n; const f = 10 ** (isErr(d) ? 0 : d); return Math.floor(n * f) / f },
+ INT: (a) => { const n = num(a[0]); return isErr(n) ? n : Math.floor(n) },
+ CEILING: (a) => { const n = num(a[0]); return isErr(n) ? n : Math.ceil(n) },
+ FLOOR: (a) => { const n = num(a[0]); return isErr(n) ? n : Math.floor(n) },
+ SIGN: (a) => { const n = num(a[0]); return isErr(n) ? n : Math.sign(n) },
+ SQRT: (a) => { const n = num(a[0]); return isErr(n) ? n : n < 0 ? ERR.value('negative') : Math.sqrt(n) },
+ POWER: (a) => { const b = num(a[0]); const e = num(a[1]); return isErr(b) ? b : isErr(e) ? e : b ** e },
+ MOD: (a) => { const x = num(a[0]); const y = num(a[1]); if (isErr(x)) return x; if (isErr(y)) return y; return y === 0 ? ERR.div0() : x % y },
+ EXP: (a) => { const n = num(a[0]); return isErr(n) ? n : Math.exp(n) },
+ LN: (a) => { const n = num(a[0]); return isErr(n) ? n : n <= 0 ? ERR.value() : Math.log(n) },
+ LOG10: (a) => { const n = num(a[0]); return isErr(n) ? n : n <= 0 ? ERR.value() : Math.log10(n) },
+ CONCAT: (a) => a.map(str).join(''),
+ CONCATENATE: (a) => a.map(str).join(''),
+ LEN: (a) => str(a[0]).length,
+ LEFT: (a) => { const n = num(a[1] ?? 1); return str(a[0]).slice(0, isErr(n) ? 1 : n) },
+ RIGHT: (a) => { const n = num(a[1] ?? 1); return isErr(n) ? n : n <= 0 ? '' : str(a[0]).slice(-n) },
+ MID: (a) => { const s = num(a[1] ?? 1); const l = num(a[2] ?? 0); return isErr(s) ? s : isErr(l) ? l : str(a[0]).slice(s - 1, s - 1 + l) },
+ LOWER: (a) => str(a[0]).toLowerCase(),
+ UPPER: (a) => str(a[0]).toUpperCase(),
+ TRIM: (a) => str(a[0]).trim().replace(/\s+/g, ' '),
+ SUBSTITUTE: (a) => str(a[0]).split(str(a[1])).join(str(a[2])),
+ FIND: (a) => { const i = str(a[1]).indexOf(str(a[0])); return i < 0 ? ERR.na() : i + 1 },
+ YEAR: (a) => Number(str(a[0]).slice(0, 4)) || ERR.value(),
+ MONTH: (a) => Number(str(a[0]).slice(5, 7)) || ERR.value(),
+ DAY: (a) => Number(str(a[0]).slice(8, 10)) || ERR.value(),
+}
+
+/**
+ * Volatiles. TODAY() is by far the most common one on earth, and banning it —
+ * which two of the three design proposals did — sends people to hard-coding a
+ * date, which is strictly worse. It is FROZEN at commit instead: the value is
+ * stamped into the document so the file shows the same number to everybody who
+ * opens it, and re-running is an explicit act.
+ */
+export const VOLATILE = new Set(['TODAY', 'NOW'])
+
+export interface EvalCtx {
+ /** column name (or id) → its values */
+ cols: Map<string, Vec>
+ n: number
+ /** frozen at commit; a document opened in 2030 shows the number it was saved with */
+ now?: string
+}
+
+function evalNode(node: Node, ctx: EvalCtx): Cell | Vec {
+ switch (node.k) {
+ case 'lit': return node.v
+ case 'ref': {
+ const v = ctx.cols.get(node.name) ?? ctx.cols.get(node.name.toLowerCase())
+ return v ?? ERR.name(node.name)
+ }
+ case 'neg': {
+ const e = evalNode(node.e, ctx)
+ return map1(e, (x) => { const n = num(x); return isErr(n) ? n : -n })
+ }
+ case 'bin': return binop(node.op, evalNode(node.l, ctx), evalNode(node.r, ctx))
+ case 'call': return callFn(node, ctx)
+ }
+}
+
+const isVec = (v: Cell | Vec): v is Vec => Array.isArray(v)
+const at = (v: Cell | Vec, i: number): Cell => (isVec(v) ? v[i] ?? null : v)
+
+function map1(a: Cell | Vec, f: (x: Cell) => Cell): Cell | Vec {
+ if (!isVec(a)) return f(a)
+ return a.map(f)
+}
+
+function binop(op: string, l: Cell | Vec, r: Cell | Vec): Cell | Vec {
+ const n = isVec(l) ? l.length : isVec(r) ? (r as Vec).length : -1
+ const one = (x: Cell, y: Cell): Cell => {
+ if (isErr(x)) return x
+ if (isErr(y)) return y
+ if (op === '&') return str(x) + str(y)
+ if (op === '=') return looseEq(x, y)
+ if (op === '<>') return !looseEq(x, y)
+ if (op === '<' || op === '>' || op === '<=' || op === '>=') {
+ const a = typeof x === 'string' && typeof y === 'string' ? x : num(x)
+ const b = typeof x === 'string' && typeof y === 'string' ? y : num(y)
+ if (isErr(a)) return a
+ if (isErr(b)) return b
+ return op === '<' ? a < b : op === '>' ? a > b : op === '<=' ? a <= b : a >= b
+ }
+ const a = num(x); if (isErr(a)) return a
+ const b = num(y); if (isErr(b)) return b
+ switch (op) {
+ case '+': return a + b
+ case '-': return a - b
+ case '*': return a * b
+ case '/': return b === 0 ? ERR.div0() : a / b
+ case '^': return a ** b
+ default: return ERR.value(`unknown operator ${op}`)
+ }
+ }
+ if (n < 0) return one(l as Cell, r as Cell)
+ return Array.from({ length: n }, (_, i) => one(at(l, i), at(r, i)))
+}
+
+const looseEq = (x: Cell, y: Cell): boolean => {
+ if (typeof x === 'number' || typeof y === 'number') {
+ const a = num(x); const b = num(y)
+ return !isErr(a) && !isErr(b) && a === b
+ }
+ return String(x ?? '').toLowerCase() === String(y ?? '').toLowerCase()
+}
+
+/** `">100"`, `"North"`, `42` — the criteria form SUMIF/COUNTIF take. */
+function matches(v: Cell, crit: Cell): boolean {
+ const c = str(crit).trim()
+ const m = c.match(/^(<=|>=|<>|<|>|=)\s*(.*)$/)
+ if (!m) return looseEq(v, crit)
+ const [, op, rest] = m
+ const target: Cell = rest === '' ? null : Number.isFinite(Number(rest)) ? Number(rest) : rest
+ const r = binop(op === '=' ? '=' : op, v, target)
+ return bool(r as Cell)
+}
+
+function callFn(node: Node & { k: 'call' }, ctx: EvalCtx): Cell | Vec {
+ const name = node.name
+
+ if (name === 'TODAY' || name === 'NOW') {
+ const iso = ctx.now ?? new Date().toISOString()
+ return name === 'TODAY' ? iso.slice(0, 10) : iso
+ }
+ if (AGG[name]) {
+ const v = evalNode(node.args[0], ctx)
+ return AGG[name](isVec(v) ? v : [v])
+ }
+ if (CONDITIONAL.has(name)) {
+ const range = evalNode(node.args[0], ctx)
+ const crit = evalNode(node.args[1], ctx)
+ const sumRange = node.args[2] ? evalNode(node.args[2], ctx) : range
+ const rv = isVec(range) ? range : [range]
+ const sv = isVec(sumRange) ? sumRange : [sumRange]
+ const keep: number[] = []
+ rv.forEach((x, i) => { if (matches(x, at(crit, i))) keep.push(i) })
+ if (name === 'COUNTIF') return keep.length
+ const vals = keep.map((i) => num(sv[i] ?? null)).filter((x): x is number => typeof x === 'number')
+ if (name === 'SUMIF') return vals.reduce((a, b) => a + b, 0)
+ return vals.length ? vals.reduce((a, b) => a + b, 0) / vals.length : ERR.div0()
+ }
+ const fn = SCALAR[name]
+ if (!fn) return ERR.name(name)
+
+ const args = node.args.map((a) => evalNode(a, ctx))
+ // widest vector argument decides the result's length; all-scalar stays scalar
+ let width = -1
+ for (const a of args) if (isVec(a)) width = Math.max(width, a.length)
+ if (width < 0) return fn(args as Cell[])
+ return Array.from({ length: width }, (_, i) => fn(args.map((a) => at(a, i))))
+}
+
+/** Evaluate one column expression over `n` rows. Never throws. */
+export function evaluate(src: string, ctx: EvalCtx): Vec {
+ let node: Node
+ try { node = parse(src) } catch { return Array.from({ length: ctx.n }, () => ERR.value('could not parse')) }
+ let out: Cell | Vec
+ try { out = evalNode(node, ctx) } catch (e) {
+ out = ERR.value(e instanceof Error ? e.message : String(e))
+ }
+ return isVec(out) ? out : Array.from({ length: ctx.n }, () => out as Cell)
+}
+
+// --- recalculation ----------------------------------------------------------
+
+export interface RecalcResult {
+ /** colId → computed values, for every column that has a formula */
+ values: Map<string, Vec>
+ /** columns in a cycle — reported, never silently zeroed */
+ cycles: string[]
+ order: string[]
+}
+
+/**
+ * Recompute every formula column in dependency order.
+ *
+ * Kahn's algorithm over COLUMNS. Anything left when the queue drains is in a
+ * cycle, and gets `#CYCLE!` rather than a plausible number — measured at 9 ms
+ * for a 1M-node graph, so at twelve nodes the sort is free.
+ */
+export function recalc(sheet: TableSheet, now?: string): RecalcResult {
+ const n = sheet.rids.reduce((a, [, c]) => a + c, 0)
+
+ // both id and name resolve, so `[Unit price]` and `unit_price` both work
+ const base = new Map<string, Vec>()
+ const put = (k: string, v: Vec) => { base.set(k, v); base.set(k.toLowerCase(), v) }
+ for (const c of sheet.columns) {
+ if (c.formula) continue
+ const d = sheet.data[c.id]
+ const vals: Vec = Array.from({ length: n }, (_, i) => readCell(d, i) as Cell)
+ put(c.id, vals); put(c.name, vals)
+ }
+
+ const formulas = sheet.columns.filter((c) => c.formula)
+ const byKey = new Map<string, string>() // id or name (lowercased) -> colId
+ for (const c of formulas) { byKey.set(c.id.toLowerCase(), c.id); byKey.set(c.name.toLowerCase(), c.id) }
+
+ const deps = new Map<string, Set<string>>()
+ for (const c of formulas) {
+ const d = new Set<string>()
+ for (const ref of dependencies(c.formula!)) {
+ const target = byKey.get(ref.toLowerCase())
+ // INCLUDING itself. `a = a + 1` is a circular reference, and excluding
+ // self-edges gave it indegree 0 — so it drained from the queue, computed
+ // against its own stale values, and produced a number.
+ if (target) d.add(target)
+ }
+ deps.set(c.id, d)
+ }
+
+ // Kahn
+ const indeg = new Map([...deps].map(([k, v]) => [k, v.size]))
+ const queue = [...indeg].filter(([, d]) => d === 0).map(([k]) => k)
+ const order: string[] = []
+ while (queue.length) {
+ const id = queue.shift()!
+ order.push(id)
+ for (const [other, d] of deps) {
+ if (d.has(id)) {
+ d.delete(id)
+ const left = (indeg.get(other) ?? 1) - 1
+ indeg.set(other, left)
+ if (left === 0) queue.push(other)
+ }
+ }
+ }
+ const cycles = formulas.map((c) => c.id).filter((id) => !order.includes(id))
+
+ const values = new Map<string, Vec>()
+ const ctx: EvalCtx = { cols: base, n, now }
+ for (const id of order) {
+ const col = formulas.find((c) => c.id === id)!
+ const v = evaluate(col.formula!, ctx)
+ values.set(id, v)
+ put(id, v); put(col.name, v)
+ }
+ for (const id of cycles) {
+ values.set(id, Array.from({ length: n }, () => ERR.cycle()))
+ }
+ return { values, cycles, order }
+}
+
+/** Every function name this build knows — the agent surface needs to say. */
+export const FUNCTIONS: string[] = [
+ ...Object.keys(AGG), ...CONDITIONAL, ...Object.keys(SCALAR), ...VOLATILE,
+].sort()
diff --git a/dash/src/grid.ts b/dash/src/grid.ts
index be9d4e75..8b56cdb2 100644
--- a/dash/src/grid.ts
+++ b/dash/src/grid.ts
@@ -22,6 +22,7 @@
import { formatValue, alignFor, TYPE_LABEL } from './format.ts'
import type { Column, ColumnType, TableSheet } from './model.ts'
import { readCell, type Store } from './store.ts'
+import { recalc, isErr, type Vec } from './formula.ts'
const ROW_H = 30
const OVERSCAN = 8
@@ -64,8 +65,15 @@ export class Grid {
private table!: HTMLElement
private editing: { rid: number; col: string } | null = null
private sort: { col: string; dir: 'asc' | 'desc' } | null = null
+ /** formula columns, recomputed on every document change. Never stored: the
+ * document holds the EXPRESSION, and the values are derived from it, so a
+ * file cannot carry a number that disagrees with its own formula. */
+ computed = new Map<string, Vec>()
+ cycles: string[] = []
/** set by the app so a type change can be routed through one place */
onRetype?: (col: Column) => void
+ /** double-clicking a computed cell edits the FORMULA, not the value */
+ onEditFormula?: (col: Column) => void
constructor(opts: GridHost) {
this.host = opts.el
@@ -124,7 +132,8 @@ export class Grid {
return `${cols(s).map((c) => {
const arrow = this.sort?.col === c.id ? (this.sort.dir === 'asc' ? ' ▲' : ' ▼') : ''
return `<div class="dg-cell dg-h" style="width:${c.w ?? 130}px" data-col="${c.id}">` +
- `<span class="dg-name" title="${esc(c.name)}">${esc(c.name)}${arrow}</span>` +
+ `<span class="dg-name" title="${esc(c.formula ? `= ${c.formula}` : c.name)}">${esc(c.name)}${arrow}</span>` +
+ (c.formula ? `<span class="dg-fx" title="${esc('= ' + c.formula)}">fx</span>` : '') +
`<button class="dg-type" data-retype="${c.id}" title="${esc(TYPE_LABEL[c.type])} — click to change">${esc(TYPE_LABEL[c.type])}</button>` +
(c.failed ? `<span class="dg-warn" title="${c.failed} value(s) could not be read as ${esc(TYPE_LABEL[c.type])}">!</span>` : '') +
`</div>`
@@ -139,10 +148,11 @@ export class Grid {
const spec = s.totals?.[c.id]
if (!spec) return `<div class="dg-cell" style="width:${c.w ?? 130}px"></div>`
const data = s.data[c.id]
+ const comp = this.computed.get(c.id)
let acc = 0
let seen = 0
for (let i = 0; i < n; i++) {
- const v = readCell(data, i)
+ const v = comp ? comp[i] : readCell(data, i)
if (typeof v !== 'number') continue
seen++
if (spec === 'min') acc = seen === 1 ? v : Math.min(acc, v)
@@ -158,6 +168,13 @@ export class Grid {
paint(): void {
const s = this.sheet
const n = rowCount(s)
+ if (s.columns.some((c) => c.formula)) {
+ // `now` is frozen from the document so TODAY() shows every reader the
+ // same date rather than each reader's own
+ const r = recalc(s, this.store.doc.modified)
+ this.computed = r.values
+ this.cycles = r.cycles
+ } else if (this.computed.size) { this.computed = new Map(); this.cycles = [] }
this.table.style.height = `${n * ROW_H}px`
// Only the visible slice exists. 100k x 6 would be 600,000 nodes, and that
@@ -173,10 +190,15 @@ export class Grid {
body.push(`<div class="dg-row" data-rid="${rid}" style="top:${i * ROW_H}px">` +
cols(s).map((c) => {
const over = s.cells?.[`${c.id}:${rid}`]
- const v = over && 'v' in over ? over.v : readCell(s.data[c.id], r)
+ const comp = this.computed.get(c.id)
+ const v = comp ? comp[r]
+ : over && 'v' in over ? over.v
+ : readCell(s.data[c.id], r)
const note = over?.note ? ' dg-noted' : ''
- return `<div class="dg-cell${note}" data-col="${c.id}" ` +
- `style="width:${c.w ?? 130}px;text-align:${alignFor(c.type)}">${esc(formatValue(v, c))}</div>`
+ const bad = isErr(v) ? ' dg-err' : ''
+ const shown = isErr(v) ? String(v) : formatValue(v, c)
+ return `<div class="dg-cell${note}${bad}" data-col="${c.id}" ` +
+ `style="width:${c.w ?? 130}px;text-align:${alignFor(c.type)}">${esc(shown)}</div>`
}).join('') + '</div>')
}
this.head.innerHTML = this.header()
@@ -227,6 +249,9 @@ export class Grid {
const s = this.sheet
const col = s.columns.find((c) => c.id === colId)
if (!col || this.store.readOnly) return
+ // a computed column is defined by its expression; typing over one cell
+ // would be a value the formula immediately contradicts
+ if (col.formula) { this.onEditFormula?.(col); return }
this.editing = { rid, col: colId }
const r = dataRow(s, rid)
const raw = readCell(s.data[colId], r)
diff --git a/dash/src/main.ts b/dash/src/main.ts
index 2ee2e2aa..447dc697 100644
--- a/dash/src/main.ts
+++ b/dash/src/main.ts
@@ -39,6 +39,8 @@ import { starterDoc } from './starter.ts'
import { Grid } from './grid.ts'
import { importDelimited } from './import.ts'
import { TYPE_LABEL } from './format.ts'
+import { defaultBinding, renderChart, type ChartBinding } from './chart.ts'
+import { FUNCTIONS } from './formula.ts'
configureApp({
appId: 'bento-dash',
@@ -136,6 +138,8 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version'): vo
`<span class="dx-mark">bento<span>/</span>dash</span>` +
`<input class="dx-title" value="">` +
`<span class="dx-dirty" hidden>•</span>` +
+ `<button class="dx-btn" data-act="formula">${t('+ Formula column')}</button>` +
+ `<button class="dx-btn" data-act="chart">${t('+ Chart')}</button>` +
`<button class="dx-btn" data-act="import">${t('Import CSV…')}</button>` +
`<button class="dx-btn" data-act="undo">${t('Undo')}</button>` +
`<button class="dx-btn" data-act="export">${t('Export CSV')}</button>` +
@@ -143,7 +147,12 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version'): vo
`<span class="dx-ver">v${APP_VERSION}</span>` +
`</header>` +
`<div class="dx-findings" hidden></div>` +
- `<div class="dx-grid"></div>`
+ `<div class="dx-body"><div class="dx-grid"></div>` +
+ `<div class="dx-chart" hidden><div class="dx-chart-head">` +
+ `<span class="dx-chart-title"></span>` +
+ `<button class="dx-btn dx-chart-kind">${t('Bar')}</button>` +
+ `<button class="dx-btn dx-chart-close" title="${t('Hide chart')}">✕</button>` +
+ `</div><div class="dx-chart-body"></div></div></div>`
const titleEl = app.querySelector<HTMLInputElement>('.dx-title')!
const dirtyEl = app.querySelector<HTMLElement>('.dx-dirty')!
@@ -153,6 +162,44 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version'): vo
const grid = new Grid({ el: app.querySelector<HTMLElement>('.dx-grid')!, store, sheetId: doc.sheets[0].id })
grid.onRetype = (col) => retype(store, col)
+ grid.onEditFormula = (col) => editFormula(store, grid, col)
+
+ // --- chart: bound to columns, derived at render, never stored
+ const chartEl = app.querySelector<HTMLElement>('.dx-chart')!
+ const chartBody = app.querySelector<HTMLElement>('.dx-chart-body')!
+ const chartTitle = app.querySelector<HTMLElement>('.dx-chart-title')!
+ const kindBtn = app.querySelector<HTMLElement>('.dx-chart-kind')!
+ let binding: ChartBinding | null = null
+ let teardown: (() => void) | null = null
+ const KINDS: Array<ChartBinding['kind']> = ['bar', 'line', 'pie', 'scatter']
+
+ const drawChart = () => {
+ if (!binding || chartEl.hidden) return
+ teardown?.()
+ const sheet = grid.sheet
+ chartTitle.textContent = `${sheet.columns.find((c) => c.id === binding!.x)?.name ?? ''} · ` +
+ binding.series.map((id) => sheet.columns.find((c) => c.id === id)?.name ?? id).join(', ')
+ kindBtn.textContent = binding.kind[0].toUpperCase() + binding.kind.slice(1)
+ // hand the grid's freshly computed formula columns in, so the chart shows
+ // the numbers on screen rather than the raw columns underneath them
+ teardown = renderChart(chartBody, sheet, binding, grid.computed as Map<string, unknown[]>)
+ }
+ store.on('doc', drawChart)
+ kindBtn.addEventListener('click', () => {
+ if (!binding) return
+ binding.kind = KINDS[(KINDS.indexOf(binding.kind) + 1) % KINDS.length]
+ drawChart()
+ })
+ app.querySelector('.dx-chart-close')!.addEventListener('click', () => {
+ chartEl.hidden = true; teardown?.(); teardown = null
+ })
+ app.querySelector('[data-act="chart"]')!.addEventListener('click', () => {
+ binding = defaultBinding(grid.sheet)
+ if (!binding) { showFindings(findingsEl, [{ message: t('This sheet has no numeric column to chart yet.') }]); return }
+ chartEl.hidden = false
+ drawChart()
+ })
+ app.querySelector('[data-act="formula"]')!.addEventListener('click', () => addFormula(store, grid))
const notes: Notice[] = []
if (frozen) {
@@ -342,3 +389,36 @@ const esc = (s: string): string =>
// and so a reader of this file sees both halves of the rule in one place
void DOC_BUDGET_FSA
void DOC_BUDGET_DOWNLOAD
+
+// --- formulas ---------------------------------------------------------------
+
+/**
+ * Add a computed column. One expression for the whole column, so inserting a
+ * row changes nothing and there is no range to fall out of date.
+ */
+function addFormula(store: Store, grid: Grid): void {
+ const sheet = grid.sheet
+ const names = sheet.columns.map((c) => (/\s/.test(c.name) ? `[${c.name}]` : c.name)).join(', ')
+ const expr = window.prompt(
+ `${t('Formula for a new column.')}\n\n${t('Columns')}: ${names}\n${t('Functions')}: ${FUNCTIONS.slice(0, 24).join(' ')}…\n\n` +
+ `${t('Example')}: Value * Probability`,
+ 'Value * Probability',
+ )
+ if (!expr) return
+ const name = window.prompt(t('Column name'), t('Computed')) || t('Computed')
+ const id = `f-${Math.floor(Date.now() % 1e8).toString(36)}`
+ store.commit({
+ op: 'addColumn', sheet: sheet.id,
+ column: { id, name, type: 'number', formula: expr },
+ })
+}
+
+/** Double-clicking a computed cell edits the expression that produced it. */
+function editFormula(store: Store, grid: Grid, col: Column): void {
+ const expr = window.prompt(`${t('Formula for')} "${col.name}"`, col.formula ?? '')
+ if (expr === null) return
+ store.commit({
+ op: 'setColumn', sheet: grid.sheet.id, col: col.id,
+ patch: expr.trim() ? { formula: expr } : { formula: undefined },
+ })
+}
diff --git a/dash/src/store.ts b/dash/src/store.ts
index 2e7aff24..ff70d2e1 100644
--- a/dash/src/store.ts
+++ b/dash/src/store.ts
@@ -28,7 +28,7 @@
// agent API. That is why this lands at commit one: retrofitting op-minting
// means rewriting the store.
-import type { CellOverride, ColumnData, DashDoc, Measure, Sheet, Step, TableSheet } from './model.ts'
+import type { CellOverride, Column, ColumnData, DashDoc, Measure, Sheet, Step, TableSheet } from './model.ts'
type Listener = () => void
export type StoreEvent = 'doc' | 'view' | 'selection'
@@ -79,6 +79,12 @@ export type Patch =
}
| { op: 'deleteRows'; sheet: string; rids: number[] }
| { op: 'setColumn'; sheet: string; col: string; patch: Record<string, unknown> }
+ /** `at` is the position; omitted appends. `data` is omitted for a FORMULA
+ * column, which has no stored values — its numbers are derived from its
+ * expression, so storing them would let a file carry a number that
+ * disagrees with the formula that produced it. */
+ | { op: 'addColumn'; sheet: string; column: Column; at?: number; data?: ColumnData }
+ | { op: 'removeColumn'; sheet: string; col: string }
| { op: 'reorderColumns'; sheet: string; order: string[] }
| { op: 'setMeasure'; name: string; measure?: Measure; dropEmpty?: boolean }
| { op: 'setTitle'; title: string }
@@ -301,6 +307,32 @@ export function applyPatch(doc: DashDoc, p: Patch): { inverse: Patch; touched: T
}
}
+ case 'addColumn': {
+ const sheet = table(doc, p.sheet)
+ const at = p.at ?? sheet.columns.length
+ sheet.columns.splice(at, 0, p.column)
+ if (p.data) sheet.data[p.column.id] = p.data
+ return {
+ inverse: { op: 'removeColumn', sheet: p.sheet, col: p.column.id },
+ touched: { sheet: p.sheet, cols: [p.column.id], structural: true },
+ }
+ }
+
+ case 'removeColumn': {
+ const sheet = table(doc, p.sheet)
+ const at = sheet.columns.findIndex((c) => c.id === p.col)
+ if (at < 0) throw new Error(`no column ${p.col}`)
+ const [column] = sheet.columns.splice(at, 1)
+ const data = sheet.data[p.col]
+ delete sheet.data[p.col]
+ // the inverse carries the column AND its data, or undoing a delete
+ // returns an empty column — the same failure deleteRows had
+ return {
+ inverse: { op: 'addColumn', sheet: p.sheet, column, at, ...(data ? { data } : {}) },
+ touched: { sheet: p.sheet, cols: [p.col], structural: true },
+ }
+ }
+
case 'setColumn': {
const sheet = table(doc, p.sheet)
const col = sheet.columns.find((c) => c.id === p.col)
diff --git a/dash/src/styles.css b/dash/src/styles.css
index c808ad41..353034c5 100644
--- a/dash/src/styles.css
+++ b/dash/src/styles.css
@@ -87,8 +87,45 @@ html, body {
.dx-findings .dx-f { display: flex; gap: 8px; align-items: baseline; }
.dx-findings .dx-dot { color: var(--accent); }
-/* ————— grid ————— */
-.dx-grid { flex: 1 1 auto; min-height: 0; position: relative; }
+/* ————— body: grid, and the chart beside it ————— */
+.dx-body { flex: 1 1 auto; min-height: 0; display: flex; }
+.dx-grid { flex: 1 1 auto; min-width: 0; min-height: 0; position: relative; }
+
+.dx-chart {
+ flex: 0 0 clamp(280px, 34%, 520px);
+ border-left: 1px solid var(--line);
+ display: flex;
+ flex-direction: column;
+ background: #fff;
+ min-width: 0;
+}
+.dx-chart[hidden] { display: none; }
+.dx-chart-head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 10px;
+ border-bottom: 1px solid var(--line);
+ background: var(--panel);
+}
+.dx-chart-title {
+ flex: 1 1 auto;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--muted);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.dx-chart-head .dx-btn { padding: 3px 8px; font-size: 12px; }
+.dx-chart-body { flex: 1 1 auto; min-height: 0; padding: 6px; }
+.dx-chart-body svg { display: block; width: 100%; height: 100%; }
+
+/* stack on a phone rather than squeezing both */
+@media (max-width: 760px) {
+ .dx-body { flex-direction: column; }
+ .dx-chart { flex: 0 0 45%; border-left: 0; border-top: 1px solid var(--line); }
+}
.dg-scroll { position: absolute; inset: 0; overflow: auto; }
.dg-table { position: relative; min-width: max-content; }
/* the sizer is the ONLY absolutely-positioned region: header and totals stay in
@@ -154,6 +191,15 @@ html, body {
flex: 0 0 auto;
cursor: help;
}
+.dg-err { color: #b91c1c; background: #fef2f2; font-weight: 600; }
+.dg-fx {
+ font: 600 9px/1.6 inherit;
+ color: var(--accent);
+ border: 1px solid var(--accent);
+ border-radius: 4px;
+ padding: 0 3px;
+ flex: 0 0 auto;
+}
.dg-agg { color: var(--muted); font-weight: 400; font-size: 11px; text-transform: uppercase; }
/* ————— gate: an unreadable document, and the way back out of it ————— */
diff --git a/scripts/test-dash-chart.ts b/scripts/test-dash-chart.ts
new file mode 100644
index 00000000..2d696789
--- /dev/null
+++ b/scripts/test-dash-chart.ts
@@ -0,0 +1,131 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/dash chart-binding rig.
+//
+// node scripts/test-dash-chart.ts
+//
+// WHAT THIS PROVES. A tile NAMES a sheet and columns; the series arrays are
+// derived at render and never stored. That is what stops a chart disagreeing
+// with the table beside it — slides learned it the expensive way. So the whole
+// surface worth testing is the DERIVATION, and it is pure, so it is testable
+// here rather than by squinting at an SVG.
+//
+// The failure that matters most is a missing value drawn as a zero. charts-lite
+// coerces with `num(v, 0)`, so a gap becomes a plunge to the axis: "we sold
+// nothing in March" instead of "we do not know about March". One is a fact and
+// the other is an absence, and a chart must not turn the second into the first.
+
+import { optionFor, defaultBinding, type ChartBinding } from '../dash/src/chart.ts'
+import type { TableSheet } from '../dash/src/model.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+const sheet = (): TableSheet => ({
+ id: 'sh', name: 'S', kind: 'table',
+ rids: [[1, 6]],
+ columns: [
+ { id: 'region', name: 'Region', type: 'text' },
+ { id: 'value', name: 'Value', type: 'money' },
+ { id: 'prob', name: 'Probability', type: 'percent' },
+ ],
+ data: {
+ region: { enc: 'dict', dict: ['North', 'South'], idx: [0, 1, 0, 1, 0, 1] },
+ value: { enc: 'raw', v: [10, 20, 30, 40, null, 60] },
+ prob: { enc: 'raw', v: [1, 0.5, 1, 0.25, 1, 0.5] },
+ },
+ steps: [],
+})
+
+const S = (o: Record<string, unknown>) => o.series as Array<{ name: string; data: unknown[] }>
+
+// ------------------------------------------------------------- aggregation
+{
+ const o = optionFor(sheet(), { x: 'region', series: ['value'], kind: 'bar', aggregate: 'sum' })
+ ok(JSON.stringify((o.xAxis as { data: string[] }).data) === JSON.stringify(['North', 'South']),
+ 'rows group by the x column')
+ // North = 10+30 (+null skipped) = 40; South = 20+40+60 = 120
+ ok(JSON.stringify(S(o)[0].data) === JSON.stringify([40, 120]), 'and the series sums each group')
+ ok(S(o)[0].name === 'Value', 'the series is named after the column, not its id')
+}
+{
+ const o = optionFor(sheet(), { x: 'region', series: ['value'], kind: 'bar', aggregate: 'avg' })
+ ok(JSON.stringify(S(o)[0].data) === JSON.stringify([20, 40]),
+ 'avg divides by the values PRESENT, not by the row count (North: 40/2, not 40/3)')
+}
+{
+ const o = optionFor(sheet(), { x: 'region', series: ['value'], kind: 'bar', aggregate: 'none' })
+ ok(S(o)[0].data.length === 6, 'aggregate:none charts one point per row')
+}
+
+// ------------------------------------------------- categories keep DATA order
+{
+ const s = sheet()
+ s.data.region = { enc: 'dict', dict: ['Zulu', 'Alpha'], idx: [0, 1, 0, 1, 0, 1] }
+ const o = optionFor(s, { x: 'region', series: ['value'], kind: 'bar', aggregate: 'sum' })
+ ok(JSON.stringify((o.xAxis as { data: string[] }).data) === JSON.stringify(['Zulu', 'Alpha']),
+ 'categories appear in first-seen order, NOT alphabetically — a chart should read like its data')
+}
+
+// ------------------------------------------------ a gap is never a zero
+{
+ const s = sheet()
+ // an entire category with no values at all
+ s.data.region = { enc: 'dict', dict: ['A', 'B'], idx: [0, 1, 0, 1, 0, 1] }
+ s.data.value = { enc: 'raw', v: [10, null, 30, null, 50, null] }
+ const o = optionFor(s, { x: 'region', series: ['value'], kind: 'bar', aggregate: 'sum' })
+ const d = S(o)[0].data
+ ok(d[0] === 90, 'A sums its three values')
+ ok(d[1] === null, 'B has NO values, so it is null — a gap')
+ ok(d[1] !== 0, 'and specifically NOT zero, which would read as "B sold nothing"')
+}
+
+// ------------------------------------------------------ computed columns
+{
+ // a formula column has no stored data; the grid hands its computed values in
+ const s = sheet()
+ s.columns.push({ id: 'w', name: 'Weighted', type: 'money', formula: 'value * prob' })
+ const computed = new Map<string, unknown[]>([['w', [10, 10, 30, 10, 0, 30]]])
+ const o = optionFor(s, { x: 'region', series: ['w'], kind: 'bar', aggregate: 'sum' }, computed)
+ ok(JSON.stringify(S(o)[0].data) === JSON.stringify([40, 50]),
+ 'a formula column charts from the COMPUTED values, which are never stored')
+}
+
+// ------------------------------------------------------------------- pie
+{
+ const o = optionFor(sheet(), { x: 'region', series: ['value'], kind: 'pie', aggregate: 'sum' })
+ const d = S(o)[0].data as Array<{ name: string; value: number }>
+ ok(d.length === 2 && d[0].name === 'North' && d[0].value === 40, 'pie takes {name,value} slices')
+}
+
+// -------------------------------------------------------- default binding
+{
+ const b = defaultBinding(sheet())!
+ ok(b.x === 'region', 'the default x is the first text column')
+ ok(b.series.includes('value'), 'and a numeric column is charted')
+ ok(!b.series.includes('prob'),
+ 'a PERCENT column is excluded: 0-to-1 beside money draws no visible bar, so the legend would name a series the reader cannot see')
+ ok(b.aggregate === 'sum', 'and it groups, because a text x column means repeated categories')
+}
+{
+ // nothing but percentages — then charting them is better than charting nothing
+ const s = sheet()
+ s.columns = s.columns.filter((c) => c.id !== 'value')
+ delete s.data.value
+ ok(defaultBinding(s)!.series.includes('prob'),
+ 'unless percent is ALL there is, in which case it is used')
+}
+{
+ const s = sheet()
+ s.columns = [s.columns[0]]
+ ok(defaultBinding(s) === null, 'a sheet with no numeric column has no default chart')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/scripts/test-dash-formula.ts b/scripts/test-dash-formula.ts
new file mode 100644
index 00000000..2c3390f5
--- /dev/null
+++ b/scripts/test-dash-formula.ts
@@ -0,0 +1,172 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/dash formula rig.
+//
+// node scripts/test-dash-formula.ts
+//
+// WHAT THIS PROVES. A spreadsheet's job is arithmetic, so a wrong answer here
+// is the worst failure the app has — and the dangerous ones are not crashes,
+// they are plausible numbers:
+//
+// 1. AN ERROR THAT BECOMES A ZERO. Divide by zero, reference a name that does
+// not exist, put text in a number column — every one must surface as an
+// error the reader can see. Zero is a number; a total containing silent
+// zeros is wrong and looks right.
+// 2. A CYCLE THAT RESOLVES. A refers to B refers to A must report #CYCLE!,
+// not settle on whatever the evaluator happened to compute first.
+// 3. STALE ORDER. If a formula column is computed before the column it
+// depends on, it reads that column's OLD values — right shape, wrong
+// numbers, and only on some recalculations.
+
+import { evaluate, recalc, dependencies, isErr, FUNCTIONS, type EvalCtx, type Vec } from '../dash/src/formula.ts'
+import type { TableSheet } from '../dash/src/model.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+const ctx = (cols: Record<string, Vec>, n: number): EvalCtx => {
+ const m = new Map<string, Vec>()
+ for (const [k, v] of Object.entries(cols)) { m.set(k, v); m.set(k.toLowerCase(), v) }
+ return { cols: m, n, now: '2026-08-03T00:00:00.000Z' }
+}
+const one = (src: string, cols: Record<string, Vec> = {}, n = 1) => evaluate(src, ctx(cols, n))[0]
+
+// ------------------------------------------------------------- arithmetic
+ok(one('1+2*3') === 7, 'precedence: 1+2*3 is 7')
+ok(one('(1+2)*3') === 9, 'parentheses group')
+ok(one('2^3^2') === 512, '^ is right-associative (2^(3^2)), as in Excel')
+ok(one('-3+5') === 2, 'unary minus')
+ok(one('10/4') === 2.5, 'division')
+ok(one('"a"&"b"') === 'ab', '& concatenates')
+ok(one('1=1') === true && one('1<>2') === true, 'comparisons')
+ok(one('2<10') === true, 'numeric comparison is numeric, not lexical')
+
+// ------------------------------------------------- errors, never zeroes
+ok(isErr(one('1/0')), 'divide by zero is an ERROR, not Infinity and not 0')
+ok(String(one('1/0')) === '#DIV/0!', 'and it says which error')
+ok(isErr(one('NOPE(1)')), 'an unknown function is #NAME?')
+ok(isErr(one('Missing+1')), 'an unknown column reference is an error')
+ok(isErr(one('1+"abc"')), 'text where a number is required is #VALUE!')
+ok(String(one('1/0+5')) === '#DIV/0!', 'errors PROPAGATE through arithmetic')
+ok(one('IFERROR(1/0, 99)') === 99, 'IFERROR catches one')
+ok(one('SUM(a)', { a: [1, 2, 3] }, 3) === 6, 'and a clean SUM still works')
+
+// the assertion an implementation that coerces errors to 0 fails
+ok(!(one('1/0') === 0), 'a division by zero is NOT silently zero')
+
+// ------------------------------------------------------------- vectorised
+{
+ const v = evaluate('Price * Qty', ctx({ Price: [10, 20, 30], Qty: [1, 2, 3] }, 3), )
+ ok(JSON.stringify(v) === JSON.stringify([10, 40, 90]), 'column * column is elementwise')
+ const w = evaluate('Price * 2', ctx({ Price: [10, 20] }, 2))
+ ok(JSON.stringify(w) === JSON.stringify([20, 40]), 'column * scalar broadcasts')
+ // the one that needs both: a share-of-total
+ const s = evaluate('Value / SUM(Value)', ctx({ Value: [25, 75] }, 2))
+ ok(JSON.stringify(s) === JSON.stringify([0.25, 0.75]),
+ 'a column divided by an AGGREGATE of itself — the mix vectorisation exists for')
+}
+
+// -------------------------------------------------------------- functions
+ok(one('ROUND(2.345, 2)') === 2.35, 'ROUND to 2dp')
+ok(one('ROUND(2.5, 0)') === 3, 'ROUND(2.5) is 3, not 2 — Excel rounds half away from zero')
+ok(one('ABS(-4)') === 4, 'ABS')
+ok(one('MOD(7,3)') === 1, 'MOD')
+ok(isErr(one('MOD(7,0)')), 'MOD by zero is an error')
+ok(one('IF(1>2,"y","n")') === 'n', 'IF')
+ok(one('AND(TRUE,FALSE)') === false && one('OR(TRUE,FALSE)') === true, 'AND / OR')
+ok(one('LEN("hello")') === 5, 'LEN')
+ok(one('UPPER("ab")') === 'AB' && one('LEFT("hello",2)') === 'he', 'text functions')
+ok(one('RIGHT("hello",2)') === 'lo', 'RIGHT')
+ok(one('TRIM(" a b ")') === 'a b', 'TRIM collapses internal runs too')
+ok(one('SUBSTITUTE("a-b","-","+")') === 'a+b', 'SUBSTITUTE')
+ok(one('YEAR("2026-08-03")') === 2026 && one('MONTH("2026-08-03")') === 8, 'date parts')
+ok(one('MEDIAN(a)', { a: [1, 3, 2] }, 3) === 2, 'MEDIAN')
+ok(one('MEDIAN(a)', { a: [1, 2, 3, 4] }, 4) === 2.5, 'MEDIAN of an even count averages the middle two')
+ok(one('COUNTA(a)', { a: [1, null, 'x', ''] }, 4) === 2, 'COUNTA ignores blanks')
+ok(one('SUMIF(r,">10",v)', { r: [5, 20, 30], v: [1, 2, 3] }, 3) === 5, 'SUMIF with a comparison')
+ok(one('COUNTIF(r,"North")', { r: ['North', 'South', 'North'] }, 3) === 2, 'COUNTIF with a literal')
+ok(one('AVERAGEIF(r,">1",v)', { r: [1, 2, 3], v: [10, 20, 30] }, 3) === 25, 'AVERAGEIF')
+ok(FUNCTIONS.length >= 45, `the library covers ${FUNCTIONS.length} functions`)
+
+// ------------------------------------------------------------- volatiles
+ok(one('TODAY()') === '2026-08-03',
+ 'TODAY() is FROZEN from the context — a saved file shows the same date to everyone')
+
+// -------------------------------------------------------------- bracketed
+ok(one('[Unit Price] * 2', { 'Unit Price': [21] }, 1) === 42,
+ 'a column whose name has spaces is referenced with [brackets]')
+
+// ----------------------------------------------------------- dependencies
+{
+ const d = dependencies('Price * Qty + SUM(Tax)')
+ ok(d.includes('Price') && d.includes('Qty') && d.includes('Tax') && d.length === 3,
+ 'dependencies finds every referenced column and nothing else')
+ ok(!dependencies('1 + 2').length, 'a constant expression depends on nothing')
+}
+
+// ------------------------------------------------------- recalc ORDERING
+const sheet = (cols: Array<{ id: string; name: string; formula?: string }>, data: Record<string, number[]>): TableSheet => ({
+ id: 'sh', name: 'S', kind: 'table',
+ rids: [[1, Object.values(data)[0]?.length ?? 0]],
+ columns: cols.map((c) => ({ ...c, type: 'number' as const })),
+ data: Object.fromEntries(Object.entries(data).map(([k, v]) => [k, { enc: 'raw' as const, v }])),
+ steps: [],
+})
+
+{
+ // net depends on gross, gross depends on price — declared in the WRONG order
+ const s = sheet(
+ [
+ { id: 'net', name: 'net', formula: 'gross * 0.8' },
+ { id: 'gross', name: 'gross', formula: 'price * 2' },
+ { id: 'price', name: 'price' },
+ ],
+ { price: [10, 20] },
+ )
+ const r = recalc(s)
+ ok(r.order.indexOf('gross') < r.order.indexOf('net'),
+ 'recalc orders dependencies first, regardless of declaration order')
+ ok(JSON.stringify(r.values.get('gross')) === JSON.stringify([20, 40]), 'gross computes')
+ ok(JSON.stringify(r.values.get('net')) === JSON.stringify([16, 32]),
+ 'and net uses the FRESH gross — not the stale column, which would give 0')
+ ok(r.cycles.length === 0, 'no cycles reported')
+}
+
+// --------------------------------------------------------------- cycles
+{
+ const s = sheet(
+ [{ id: 'a', name: 'a', formula: 'b + 1' }, { id: 'b', name: 'b', formula: 'a + 1' }],
+ { seed: [1] },
+ )
+ const r = recalc(s)
+ ok(r.cycles.length === 2, 'a two-column cycle is detected')
+ ok(isErr(r.values.get('a')![0]) && String(r.values.get('a')![0]) === '#CYCLE!',
+ 'and both columns read #CYCLE! rather than a plausible number')
+}
+{
+ // self-reference
+ const s = sheet([{ id: 'a', name: 'a', formula: 'a + 1' }], { seed: [1] })
+ ok(recalc(s).cycles.length === 1, 'a self-reference is a cycle')
+}
+{
+ // a long chain must NOT be mistaken for a cycle
+ const s = sheet(
+ [
+ { id: 'd', name: 'd', formula: 'c + 1' }, { id: 'c', name: 'c', formula: 'b + 1' },
+ { id: 'b', name: 'b', formula: 'a + 1' }, { id: 'a', name: 'a' },
+ ],
+ { a: [0] },
+ )
+ const r = recalc(s)
+ ok(r.cycles.length === 0 && r.values.get('d')![0] === 3,
+ 'a four-deep chain resolves to 3, and is not reported as a cycle')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/scripts/test-dash-store.ts b/scripts/test-dash-store.ts
index bb98b28f..3f80cb05 100644
--- a/scripts/test-dash-store.ts
+++ b/scripts/test-dash-store.ts
@@ -94,6 +94,11 @@ roundTrip('setMeasure', {
measure: { name: 'Revenue', expr: 'SUM(amount)', grain: 'sh1', additive: true },
})
roundTrip('setTitle', { op: 'setTitle', title: 'renamed' })
+roundTrip('addColumn', {
+ op: 'addColumn', sheet: 'sh1',
+ column: { id: 'computed', name: 'Computed', type: 'number', formula: 'amount * 2' },
+})
+roundTrip('removeColumn', { op: 'removeColumn', sheet: 'sh1', col: 'amount' })
roundTrip('a multi-patch commit', [
{ op: 'setCells', sheet: 'sh1', col: 'amount', rids: [1], v: [1] },
{ op: 'setColumn', sheet: 'sh1', col: 'amount', patch: { unit: 'EUR' } },