Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

dash: typed entry reads percent, currency and dates; text in arithmetic follows Excel (#810)

nyblnet45c70ec60b25
diff --git a/.github/actions/validate-dash/action.yml b/.github/actions/validate-dash/action.yml
index 39003ded..b4579b8d 100644
--- a/.github/actions/validate-dash/action.yml
+++ b/.github/actions/validate-dash/action.yml
@@ -696,3 +696,11 @@ runs:
# that has it exactly backwards.
shell: bento-step {0}
run: node scripts/test-dash-datavalid.ts
+
+ - name: bento/dash typed entry and text in arithmetic
+ # 10, $5, 15% typed into a spreadsheet then =SUM said 30 and =G13*G15
+ # said 150: typing stored the text, and the engine read "15%" as 15.
+ # Entry values + formats, Excel's text-in-arithmetic rule, the formula
+ # bar's entered form, and malformed formulas refused at entry.
+ shell: bento-step {0}
+ run: node scripts/test-dash-entryparse.ts
diff --git a/.github/workflows/ci-dash.yml b/.github/workflows/ci-dash.yml
index 48f15c2c..85f79fe7 100644
--- a/.github/workflows/ci-dash.yml
+++ b/.github/workflows/ci-dash.yml
@@ -69,6 +69,12 @@ jobs:
# marching ants; point mode inserts references (dataset and
# spreadsheet, other sheets by tab); Escape closes Story and Pivot.
run: node scripts/test-dash-gestures-browser.mjs
+ - name: Typing into a spreadsheet cell reads what was meant
+ # The review's keystrokes: 10, $5, 15% then =SUM and =G13*G15 must say
+ # 15.15 and 1.5 (they said 30 and 150). ISO and named-month dates are
+ # dates, 3/4/2026 stays text, the formula bar shows 100% not 1, and
+ # =A11+ is refused in the cell and the bar with the reason shown.
+ run: node scripts/test-dash-entryparse-browser.mjs
dash-gate-browser:
runs-on: ubuntu-latest
diff --git a/dash/CHANGELOG.md b/dash/CHANGELOG.md
index b397b74d..b3ee1713 100644
--- a/dash/CHANGELOG.md
+++ b/dash/CHANGELOG.md
@@ -12,6 +12,21 @@ There is no server, so a break here would be permanent.
The release that came out of watching somebody use 0.2.0.
+- **Typing into a spreadsheet cell reads what you meant, and sums add up.**
+ `15%` is stored as 0.15 and shown as 15%; `$5`, `£1,234` and `€3,50` are
+ numbers that keep their currency symbol; `(5)` is −5; `2026-03-04` and
+ `Mar 4 2026` are dates. `3/4/2026` still stays as text, because it could be
+ either day. Pasting text into a spreadsheet reads it the same way. Before,
+ all of these were stored as text, and formulas then read the text `15%` as
+ 15: a SUM over 10, $5 and 15% said 30 instead of 15.15. Formulas now treat
+ text as Excel does. A range in SUM, AVERAGE or COUNT skips text, arithmetic
+ on text that is not a number gives #VALUE!, and `=10*15%` is 1.5. `SUM(1, 2, 3)`
+ now adds every argument; it used to stop at the first one.
+- **The formula bar shows what you typed.** A cell reading 100% shows `100%`,
+ not `1`, and a currency cell shows `$300.50`.
+- **A formula with a mistake in it is not entered.** `=A11+` used to go in and
+ show #VALUE!. Now the cell stays open, the problem is shown under it, and Esc
+ cancels. The formula bar does the same.
- **CSV export no longer lets a cell run as a formula.** Text starting with `=`, `+`, `-`, `@`, a tab or a return is written with a leading `'`, so opening the CSV in Excel or Sheets shows it as text.
- **Neutral title while sealed, matching the saved file's title.**
- **A sealed workbook deletes this browser's earlier plaintext recovery copy and version history of itself** on open; other workbooks' copies are untouched.
diff --git a/dash/src/cellformula.ts b/dash/src/cellformula.ts
index 7f3ae0da..9eaed3a7 100644
--- a/dash/src/cellformula.ts
+++ b/dash/src/cellformula.ts
@@ -57,8 +57,8 @@
// rows together, and that is a wrong number that looks like a right one.
import {
- evaluate, isErr, recalc, spillError, vecShape, FormulaError,
- type Cell, type Shaped, type Vec,
+ evaluate, isErr, recalc, spillError, syntaxProblem, vecShape, FormulaError,
+ type Cell, type Shaped, type SyntaxProblem, type Vec,
} from './formula.ts'
import {
expandRange, formatRef, isNameLike, mapNames, mapRefs, rewriteFormulaRefs,
@@ -735,6 +735,29 @@ export function evalCellArray(
return { value: out[0] ?? null, rows: shape.rows, cols: shape.cols, cells: out }
}
+/**
+ * Would this cell formula PARSE? null when it would; otherwise why not, with
+ * the place it went wrong spelled as the author wrote it.
+ *
+ * ENTRY ONLY — the cell editor and the formula bar ask before committing
+ * (finding 3.4). A formula already in a file is never refused: it evaluates,
+ * forgivingly, as it always has. References are swapped for placeholders that
+ * read as plain words (they are what `bindRefs` would swap them for), so the
+ * grammar is formula.ts's own and the only thing this adds is the swap back.
+ */
+export function cellFormulaProblem(src: string, scope: RefScope = NO_SHEETS): SyntaxProblem | null {
+ const named = expandNames(formulaBody(src), scope.names)
+ if (named.cycle !== undefined) return null // evaluates to its own error
+ // `#REF!` is a reference that was deleted — a formula, not a typo
+ if (named.expr.includes(REF_ERR)) return null
+ const texts: string[] = []
+ const expr = mapRefs(named.expr, (u) => { texts.push(u.text); return `_ref${texts.length - 1}_` })
+ const why = syntaxProblem(expr)
+ if (!why) return null
+ const back = why.near.match(/^_ref(\d+)_$/)
+ return back ? { ...why, near: texts[Number(back[1])] ?? why.near } : why
+}
+
// --- ordering ---------------------------------------------------------------
/** How much of a rectangle a source occupies, when it has no opinion of its own. */
diff --git a/dash/src/cellprops.ts b/dash/src/cellprops.ts
index 649feee2..69136a6b 100644
--- a/dash/src/cellprops.ts
+++ b/dash/src/cellprops.ts
@@ -35,11 +35,17 @@
// not. In a cell explicitly formatted Number/Currency/Percent the author
// HAS said it is a quantity, so there `01234` is 1234.
//
-// 4. DASH NEVER INFERS A DATE FROM TYPING. `1/2` is the text "1/2", not the
-// 2nd of January and not the 1st of February — nothing on screen would say
-// which, and that guess is the one that renamed a third of the human
-// genome. Dates arrive by APPLYING the Date format, which parses only
-// unambiguous spellings (rule 8) and leaves anything else alone.
+// 4. DASH NEVER GUESSES A DATE FROM TYPING — and reads the ones that need no
+// guess. `1/2` and `3/4/2026` stay the text they were, not the 2nd of
+// January and not the 1st of February — nothing on screen would say which,
+// and that guess is the one that renamed a third of the human genome. But
+// `2026-03-04` (ISO) and `Mar 4 2026` / `4 March 2026` (a named month) can
+// only mean one day, and refusing THOSE was not caution, it was a
+// spreadsheet that could not take a date (review finding 3.2): typing one
+// stores the canonical `YYYY-MM-DD` and stamps the Date format, as rule 5
+// stamps a percent. A slash date stays text even when its day is over 12
+// (`readEnteredDate` says why). In a cell already formatted Date, every
+// unambiguous spelling is read (rule 8).
//
// 5. A MARK MAKES A FORMAT; a separator does not. Typing `50%` into an
// unformatted cell stores 0.5 and stamps `0%`; typing `$1,200.50` stores
@@ -47,7 +53,15 @@
// NOTHING — a comma is how a person types a number, whereas a `%` or a
// currency symbol is a statement about what the number MEANS. A format is
// only ever stamped on a cell that had none; typing never overwrites a
-// format somebody chose.
+// format somebody chose. `(5)` is -5 (accounting), and `€3,50` is 3.5 —
+// the digits are read by import.ts's `readEntryNumber`, the same shapes a
+// CSV is read with, and a field that fits BOTH conventions (`1,234`) goes
+// the way the VIEWER's own locale writes decimals.
+//
+// This is what typing does on a spreadsheet since review finding 3.1. It
+// was written here, tested, and never wired: grid.ts kept its own narrower
+// `canvasValue`, so `15%` was stored as the TEXT "15%" and the formula
+// engine then read that text as 15.
//
// 6. A FORMAT CHANGE NEVER RESCALES A NUMBER. Applying Percent to 50 shows
// 5000%, as it does everywhere else, because the alternative — quietly
@@ -86,7 +100,8 @@
import './cellprops.css'
import { t } from './i18n.ts'
-import { formatValue } from './format.ts'
+import { formatValue, readPattern, typedNumber, viewerDecimal } from './format.ts'
+import { readEntryNumber, type EntryNumber } from './import.ts'
import { formatRef } from './a1.ts'
import { isFormula } from './cellformula.ts'
import {
@@ -227,22 +242,13 @@ export const isCustomPattern = (fmt: string | undefined): boolean => {
// --- reading what was typed -------------------------------------------------
-/** Grouped, or plain, with an optional exponent. Signs and marks are peeled first. */
-const NUMERIC = /^(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?(?:[eE][-+]?\d+)?$/
-/** Symbols worth peeling. A prefix a person would type, not every glyph in Unicode. */
-const SYMBOLS = /^[$£€¥₹₽₩₪₺]\s?|^[A-Z]{0,3}\$\s?/
-
-export interface TypedNumber {
- n: number
- /** the field carried a `%` — the value has ALREADY been divided by 100 */
- pct: boolean
- /** the field carried a currency symbol, verbatim */
- symbol: string
- /** decimals actually typed, so a stamped format can match what was written */
- dp: number
- /** the field carried a thousands separator */
- group: boolean
-}
+/**
+ * What a typed field reads as — import.ts's `EntryNumber`. The reading is
+ * import's, not a second parser: one set of digit shapes decides what `1,234`,
+ * `3,50`, `$5`, `(5)` and `15%` mean, whether they were typed, pasted,
+ * imported or met by a formula.
+ */
+export type TypedNumber = EntryNumber
/**
* Read a typed field as a number, or answer null.
@@ -250,50 +256,13 @@ export interface TypedNumber {
* `strict` is rule 3: with it, a leading zero disqualifies the field (an
* unformatted cell keeps `01234` as text); without it — the cell is explicitly
* numeric — the zeros are dropped and the number is read.
+ *
+ * The decimal convention is the VIEWER's when the field alone cannot say
+ * (`1,234` is 1234 to a British typist and 1.234 to a German one); `3,50`
+ * reads 3.5 to everybody, as it does on import. See `readEntryNumber`.
*/
export function readTypedNumber(text: string, opts: { strict?: boolean } = {}): TypedNumber | null {
- let s = text.trim()
- if (!s) return null
-
- // (1,200) is -1200: accounting notation, and the only bracket form worth it
- let neg = false
- if (/^\(.*\)$/.test(s)) { neg = true; s = s.slice(1, -1).trim() }
-
- let symbol = ''
- const sym = s.match(SYMBOLS)
- if (sym) { symbol = sym[0]; s = s.slice(sym[0].length).trim() }
-
- if (s.startsWith('-')) { neg = !neg; s = s.slice(1).trim() }
- else if (s.startsWith('+')) s = s.slice(1).trim()
-
- // the symbol may sit after the sign — `-$5` as well as `$-5`
- if (!symbol) {
- const sym2 = s.match(SYMBOLS)
- if (sym2) { symbol = sym2[0]; s = s.slice(sym2[0].length).trim() }
- }
-
- let pct = false
- if (s.endsWith('%')) { pct = true; s = s.slice(0, -1).trim() }
-
- if (!/\d/.test(s) || !NUMERIC.test(s)) return null
- // rule 3: `0` and `0.5` are numbers; `007` is a label somebody kept the zeros on
- if (opts.strict && /^0\d/.test(s)) return null
-
- const bare = s.replace(/,/g, '')
- let n = Number(bare)
- if (!Number.isFinite(n)) return null
- if (neg) n = -n
- if (pct) n /= 100
-
- const dot = bare.indexOf('.')
- const eAt = bare.search(/[eE]/)
- return {
- n,
- pct,
- symbol,
- dp: dot < 0 ? 0 : (eAt < 0 ? bare.length : eAt) - dot - 1,
- group: s.includes(','),
- }
+ return readEntryNumber(text, { strict: opts.strict, prefer: viewerDecimal() })
}
const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
@@ -344,6 +313,22 @@ export function readTypedDate(text: string): string | null {
return null
}
+/**
+ * A date read from TYPING into a cell with no format — rule 4's narrower set.
+ *
+ * ISO (`2026-03-04`, `2026/3/4`) and a named month (`Mar 4 2026`,
+ * `4 March 2026`) and nothing else. `readTypedDate` also accepts a slash date
+ * whose day is over 12 (`13/2/2026`), which is right when somebody has SAID the
+ * cell is a date — but from bare typing it would make `13/2/2026` a date and
+ * `12/2/2026`, one row up, the text it has to stay. One column, two kinds, and
+ * which is which decided by the day of the month: the refusal is kept whole.
+ */
+export function readEnteredDate(text: string): string | null {
+ const s = text.trim()
+ if (/^\d{1,2}[-/.]\d{1,2}[-/.]\d{2,4}$/.test(s)) return null
+ return readTypedDate(s)
+}
+
/**
* A time of day, canonical `HH:MM` (or `HH:MM:SS`), or null.
*
@@ -404,7 +389,20 @@ export function coerceInput(prev: CanvasCell | undefined, text: string): CanvasC
// rule 3: strict (leading zeros are a label) unless the cell says it is a quantity
const num = readTypedNumber(s, { strict: !numeric })
- if (!num) return { ...rest, v: s }
+ if (!num) {
+ // rule 4: a date is read from typing only where nobody could misread it
+ // (in a Date cell any unambiguous spelling; in a blank one the narrower set
+ // `readEnteredDate` allows; in a cell somebody formatted as a NUMBER, none —
+ // typing never overwrites a format somebody chose, rule 5)
+ if (choice?.kind === 'date') {
+ const d = readTypedDate(s)
+ if (d) return { ...rest, v: d }
+ } else if (!has) {
+ const d = readEnteredDate(s)
+ if (d) return { ...rest, v: d, format: DATE_PATTERN }
+ }
+ return { ...rest, v: s }
+ }
// A bare number in a PERCENT cell is percent points — Excel's rule, and the
// one everybody has muscle memory for: 50 in a percent cell is 50%.
@@ -413,7 +411,7 @@ export function coerceInput(prev: CanvasCell | undefined, text: string): CanvasC
// rule 5: a MARK makes a format, a separator does not
if (num.pct) {
- return { ...rest, v: num.n, format: buildPattern({ ...DEFAULT_CHOICE, kind: 'percent', dp: Math.max(0, num.dp - 2), group: false }) }
+ return { ...rest, v: num.n, format: buildPattern({ ...DEFAULT_CHOICE, kind: 'percent', dp: num.dp, group: false }) }
}
if (num.symbol) {
return {
@@ -473,6 +471,67 @@ export function recastForFormat(prev: CanvasCell | undefined, fmt: string | unde
return { cell: orNull(base), refused: false }
}
+/**
+ * What the formula bar (and the cell editor) shows for a VALUE cell: the form
+ * somebody would type to put that value there — finding 2.8.
+ *
+ * Not the display (`$1,200.50` rounds; `12%` hides `12.5%`) and not the raw
+ * stored number (`1` for a cell that reads `100%`, which then re-commits as
+ * 100%·100 the moment somebody presses Enter on it in a percent cell). The
+ * rule is a ROUND TRIP: `coerceInput(cell, enteredForm(cell))` stores the same
+ * value again, so opening a cell and pressing Enter never changes it.
+ *
+ * • a percent cell shows its value ×100 with a `%`, at full precision;
+ * • a currency cell shows its symbol and at least the format's decimals;
+ * • any other number is written in the viewer's own decimal separator,
+ * ungrouped — the separator `readTypedNumber` will read it back with;
+ * • text that would NOT read back as itself (`'15%` kept as text, a legacy
+ * file's "2026-03-04" that was never made a date) wears the apostrophe that
+ * keeps it text, which is also how a reader can see that it IS text.
+ *
+ * A formula cell is not this function's business: the bar shows its source.
+ */
+export function enteredForm(cell: CanvasCell | undefined): string {
+ const v = cell?.v
+ if (v === undefined || v === null || v === '') return ''
+ if (typeof v === 'boolean') return v ? 'TRUE' : 'FALSE'
+ const fmt = typeof cell?.format === 'string' ? cell.format : undefined
+ if (typeof v === 'number') {
+ if (!Number.isFinite(v)) return String(v)
+ const kind = fmt ? classifyFormat(fmt).kind : 'general'
+ return enteredNumber(v, kind === 'percent' ? 'percent' : kind === 'currency' ? 'currency' : 'plain', fmt)
+ }
+ const s = String(v)
+ if (isTextFormat(fmt)) return s
+ // would typing `s` back into this cell store `s`? if not, it needs the apostrophe
+ const { v: _v, f: _f, ...rest } = cell ?? {}
+ const back = coerceInput(rest, s)
+ return back && back.v === s && back.f === undefined && back.format === rest.format ? s : `'${s}`
+}
+
+/**
+ * A NUMBER in its entered form — `enteredForm`'s numeric half, shared with the
+ * dataset kind, whose column (not the cell) says percent or money.
+ *
+ * percent ×100 with a `%`, at full precision — `100%` for a stored 1
+ * currency the pattern's own symbol, and at least its decimals — `$300.50`
+ * plain the number, ungrouped, in the viewer's decimal separator
+ */
+export function enteredNumber(v: number, kind: 'percent' | 'currency' | 'plain', fmt?: string): string {
+ if (!Number.isFinite(v)) return String(v)
+ if (kind === 'percent') {
+ const shown = Number((v * 100).toPrecision(15))
+ // full precision, but never the binary noise of ×100 (0.07·100)
+ return `${typedNumber(shown / 100 === v ? shown : v * 100)}%`
+ }
+ if (kind === 'currency') {
+ const p = readPattern(fmt)
+ const body = typedNumber(Math.abs(v), p.dp ?? 0)
+ return `${v < 0 ? '-' : ''}${p.prefix}${body}${p.suffix}`
+ }
+ return typedNumber(v)
+}
+
// --- selections, as A1 keys -------------------------------------------------
/** One address. a1.ts's `formatRef` is the ONLY place a key is minted. */
diff --git a/dash/src/datavalid.css b/dash/src/datavalid.css
index 3f5c50e5..627f83d8 100644
--- a/dash/src/datavalid.css
+++ b/dash/src/datavalid.css
@@ -66,6 +66,30 @@
background: var(--err-bg);
}
+/* The formula bar refusing a formula that does not parse — the same look. */
+.dx-fx-input.dv-refused {
+ box-shadow: inset 0 0 0 2px var(--err-ink);
+ background: var(--err-bg);
+}
+
+/* WHY it was refused, under the editor. Fixed on the body for the same
+ reason as the list menu below: a cell clips. Pointer-transparent, so it
+ never steals the click that moves on. */
+.dg-refuse-tip {
+ position: fixed;
+ z-index: 60;
+ max-width: 340px;
+ padding: 5px 9px;
+ font-size: 12px;
+ line-height: 1.35;
+ color: var(--err-ink);
+ background: var(--surface);
+ border: 1px solid var(--err-ink);
+ border-radius: var(--dp-radius);
+ box-shadow: var(--shadow-pop);
+ pointer-events: none;
+}
+
/* ————— the list menu —————
`position:fixed` on the body: the grid's cells clip, so a menu inside one is
a menu with two entries and a scrollbar. The geometry is the repo's floating
diff --git a/dash/src/format.ts b/dash/src/format.ts
index 25d8c172..b1d76b53 100644
--- a/dash/src/format.ts
+++ b/dash/src/format.ts
@@ -40,6 +40,45 @@ export const setViewerLocale = (l: string | undefined): void => { viewerLocale =
const forNumbers = (): string | undefined => viewerLocale ?? locale()
+/**
+ * The VIEWER's decimal separator — '.' or ','. What a typist means by `1,234`
+ * (import.ts `readEntryNumber` asks this to break a tie only a single value
+ * can have), and the separator the formula bar writes a number back with, so
+ * that what it shows is what the same person would type to get it again.
+ */
+export function viewerDecimal(): '.' | ',' {
+ try {
+ const part = new Intl.NumberFormat(forNumbers()).formatToParts(1.5).find((p) => p.type === 'decimal')
+ return part?.value === ',' ? ',' : '.'
+ } catch {
+ return '.'
+ }
+}
+
+/**
+ * A number written the way a person would TYPE it, in the viewer's own
+ * separators: no grouping, as many digits as the value needs (15 significant,
+ * or 17 when 15 would not read back as the same double), and at least `minDp`
+ * decimals. The formula bar's half of "show what was entered".
+ */
+export function typedNumber(n: number, minDp = 0): string {
+ let digits = 15
+ if (Number(n.toPrecision(15)) !== n) digits = 17
+ const fmt = (sig: number) => new Intl.NumberFormat(forNumbers(), {
+ useGrouping: false,
+ maximumSignificantDigits: sig,
+ }).format(n)
+ let out = fmt(digits)
+ if (minDp > 0) {
+ // pad to the format's decimals: `$300.5` under `$#,##0.00` reads `$300.50`
+ const dec = viewerDecimal()
+ const at = out.indexOf(dec)
+ const have = at < 0 ? 0 : out.length - at - 1
+ if (have < minDp) out = (at < 0 ? out + dec : out) + '0'.repeat(minDp - have)
+ }
+ return out
+}
+
/**
* What an Excel-style pattern means, and the ONE place that decides it.
*
diff --git a/dash/src/formula.ts b/dash/src/formula.ts
index 6f0c4c80..c747b63b 100644
--- a/dash/src/formula.ts
+++ b/dash/src/formula.ts
@@ -30,7 +30,7 @@ import { sheetQualifiers } from './a1.ts'
// implementations, deliberately: two answers to "what does #,##0.00 mean", or
// to "what day is 03/04/2026", is one wrong number waiting for a date change.
import { formatNumber, readPattern } from './format.ts'
-import { coerce, inferColumn } from './import.ts'
+import { coerce, inferColumn, readEntryNumber } from './import.ts'
export type Cell = number | string | boolean | null | FormulaError
export type Vec = Cell[]
@@ -67,7 +67,7 @@ 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[] {
+function lex(src: string, skipped?: (ch: string) => void): Tok[] {
const out: Tok[] = []
let i = 0
const isIdStart = (c: string) => /[A-Za-z_]/.test(c)
@@ -110,9 +110,14 @@ function lex(src: string): Tok[] {
}
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 }
+ // `%` is the POSTFIX percent, Excel's: `=10*15%` is 1.5. It was skipped as
+ // an unknown character, so that formula said 150.
+ 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
+ // anything else is skipped rather than fatal — at EVALUATION. Entry asks
+ // `syntaxProblem` first, which reports it instead.
+ skipped?.(c)
+ i++
}
return out
}
@@ -171,8 +176,15 @@ function parse(src: string): Node {
return { k: 'lit', v: ERR.value() }
}
+ /** `x%` is x / 100, binding tighter than anything — `2^50%` is 2^0.5. */
+ function postfix(): Node {
+ let e = primary()
+ while (peek()?.t === 'op' && peek()!.v === '%') { eat(); e = { k: 'bin', op: '/', l: e, r: { k: 'lit', v: 100 } } }
+ return e
+ }
+
function expr(min: number): Node {
- let left = primary()
+ let left = postfix()
for (;;) {
const tk = peek()
if (!tk || tk.t !== 'op') break
@@ -188,6 +200,88 @@ function parse(src: string): Node {
return expr(0)
}
+/** Why an expression does not parse — see `syntaxProblem`. */
+export interface SyntaxProblem {
+ /** `incomplete` — it ends where a value was due (`A11+`, `SUM(`);
+ * `unclosed` — a bracket is opened and never closed (`(1+2`);
+ * `unexpected` — something stands where it cannot (`1 2`, `)`, `,`, `{`) */
+ code: 'incomplete' | 'unclosed' | 'unexpected'
+ /** the token it went wrong at, or the last good one for `incomplete` */
+ near: string
+}
+
+/**
+ * Does this expression PARSE? null when it does.
+ *
+ * `parse` is forgiving by design — it never throws, skips what it does not
+ * know, closes brackets nobody closed, and drops whatever follows a complete
+ * expression — because it runs on FORMULAS ALREADY IN A FILE, where a refusal
+ * would be a blank where an answer was. That forgiveness is wrong at ENTRY:
+ * `=A11+` committed and showed #VALUE!, `=(1` said 1, `=1 2` said 1 (review
+ * finding 3.4). So entry asks this first — the same grammar, walked strictly —
+ * and refuses, the way Excel ("There's a problem with this formula") and
+ * Sheets (a parse error beside the cell) do. Evaluation is untouched.
+ */
+export function syntaxProblem(src: string): SyntaxProblem | null {
+ let odd: string | null = null
+ const toks = lex(src, (ch) => { if (odd === null) odd = ch })
+ if (odd !== null) return { code: 'unexpected', near: odd }
+ let p = 0
+ const text = (tk: Tok | undefined) => (tk === undefined ? '' : tk.t === 'str' ? `"${tk.v}"` : String(tk.v))
+ const isP = (v: string) => toks[p]?.t === 'punc' && toks[p]!.v === v
+ const isOp = (v?: string) => toks[p]?.t === 'op' && (v === undefined || toks[p]!.v === v)
+ class Stop { why: SyntaxProblem; constructor(why: SyntaxProblem) { this.why = why } }
+ function fail(code: SyntaxProblem['code']): never {
+ const near = code === 'incomplete' ? text(toks[p - 1]) : code === 'unclosed' ? '(' : text(toks[p])
+ throw new Stop({ code, near })
+ }
+ function operand(): void {
+ while (isOp('-') || isOp('+')) p++
+ const tk = toks[p]
+ if (!tk) fail('incomplete')
+ if (tk.t === 'num' || tk.t === 'str') p++
+ else if (tk.t === 'id') {
+ p++
+ if (isP('(')) {
+ p++
+ if (isP(')')) { p++ } else {
+ for (;;) {
+ if (isP(',') || isP(')')) fail('unexpected') // an empty argument
+ expression()
+ if (isP(',')) { p++; continue }
+ if (isP(')')) { p++; break }
+ if (p >= toks.length) fail('unclosed')
+ fail('unexpected')
+ }
+ }
+ }
+ } else if (tk.t === 'punc' && tk.v === '(') {
+ p++
+ expression()
+ if (isP(')')) p++
+ else if (p >= toks.length) fail('unclosed')
+ else fail('unexpected')
+ } else fail('unexpected')
+ while (isOp('%')) p++
+ }
+ function expression(): void {
+ operand()
+ while (isOp() && PREC[toks[p]!.v] !== undefined) {
+ p++
+ operand()
+ }
+ }
+ try {
+ if (!toks.length) return { code: 'incomplete', near: '=' }
+ expression()
+ if (p < toks.length) fail('unexpected')
+ return null
+ } catch (e) {
+ if (e instanceof Stop) return e.why
+ throw e
+ }
+}
+
/** Column names an expression depends on — the edges of the recalc graph. */
export function dependencies(src: string): string[] {
const out = new Set<string>()
@@ -203,14 +297,43 @@ export function dependencies(src: string): string[] {
// --- coercion ---------------------------------------------------------------
+// ═══ TEXT IN ARITHMETIC — the rule, which is Excel's ═══════════════════════
+//
+// Review finding 3.1: a spreadsheet cell holding the TEXT "15%" counted as 15
+// in `SUM` and in `*`, because this function stripped every `%`, `$` and `,`
+// it could see and read whatever digits were left. SUM(10, "$5", "15%") said
+// 30 and 10 * "15%" said 150 — numbers that look right and are not. The rule
+// now, stated once, for every caller in this file:
+//
+// 1. A RANGE OR REFERENCE handed to an aggregate (SUM, AVERAGE, COUNT, MIN,
+// MAX, MEDIAN, PRODUCT, STDEV…, and the sum range of SUMIF/SUMIFS) counts
+// only the NUMBERS in it. Text — even text that looks like a number — and
+// booleans are skipped, blanks are skipped. `numbersIn` / `rangeNumber`.
+// 2. A value written DIRECTLY as an aggregate's argument (`SUM(1, "5", TRUE)`)
+// is coerced as arithmetic would coerce it (rule 3), and text that will
+// not read is #VALUE! — except COUNT, which simply does not count it.
+// `aggArgs`.
+// 3. DIRECT ARITHMETIC (`+ - * / ^`, unary minus, comparisons against a
+// number, and every function argument that wants a number) coerces text
+// exactly as Excel does: the text must read WHOLE as a number in the
+// notation a person types — `"15%"` is 0.15, `"$5"` is 5, `"(5)"` is -5,
+// `"1,234"` is 1234, `"1e3"` is 1000 — and anything else is #VALUE!, never
+// the digits that happened to be in it. The reading is import.ts's
+// `readEntryNumber` with import's own tie-break ('.' wins `1,234`), so the
+// answer does not depend on who opens the file. A date string is #VALUE!:
+// dash keeps a date as a date, not as Excel's serial number (see VALUE).
+// 4. A blank is 0 in arithmetic, a boolean is 1 or 0 — unchanged.
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 r = readEntryNumber(String(v), { prefer: '.' })
+ return r ? r.n : ERR.value(`"${v}" is not a number`)
}
+
+/** Rule 1: what a cell IN A RANGE contributes to an aggregate — a number, or nothing. */
+const rangeNumber = (x: Cell | undefined): number | null => (typeof x === 'number' ? x : null)
const str = (v: Cell): string => (v == null ? '' : isErr(v) ? v.code : String(v))
const bool = (v: Cell): boolean => {
if (isErr(v)) return false
@@ -235,15 +358,17 @@ const bool = (v: Cell): boolean => {
* 0. Excel's rule, and the reason it is Excel's rule is that a spreadsheet
* range is mostly empty by nature.
*
- * Non-numeric TEXT is dropped as it always was: `num()` gives an error for it
- * and an error is not a number.
+ * TEXT AND BOOLEANS ARE SKIPPED TOO — all text, including text that looks
+ * like a number (rule 1 above `num`). This used to run every cell through
+ * `num()`, which is how the text "15%" became 15 inside a SUM. A value written
+ * directly as an argument has already been coerced by `aggArgs` and arrives
+ * here as a number.
*/
const numbersIn = (v: Vec): number[] => {
const out: number[] = []
for (const x of v) {
- if (x === null || x === undefined || x === '') continue
- const n = num(x)
- if (typeof n === 'number') out.push(n)
+ const n = rangeNumber(x)
+ if (n !== null) out.push(n)
}
return out
}
@@ -375,9 +500,12 @@ const nth = (list: number[], kArg: Cell, big: boolean): Cell => {
return [...list].sort((x, y) => (big ? y - x : x - y))[i - 1]
}
+/** The numbers among some arguments: a RANGE gives only its numbers (rule 1
+ * above `num`), a single value is coerced (rule 3) and dropped if it will not. */
const nums = (a: Array<Cell | Vec>): number[] =>
- a.flatMap((x) => (Array.isArray(x) ? x : [x]))
- .map((x) => num(x as Cell)).filter((x): x is number => typeof x === 'number')
+ a.flatMap((x) => (Array.isArray(x)
+ ? x.map(rangeNumber).filter((n): n is number => n !== null)
+ : [num(x as Cell)].filter((n): n is number => typeof n === 'number')))
/**
* Functions that consume a WHOLE COLUMN, dispatched before SCALAR.
@@ -1140,6 +1268,43 @@ const asDate = (v: Cell): Date | null => {
const isoOf = (d: Date): string => d.toISOString().slice(0, 10)
const DAY_MS = 86_400_000
+/** The aggregates that count raw entries rather than numbers — they see every arg as given. */
+const RAW_COUNT = new Set(['COUNTA', 'COUNTBLANK', 'COUNTUNIQUE'])
+
+/**
+ * An aggregate's arguments, ALL of them, as the one vector it reduces.
+ *
+ * ALL of them: this read `node.args[0]` and nothing else, so `SUM(1, 2, 3)`
+ * was 1 and `SUM(A1:A2, A3)` left A3 out — a total with a piece missing and
+ * nothing on screen to say so.
+ *
+ * Rules 1 and 2 above `num`: a range (any vector — a reference, a column, an
+ * array result) goes in as it is and `numbersIn` takes only its numbers; a
+ * value written directly is coerced here, so `SUM(1, "5", TRUE)` is 7 and
+ * `SUM(1, "abc")` is #VALUE!, as in Excel. COUNT does not count a direct value
+ * that will not read; it does not fail on one either.
+ */
+function aggArgs(name: string, args: Node[], ctx: EvalCtx): Vec | FormulaError {
+ const out: Vec = []
+ for (const a of args) {
+ const v = evalNode(a, ctx)
+ // the common case, one range, is handed over as it is — no copy of 400k cells
+ if (args.length === 1 && isVec(v)) return v
+ if (isVec(v)) {
+ for (const x of v) out.push(x)
+ continue
+ }
+ if (RAW_COUNT.has(name) || isErr(v) || v === null || typeof v === 'number') { out.push(v); continue }
+ const n = num(v)
+ if (isErr(n)) {
+ if (name === 'COUNT') continue
+ return n
+ }
+ out.push(n)
+ }
+ return out
+}
+
function callFn(node: Node & { k: 'call' }, ctx: EvalCtx): Cell | Vec {
const name = node.name
@@ -1153,8 +1318,8 @@ function callFn(node: Node & { k: 'call' }, ctx: EvalCtx): Cell | Vec {
if (shaped) return shaped(node.args.map((x) => evalNode(x, ctx)))
if (AGG[name]) {
- const v = evalNode(node.args[0], ctx)
- const vec = isVec(v) ? v : [v]
+ const vec = aggArgs(name, node.args, ctx)
+ if (isErr(vec)) return vec
if (!COUNTING.has(name)) {
const bad = vec.find(isErr)
if (bad) return bad
@@ -1170,7 +1335,7 @@ function callFn(node: Node & { k: 'call' }, ctx: EvalCtx): Cell | Vec {
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')
+ const vals = keep.map((i) => rangeNumber(sv[i])).filter((x): x is number => x !== null)
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()
}
@@ -1196,7 +1361,7 @@ function callFn(node: Node & { k: 'call' }, ctx: EvalCtx): Cell | Vec {
if (pairs.every((p) => matches(p.range[i] ?? null, at(p.crit, i)))) keep.push(i)
}
if (counting) return keep.length
- const vals = keep.map((i) => num(target![i] ?? null)).filter((x): x is number => typeof x === 'number')
+ const vals = keep.map((i) => rangeNumber(target![i])).filter((x): x is number => x !== null)
if (name === 'SUMIFS') return vals.reduce((a, b) => a + b, 0)
if (!vals.length) return name === 'AVERAGEIFS' ? ERR.div0() : 0
if (name === 'AVERAGEIFS') return vals.reduce((a, b) => a + b, 0) / vals.length
diff --git a/dash/src/grid.ts b/dash/src/grid.ts
index 61e61a87..678c9944 100644
--- a/dash/src/grid.ts
+++ b/dash/src/grid.ts
@@ -39,6 +39,10 @@ import {
shiftSheetFormulas, shiftDefinedNames, workbookSources,
} from './cellformula.ts'
import { mountFind, type FindUI, type Hit } from './find.ts'
+import { coerceInput, enteredForm, enteredNumber, isTextFormat, DATE_PATTERN } from './cellprops.ts'
+import { readEntryNumber } from './import.ts'
+import { viewerDecimal } from './format.ts'
+import { cellFormulaProblem } from './cellformula.ts'
// The data-validation stylesheet is imported HERE rather than in datavalid.ts,
// because this is the file that emits the markup it styles and because
// datavalid.ts is also read by xlsx.ts, whose rig runs in node with no css
@@ -448,29 +452,21 @@ export const canvasType = (v: unknown): ColumnType =>
typeof v === 'number' ? 'number' : typeof v === 'boolean' ? 'bool' : 'text'
/**
- * What the user typed, as a stored value.
+ * What the user typed, as a stored value — `canvasCellEdit`'s value, alone.
*
- * DELIBERATELY NARROW. A number only when the whole field is one, and a boolean
- * only for the two words; everything else is text, including `2026-01-01` (the
- * table path stores dates as strings too) and `50%`. Excel would turn `50%`
- * into 0.5 wearing a percent format, which means typing invents a FORMAT — and
- * this pass does not write formats (that is the next one). Storing the text is
- * the answer that cannot be wrong about what the author meant.
- *
- * `1,200` is 1200: a thousands separator is how people type numbers into
- * spreadsheets, and `coerceForColumn` already strips them on the table side.
+ * This used to be its own, DELIBERATELY NARROW reader: a number only when the
+ * whole field was bare digits, so `15%`, `$5` and `2026-03-04` were all stored
+ * as text, on the argument that turning `50%` into 0.5 "invents a format".
+ * Review finding 3.1 measured what that cost: the formula engine then read the
+ * TEXT "15%" as 15, so `=SUM` over 10, $5 and 15% said 30 where every other
+ * spreadsheet says 15.15. Typing now goes through cellprops.ts `coerceInput`,
+ * whose header states the rules (a MARK makes a format; an unambiguous date is
+ * read; `3/4/2026` is still refused).
*/
-const NUMERIC = /^[-+]?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?(?:[eE][-+]?\d+)?$/
export function canvasValue(text: string): unknown {
const s = text.trim()
if (s === '') return ''
- if (/^true$/i.test(s)) return true
- if (/^false$/i.test(s)) return false
- // the regex admits `.` and `+` alone, which `Number` reads as NaN/0 — so the
- // digit test is separate rather than folded into an even hairier pattern
- if (!/\d/.test(s) || !NUMERIC.test(s)) return s
- const n = Number(s.replace(/,/g, ''))
- return Number.isFinite(n) ? n : s
+ return coerceInput(undefined, s)?.v ?? s
}
/**
@@ -487,13 +483,40 @@ export function canvasValue(text: string): unknown {
* everything but `f`. And a value and a formula are alternatives — writing one
* drops the other, because a file that carries a number beside the formula that
* produced it can carry a number that disagrees with it.
+ *
+ * The rules for what a typed field IS — percent, currency, accounting
+ * negatives, dates, the apostrophe, the Text format — are cellprops.ts's
+ * `coerceInput`, which this is now a name for.
*/
export function canvasCellEdit(prev: CanvasCell | undefined, text: string): CanvasCell | null {
- const { v: _v, f: _f, ...rest } = prev ?? {}
- const s = text.trim()
- if (s === '') return Object.keys(rest).length ? rest : null
- if (isFormula(s)) return { ...rest, f: s }
- return { ...rest, v: canvasValue(s) }
+ return coerceInput(prev, text)
+}
+
+/**
+ * Writing an already-TYPED value (a paste from this grid, a fill): a number or
+ * a boolean is stored as it is, never printed and re-read — printing 1.234 and
+ * reading it back as a German typist would is 1234. Strings go through typing.
+ */
+export function canvasCellPut(prev: CanvasCell | undefined, val: unknown): CanvasCell | null {
+ if (typeof val === 'number' || typeof val === 'boolean') {
+ const { v: _v, f: _f, ...rest } = prev ?? {}
+ return { ...rest, v: val }
+ }
+ return coerceInput(prev, val == null ? '' : String(val))
+}
+
+/**
+ * Why a typed spreadsheet formula is REFUSED, in the reader's language — or
+ * null when it parses. Exported for the rig; the two editors are its callers.
+ */
+export function formulaRefusal(src: string): string | null {
+ const p = cellFormulaProblem(src)
+ if (!p) return null
+ if (p.code === 'unclosed') return t('There’s a problem with this formula: a bracket is opened and never closed.')
+ if (p.code === 'incomplete') {
+ return t('There’s a problem with this formula: it ends after “{near}”, where a value is missing.', { near: p.near })
+ }
+ return t('There’s a problem with this formula: “{near}” cannot go there.', { near: p.near })
}
/** Clearing a cell — the same rule, with no text to store. */
@@ -517,7 +540,9 @@ export function canvasShown(cell: CanvasCell | undefined, v: unknown): string {
}
export const canvasAlign = (cell: CanvasCell | undefined, v: unknown): string =>
- cell?.align ?? alignFor(canvasType(v))
+ cell?.align ?? (cell?.format === DATE_PATTERN && typeof v === 'string'
+ ? 'right' // a date is a quantity of days: it sits with the numbers
+ : alignFor(canvasType(v)))
export class Grid {
private host: HTMLElement
@@ -1908,22 +1933,37 @@ export class Grid {
: [])
}
- /** Write the formula bar's contents into the active cell. */
- setActiveCell(text: string): void {
+ /**
+ * Write the formula bar's contents into the active cell.
+ *
+ * Answers why it REFUSED, or null when it wrote (or had nothing to do). The
+ * one refusal is a spreadsheet formula that does not parse — the same check
+ * the in-cell editor makes, so the bar is not the door that lets `=A11+` in.
+ */
+ setActiveCell(text: string): string | null {
// On a SPREADSHEET a leading `=` is a cell formula, full stop. The dataset
// path sends it to the COLUMN's expression because that is where a dataset
// keeps one; here there is no column to own it, which is the whole reason
// this kind exists — `=SUM(A1:A5)` under a block of numbers had nowhere to
// land.
if (this.canvas) {
- if (this.store.readOnly) return
+ if (this.store.readOnly) return null
const cur = this.sel.cursor
const key = canvasKey(cur.row, cur.col)
const had = this.canvas.cells[key]
+ if (isFormula(text.trim()) && !isTextFormat(had?.format)) {
+ const why = formulaRefusal(text.trim())
+ if (why !== null) return why
+ }
const next = canvasCellEdit(had, text)
if (next !== null || had !== undefined) this.writeCanvas({ [key]: next })
- return
+ return null
}
+ this.setActiveDatasetCell(text)
+ return null
+ }
+
+ private setActiveDatasetCell(text: string): void {
const s = this.sheet
const c = cols(s)[this.sel.cursor.col]
if (!c || this.store.readOnly) return
@@ -2411,7 +2451,7 @@ export class Grid {
const c = vis[cur.col]
const ref = c ? `${colToLetters(cur.col)}${cur.row + 1}` : ''
const v = this.valueAt(cur.row, cur.col)
- const raw = v == null ? '' : isErr(v) ? String(v) : String(v)
+ const raw = v == null ? '' : isErr(v) ? String(v) : c ? datasetEntered(v, c) : String(v)
const summary = this.selectionSummary()
// The formula bar shows the SOURCE when there is one — a per-cell formula
// first, then the column's expression, then the value. A bar that shows the
@@ -2771,8 +2811,8 @@ export class Grid {
if (!s) return ''
const cell = s.cells[canvasKey(row, col)]
if (typeof cell?.f === 'string') return cell.f
- const v = cell && 'v' in cell ? cell.v : null
- return v == null ? '' : String(v)
+ // the ENTERED form (`100%`, `$300.50`), not the stored 1 — finding 2.8
+ return enteredForm(cell)
}
private paintCanvas(s: CanvasSheet, hadFocus = false): void {
@@ -3122,11 +3162,21 @@ export class Grid {
// deliberately so — the two editors differ only in what a cell IS.
if (write && !isFormula(typed)) {
const rule = canvasRuleAt(canvasRules(this.canvas ?? s), row, col)
- const why = this.refusal(rule, canvasValue(typed))
+ const why = this.refusal(rule, coerceInput((this.canvas ?? s).cells[key], typed)?.v ?? '')
+ if (why !== null) { this.refuse(cell, why); return }
+ }
+ // A formula that does not PARSE is refused, not committed (finding 3.4).
+ // `=A11+` used to land and show #VALUE!, which reads as "A11 holds
+ // something odd" when the fault is the typing. Excel stops at "There's a
+ // problem with this formula"; Sheets keeps the editor open with the
+ // error beside it. So does this, and Escape abandons the edit.
+ if (write && isFormula(typed.trim()) && !isTextFormat((this.canvas ?? s).cells[key]?.format)) {
+ const why = formulaRefusal(typed.trim())
if (why !== null) { this.refuse(cell, why); return }
}
cell.classList.remove('dv-refused')
cell.removeAttribute('title')
+ this.dropRefusalTip()
done = true
this.cvEditing = null
const text = typed
@@ -3202,8 +3252,7 @@ export class Grid {
// A pasted value is already typed when it came from this grid; text
// from another application arrives as a string and is read the same way
// a typed cell is, so `1,200` from Numbers means what it does here.
- const text = val == null ? '' : String(val)
- const next = canvasCellEdit(had, text)
+ const next = canvasCellPut(had, val)
if (next !== null || had !== undefined) cells[key] = next
})
})
@@ -3291,9 +3340,29 @@ export class Grid {
cell.classList.add('dv-refused')
cell.title = why
if (this.descEl) this.descEl.textContent = why
+ // VISIBLE, under the cell. A title is a tooltip nobody hovers for while
+ // typing, and a red outline alone says "no" without saying why — the
+ // reader was left pressing Enter at a cell that would not take it.
+ this.dropRefusalTip()
+ const tip = document.createElement('div')
+ tip.className = 'dg-refuse-tip'
+ tip.setAttribute('role', 'alert')
+ tip.textContent = `${why} ${t('Press Esc to cancel.')}`
+ const r = cell.getBoundingClientRect()
+ tip.style.left = `${Math.round(r.left)}px`
+ tip.style.top = `${Math.round(r.bottom + 4)}px`
+ document.body.appendChild(tip)
+ this.refuseTip = tip
cell.focus()
}
+ private refuseTip: HTMLElement | null = null
+
+ private dropRefusalTip(): void {
+ this.refuseTip?.remove()
+ this.refuseTip = null
+ }
+
private wire(): void {
this.wireDropdowns()
// the fill handle: drag down to extend the selection and fill it
@@ -3704,7 +3773,7 @@ export class Grid {
const src = this.formulaAtPos(dataRow(s, rid), s.columns.findIndex((c) => c.id === colId))
cell.textContent = seed !== undefined ? seed
: src !== undefined ? src
- : (raw == null ? '' : String(raw))
+ : datasetEntered(raw, col) // the entered form, not the stored number (2.8)
cell.focus()
const range = document.createRange()
range.selectNodeContents(cell)
@@ -3725,6 +3794,7 @@ export class Grid {
}
cell.classList.remove('dv-refused')
cell.removeAttribute('title')
+ this.dropRefusalTip()
done = true
this.editing = null
const text = typed
@@ -4070,14 +4140,33 @@ export function coerceForColumn(text: string, type: ColumnType): unknown {
const s = text.trim()
if (s === '') return null
if (type === 'number' || type === 'money' || type === 'percent') {
- const n = Number(s.replace(/[,\s£$€¥%]/g, ''))
- if (!Number.isFinite(n)) return s // keep what they typed rather than
- return type === 'percent' && s.includes('%') ? n / 100 : n // silently zeroing
+ // import.ts's reader, as the spreadsheet kind uses: `£1,234.50`, `(5)`,
+ // and `12,5 %` to a German reader all mean what they say, and text that is
+ // not a whole number (`12abc`) is kept rather than read as its digits.
+ // A `%` divides by 100 in ANY numeric column — `15%` is 0.15 wherever it
+ // is typed — and a bare `15` in a percent column stays 15, as before.
+ const r = readEntryNumber(s, { prefer: viewerDecimal() })
+ return r ? r.n : s // keep what they typed rather than silently zeroing
}
if (type === 'bool') return /^(y|yes|true|1|✓)$/i.test(s)
return s
}
+/**
+ * A dataset cell's value in the form somebody would TYPE it — what the
+ * formula bar and the cell editor show (finding 2.8: a Percent column's 1 read
+ * `1` in the bar while the cell read 100%). The column's type says percent or
+ * money; `coerceForColumn` reads the result back to the same value.
+ */
+export function datasetEntered(v: unknown, col: Pick<Column, 'type' | 'format'>): string {
+ if (v == null) return ''
+ if (typeof v === 'number') {
+ const kind = col.type === 'percent' ? 'percent' : col.type === 'money' ? 'currency' : 'plain'
+ return enteredNumber(v, kind, col.format)
+ }
+ return String(v)
+}
+
/** Where a data bar starts, as a percentage — negatives run left of the axis. */
const bar0 = (cf: CellStyle): number =>
cf.bar ? (cf.bar.negative ? Math.max(0, (cf.bar as { axis?: number }).axis ?? 0) - cf.bar.pct : (cf.bar as { axis?: number }).axis ?? 0) : 0
diff --git a/dash/src/i18n/de.ts b/dash/src/i18n/de.ts
index ab25acfa..117829e8 100644
--- a/dash/src/i18n/de.ts
+++ b/dash/src/i18n/de.ts
@@ -754,6 +754,10 @@ export const de: Catalog = {
"Copy saved — you are still editing the original": "Kopie gespeichert — Sie bearbeiten weiterhin das Original",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "Die Absturzwiederherstellung ist für diese Arbeitsmappe deaktiviert – sie ist zu groß für eine Sicherungskopie. Speichern Sie häufig.",
"A backup of this workbook for yourself — same workbook, same live session.": "Eine Sicherungskopie für Sie — gleiche Arbeitsmappe, gleiche Live-Sitzung.",
+ "Press Esc to cancel.": "Mit Esc abbrechen.",
+ "There’s a problem with this formula: a bracket is opened and never closed.": "Mit dieser Formel stimmt etwas nicht: Eine Klammer wird geöffnet und nie geschlossen.",
+ "There’s a problem with this formula: it ends after “{near}”, where a value is missing.": "Mit dieser Formel stimmt etwas nicht: Sie endet nach „{near}“, wo ein Wert fehlt.",
+ "There’s a problem with this formula: “{near}” cannot go there.": "Mit dieser Formel stimmt etwas nicht: „{near}“ kann dort nicht stehen.",
"Apply to": "Anwenden auf",
"Custom…": "Benutzerdefiniert…",
"Not set": "Nicht festgelegt",
diff --git a/dash/src/i18n/es.ts b/dash/src/i18n/es.ts
index df6e6adc..24bc377c 100644
--- a/dash/src/i18n/es.ts
+++ b/dash/src/i18n/es.ts
@@ -754,6 +754,10 @@ export const es: Catalog = {
"Copy saved — you are still editing the original": "Copia guardada: sigues editando el original",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "La recuperación tras fallos está desactivada para este libro: es demasiado grande para guardar una copia de seguridad. Guarda a menudo.",
"A backup of this workbook for yourself — same workbook, same live session.": "Una copia de seguridad para ti — mismo libro, misma sesión en vivo.",
+ "Press Esc to cancel.": "Pulse Esc para cancelar.",
+ "There’s a problem with this formula: a bracket is opened and never closed.": "Hay un problema con esta fórmula: se abre un paréntesis que nunca se cierra.",
+ "There’s a problem with this formula: it ends after “{near}”, where a value is missing.": "Hay un problema con esta fórmula: termina después de «{near}», donde falta un valor.",
+ "There’s a problem with this formula: “{near}” cannot go there.": "Hay un problema con esta fórmula: «{near}» no puede ir ahí.",
"Apply to": "Aplicar a",
"Custom…": "Personalizado…",
"Not set": "Sin definir",
diff --git a/dash/src/i18n/fr.ts b/dash/src/i18n/fr.ts
index 5d9cecc2..337d00e3 100644
--- a/dash/src/i18n/fr.ts
+++ b/dash/src/i18n/fr.ts
@@ -754,6 +754,10 @@ export const fr: Catalog = {
"Copy saved — you are still editing the original": "Copie enregistrée — vous modifiez toujours l'original",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "La récupération après plantage est désactivée pour ce classeur : il est trop volumineux pour en garder une copie de secours. Enregistrez souvent.",
"A backup of this workbook for yourself — same workbook, same live session.": "Une sauvegarde pour vous — même classeur, même session live.",
+ "Press Esc to cancel.": "Appuyez sur Échap pour annuler.",
+ "There’s a problem with this formula: a bracket is opened and never closed.": "Cette formule pose problème : une parenthèse est ouverte et jamais fermée.",
+ "There’s a problem with this formula: it ends after “{near}”, where a value is missing.": "Cette formule pose problème : elle s’arrête après « {near} », là où il manque une valeur.",
+ "There’s a problem with this formula: “{near}” cannot go there.": "Cette formule pose problème : « {near} » ne peut pas se trouver là.",
"Apply to": "Appliquer à",
"Custom…": "Personnalisé…",
"Not set": "Non défini",
diff --git a/dash/src/i18n/it.ts b/dash/src/i18n/it.ts
index 6368184c..9e33fcb8 100644
--- a/dash/src/i18n/it.ts
+++ b/dash/src/i18n/it.ts
@@ -754,6 +754,10 @@ export const it: Catalog = {
"Copy saved — you are still editing the original": "Copia salvata: stai ancora modificando l'originale",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "Il ripristino dopo un arresto anomalo è disattivato per questa cartella di lavoro: è troppo grande per conservarne una copia di backup. Salva spesso.",
"A backup of this workbook for yourself — same workbook, same live session.": "Una copia di riserva per te — stessa cartella di lavoro, stessa sessione live.",
+ "Press Esc to cancel.": "Premi Esc per annullare.",
+ "There’s a problem with this formula: a bracket is opened and never closed.": "C’è un problema con questa formula: una parentesi viene aperta e mai chiusa.",
+ "There’s a problem with this formula: it ends after “{near}”, where a value is missing.": "C’è un problema con questa formula: finisce dopo «{near}», dove manca un valore.",
+ "There’s a problem with this formula: “{near}” cannot go there.": "C’è un problema con questa formula: «{near}» non può stare lì.",
"Apply to": "Applica a",
"Custom…": "Personalizzato…",
"Not set": "Non impostato",
diff --git a/dash/src/i18n/ja.ts b/dash/src/i18n/ja.ts
index 55e69a13..bb0ff65e 100644
--- a/dash/src/i18n/ja.ts
+++ b/dash/src/i18n/ja.ts
@@ -754,6 +754,10 @@ export const ja: Catalog = {
"Copy saved — you are still editing the original": "コピーを保存しました — 編集中なのは引き続き元のファイルです",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "このブックのクラッシュ復旧はオフです — 大きすぎてバックアップを保存できません。こまめに保存してください。",
"A backup of this workbook for yourself — same workbook, same live session.": "自分用のバックアップ — 同じブック・同じライブセッションです。",
+ "Press Esc to cancel.": "Esc キーで取り消します。",
+ "There’s a problem with this formula: a bracket is opened and never closed.": "この数式には問題があります: 括弧が開いたまま閉じられていません。",
+ "There’s a problem with this formula: it ends after “{near}”, where a value is missing.": "この数式には問題があります: 「{near}」の後で終わっていて、値が足りません。",
+ "There’s a problem with this formula: “{near}” cannot go there.": "この数式には問題があります: 「{near}」はそこに置けません。",
"Apply to": "適用先",
"Custom…": "カスタム…",
"Not set": "未設定",
diff --git a/dash/src/i18n/packed.ts b/dash/src/i18n/packed.ts
index 71ba0f66..292e89f4 100644
--- a/dash/src/i18n/packed.ts
+++ b/dash/src/i18n/packed.ts
@@ -395,6 +395,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Plot three numeric columns in 3D": ["3 つの数値列を 3D でプロットする","以 3D 绘制三个数值列","以 3D 繪製三個數值欄","Representar tres columnas numéricas en 3D","Représenter trois colonnes numériques en 3D","Drei numerische Spalten in 3D darstellen","Rappresenta tre colonne numeriche in 3D","Plotar três colunas numéricas em 3D"],
"Portrait": ["縦","纵向","直向","Vertical","Portrait","Hochformat","Verticale","Retrato"],
"Present ▸": ["プレゼン ▸","演示 ▸","放映 ▸","Presentar ▸","Présenter ▸","Präsentieren ▸","Presenta ▸","Apresentar ▸"],
+ "Press Esc to cancel.": ["Esc キーで取り消します。","按 Esc 取消。","按 Esc 取消。","Pulse Esc para cancelar.","Appuyez sur Échap pour annuler.","Mit Esc abbrechen.","Premi Esc per annullare.","Pressione Esc para cancelar."],
"Previous": ["前へ","上一张","上一張","Anterior","Précédent","Zurück","Precedente","Anterior"],
"Previous / next sheet": ["前 / 次のシート","上一个 / 下一个工作表","上一個 / 下一個工作表","Hoja anterior / siguiente","Feuille précédente / suivante","Vorheriges / nächstes Blatt","Foglio precedente / successivo","Planilha anterior / próxima"],
"Previous match (⇧⏎)": ["前の一致 (⇧⏎)","上一个匹配项 (⇧⏎)","上一個相符項 (⇧⏎)","Coincidencia anterior (⇧⏎)","Occurrence précédente (⇧⏎)","Vorheriger Treffer (⇧⏎)","Corrispondenza precedente (⇧⏎)","Ocorrência anterior (⇧⏎)"],
@@ -542,6 +543,9 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"The {what} this comment was on has been deleted. The comment is kept.": ["このコメントが付いていた {what} は削除されました。コメントは残ります。","此评论所在的{what}已被删除。评论已保留。","此註解所附著的{what}已被刪除。註解仍保留。","Se ha eliminado {what}, donde estaba este comentario. El comentario se conserva.","L’élément commenté ({what}) a été supprimé. Le commentaire est conservé.","Der Bezug dieses Kommentars ({what}) wurde gelöscht. Der Kommentar bleibt erhalten.","L’elemento a cui era riferito questo commento ({what}) è stato eliminato. Il commento viene conservato.","O {what} em que este comentário estava foi excluído. O comentário foi mantido."],
"Theme": ["テーマ","配色主题","佈景主題","Tema","Thème","Design","Tema","Tema"],
"There is nothing to paste. This browser will not hand a menu the system clipboard, so ⌘V pastes what a menu cannot reach.": ["貼り付けるものがありません。このブラウザーはメニューにシステムのクリップボードを渡さないため、メニューでは届かないものも ⌘V なら貼り付けられます。","没有可粘贴的内容。此浏览器不会把系统剪贴板交给菜单,因此菜单够不到的内容可以用 ⌘V 粘贴。","沒有可貼上的內容。此瀏覽器不會把系統剪貼簿交給選單,因此選單構不到的內容可以用 ⌘V 貼上。","No hay nada que pegar. Este navegador no le entrega el portapapeles del sistema a un menú, así que ⌘V pega lo que un menú no alcanza.","Il n’y a rien à coller. Ce navigateur ne donne pas le presse-papiers du système à un menu ; ⌘V colle donc ce qu’un menu ne peut pas atteindre.","Es gibt nichts zum Einfügen. Dieser Browser gibt einem Menü die Systemzwischenablage nicht heraus, deshalb fügt ⌘V ein, was ein Menü nicht erreichen kann.","Non c’è nulla da incollare. Questo browser non passa a un menu gli appunti di sistema, quindi ⌘V incolla ciò che un menu non riesce a raggiungere.","Não há nada para colar. Este navegador não entrega a área de transferência do sistema a um menu, então o ⌘V cola o que um menu não alcança."],
+ "There’s a problem with this formula: a bracket is opened and never closed.": ["この数式には問題があります: 括弧が開いたまま閉じられていません。","此公式有问题:有一个括号打开后没有闭合。","此公式有問題:有一個括號開啟後沒有關閉。","Hay un problema con esta fórmula: se abre un paréntesis que nunca se cierra.","Cette formule pose problème : une parenthèse est ouverte et jamais fermée.","Mit dieser Formel stimmt etwas nicht: Eine Klammer wird geöffnet und nie geschlossen.","C’è un problema con questa formula: una parentesi viene aperta e mai chiusa.","Há um problema com esta fórmula: um parêntese é aberto e nunca fechado."],
+ "There’s a problem with this formula: it ends after “{near}”, where a value is missing.": ["この数式には問題があります: 「{near}」の後で終わっていて、値が足りません。","此公式有问题:它在“{near}”之后就结束了,缺少一个值。","此公式有問題:它在「{near}」之後就結束了,缺少一個值。","Hay un problema con esta fórmula: termina después de «{near}», donde falta un valor.","Cette formule pose problème : elle s’arrête après « {near} », là où il manque une valeur.","Mit dieser Formel stimmt etwas nicht: Sie endet nach „{near}“, wo ein Wert fehlt.","C’è un problema con questa formula: finisce dopo «{near}», dove manca un valore.","Há um problema com esta fórmula: termina depois de «{near}», onde falta um valor."],
+ "There’s a problem with this formula: “{near}” cannot go there.": ["この数式には問題があります: 「{near}」はそこに置けません。","此公式有问题:“{near}”不能放在那里。","此公式有問題:「{near}」不能放在那裡。","Hay un problema con esta fórmula: «{near}» no puede ir ahí.","Cette formule pose problème : « {near} » ne peut pas se trouver là.","Mit dieser Formel stimmt etwas nicht: „{near}“ kann dort nicht stehen.","C’è un problema con questa formula: «{near}» non può stare lì.","Há um problema com esta fórmula: «{near}» não pode ficar aí."],
"These are yours, not the workbook’s: they are kept in this browser and never written into the file, so the same workbook can be English and light on your screen and Japanese and dark on someone else’s.": ["これらはブックのものではなく、あなたのものです。このブラウザにだけ保存され、ファイルには決して書き込まれません — 同じブックが、あなたの画面では英語でライト、別の人の画面では日本語でダークになることもあります。","这些设置属于你,而不属于工作簿:它们只保存在此浏览器中,永远不会写入文件 — 所以同一个工作簿可以在你的屏幕上是英语浅色,在别人的屏幕上是日语深色。","這些設定屬於你,而不屬於活頁簿:它們只保存在這個瀏覽器裡,永遠不會寫進檔案 — 所以同一份活頁簿可以在你的螢幕上是英文淺色,在別人的螢幕上是日文深色。","Son tuyos, no del libro: se guardan en este navegador y nunca se escriben en el archivo, así que el mismo libro puede verse en inglés y claro en tu pantalla y en japonés y oscuro en la de otra persona.","Ils sont à vous, pas au classeur : ils restent dans ce navigateur et ne sont jamais écrits dans le fichier — un même classeur peut donc être en anglais et clair sur votre écran, en japonais et sombre sur celui d’une autre personne.","Sie gehören Ihnen, nicht der Arbeitsmappe: Sie bleiben in diesem Browser und werden nie in die Datei geschrieben — dieselbe Arbeitsmappe kann also auf Ihrem Bildschirm englisch und hell sein und auf einem anderen japanisch und dunkel.","Sono tue, non della cartella di lavoro: restano in questo browser e non vengono mai scritte nel file, così la stessa cartella può essere in inglese e chiara sul tuo schermo e in giapponese e scura su quello di un altro.","Estas são suas, não da pasta de trabalho: ficam guardadas neste navegador e nunca são gravadas no arquivo, então a mesma pasta pode estar em inglês e no tema claro na sua tela e em japonês e escuro na de outra pessoa."],
"These cells": ["これらのセル","这些单元格","這些儲存格","Estas celdas","Ces cellules","Diese Zellen","Queste celle","Estas células"],
"This action needs a dataset sheet, and the sheet on screen is not one.": ["この操作にはデータセットのシートが必要ですが、表示中のシートはそれではありません。","此操作需要数据集工作表,而当前显示的不是。","此動作需要資料集工作表,而目前顯示的不是。","Esta acción necesita una hoja de conjunto de datos, y la que está en pantalla no lo es.","Cette action nécessite une feuille de jeu de données, et celle affichée n’en est pas une.","Diese Aktion braucht ein Datensatzblatt, und das angezeigte ist keines.","Questa azione richiede un foglio set di dati, e quello a schermo non lo è.","Esta ação precisa de uma planilha de conjunto de dados, e a planilha em tela não é uma."],
diff --git a/dash/src/i18n/pt.ts b/dash/src/i18n/pt.ts
index a05eff18..fe2c8ae2 100644
--- a/dash/src/i18n/pt.ts
+++ b/dash/src/i18n/pt.ts
@@ -767,6 +767,10 @@ export const pt: Catalog = {
"Copy saved — you are still editing the original": "Cópia salva — você continua editando o original",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "A recuperação de falhas está desativada para esta pasta de trabalho: ela é grande demais para manter uma cópia de segurança. Salve com frequência.",
"A backup of this workbook for yourself — same workbook, same live session.": "Um backup desta pasta de trabalho para você — mesma pasta de trabalho, mesma sessão ao vivo.",
+ "Press Esc to cancel.": "Pressione Esc para cancelar.",
+ "There’s a problem with this formula: a bracket is opened and never closed.": "Há um problema com esta fórmula: um parêntese é aberto e nunca fechado.",
+ "There’s a problem with this formula: it ends after “{near}”, where a value is missing.": "Há um problema com esta fórmula: termina depois de «{near}», onde falta um valor.",
+ "There’s a problem with this formula: “{near}” cannot go there.": "Há um problema com esta fórmula: «{near}» não pode ficar aí.",
"Apply to": "Aplicar a",
"Custom…": "Personalizado…",
"Not set": "Não definido",
diff --git a/dash/src/i18n/zh-Hans.ts b/dash/src/i18n/zh-Hans.ts
index f8307881..16ea864d 100644
--- a/dash/src/i18n/zh-Hans.ts
+++ b/dash/src/i18n/zh-Hans.ts
@@ -754,6 +754,10 @@ export const zhHans: Catalog = {
"Copy saved — you are still editing the original": "副本已保存 — 你仍在编辑原文件",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "此工作簿的崩溃恢复已关闭 — 文件太大,无法保留备份。请经常保存。",
"A backup of this workbook for yourself — same workbook, same live session.": "自己留存的备份 — 同一个工作簿、同一个实时会话。",
+ "Press Esc to cancel.": "按 Esc 取消。",
+ "There’s a problem with this formula: a bracket is opened and never closed.": "此公式有问题:有一个括号打开后没有闭合。",
+ "There’s a problem with this formula: it ends after “{near}”, where a value is missing.": "此公式有问题:它在“{near}”之后就结束了,缺少一个值。",
+ "There’s a problem with this formula: “{near}” cannot go there.": "此公式有问题:“{near}”不能放在那里。",
"Apply to": "应用于",
"Custom…": "自定义…",
"Not set": "未设置",
diff --git a/dash/src/i18n/zh-Hant.ts b/dash/src/i18n/zh-Hant.ts
index 86b4e381..03b08a13 100644
--- a/dash/src/i18n/zh-Hant.ts
+++ b/dash/src/i18n/zh-Hant.ts
@@ -754,6 +754,10 @@ export const zhHant: Catalog = {
"Copy saved — you are still editing the original": "副本已儲存 — 你仍在編輯原始檔案",
"Crash recovery is off for this workbook — it’s too large to keep a backup copy. Save often.": "此活頁簿的當機復原已關閉 — 檔案太大,無法保留備份。請經常儲存。",
"A backup of this workbook for yourself — same workbook, same live session.": "自己留存的備份 — 同一個活頁簿、同一個即時會話。",
+ "Press Esc to cancel.": "按 Esc 取消。",
+ "There’s a problem with this formula: a bracket is opened and never closed.": "此公式有問題:有一個括號開啟後沒有關閉。",
+ "There’s a problem with this formula: it ends after “{near}”, where a value is missing.": "此公式有問題:它在「{near}」之後就結束了,缺少一個值。",
+ "There’s a problem with this formula: “{near}” cannot go there.": "此公式有問題:「{near}」不能放在那裡。",
"Apply to": "套用至",
"Custom…": "自訂…",
"Not set": "未設定",
diff --git a/dash/src/import.ts b/dash/src/import.ts
index 1fd78ec0..2aa7197b 100644
--- a/dash/src/import.ts
+++ b/dash/src/import.ts
@@ -183,11 +183,6 @@ export interface Inference {
const BOOLS = new Set(['true', 'false', 'yes', 'no', 'y', 'n', '1', '0', 't', 'f'])
const blank = (s: string) => s.trim() === ''
-/**
- * Read a number under ONE convention. `point` is the decimal separator; the
- * other of . and , is then the grouping separator and must appear only in
- * groups of three.
- */
/**
* The digit shape each convention allows, checked in full rather than by
* stripping characters until something parses.
@@ -197,28 +192,141 @@ const blank = (s: string) => s.trim() === ''
* `2026-01-15`, which then read as the NUMBER 20260115. A date column silently
* became a number column, and every value in it was eight digits of nonsense.
*/
-const NUM_DOT = /^(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?$/
-const NUM_COMMA = /^(?:\d{1,3}(?:\.\d{3})+|\d+)(?:,\d+)?$/
+const NUM_DOT = /^(?:(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|\.\d+)$/
+const NUM_COMMA = /^(?:(?:\d{1,3}(?:\.\d{3})+|\d+)(?:,\d+)?|,\d+)$/
+/** Exponent notation, which only the dot convention spells (`1e3`, `2.5E-4`). */
+const NUM_EXP = /^\d+(?:\.\d+)?[eE][-+]?\d+$/
-function readNumber(raw: string, point: '.' | ','): number | null {
+/**
+ * The currency marks worth peeling — a symbol a person would type, not every
+ * glyph in Unicode — plus the `US$` / `A$` / `C$` spellings. Either end of the
+ * field: `$5` and `5 €` are both how somebody writes money.
+ */
+const SYM_LEAD = /^(?:[$£€¥₹₽₩₪₺]|[A-Z]{1,3}\$)\s?/
+const SYM_TRAIL = /\s?(?:[$£€¥₹₽₩₪₺])$/
+
+/** A number field with its NOTATION taken off: sign, currency mark, percent. */
+interface Peeled { neg: boolean; symbol: string; pct: boolean; body: string }
+
+function peel(raw: string): Peeled | null {
let s = raw.trim()
if (s === '') return null
- // accounting negatives
let neg = false
+ // accounting negatives — `(1,200)` is -1200, and the only bracket form worth it
if (/^\(.*\)$/.test(s)) { neg = true; s = s.slice(1, -1).trim() }
- // currency and spacing, either end
- s = s.replace(/^[\s$£€¥]+/, '').replace(/[\s$£€¥]+$/, '')
+ let symbol = ''
+ const lead = s.match(SYM_LEAD)
+ if (lead) { symbol = lead[0].trim(); s = s.slice(lead[0].length).trim() }
+ if (s.startsWith('-')) { neg = !neg; s = s.slice(1).trim() }
+ else if (s.startsWith('+')) s = s.slice(1).trim()
+ // the symbol may sit after the sign — `-$5` as well as `$-5`
+ if (!symbol) {
+ const again = s.match(SYM_LEAD)
+ if (again) { symbol = again[0].trim(); s = s.slice(again[0].length).trim() }
+ }
// a trailing percent is part of the NOTATION, not the number
- if (s.endsWith('%')) s = s.slice(0, -1).trim()
- if (s.startsWith('-')) { neg = true; s = s.slice(1) }
- else if (s.startsWith('+')) s = s.slice(1)
- if (!(point === '.' ? NUM_DOT : NUM_COMMA).test(s)) return null
+ let pct = false
+ if (s.endsWith('%')) { pct = true; s = s.slice(0, -1).trim() }
+ if (!symbol) {
+ const trail = s.match(SYM_TRAIL)
+ if (trail) { symbol = trail[0].trim(); s = s.slice(0, -trail[0].length).trim() }
+ }
+ if (!pct && s.endsWith('%')) { pct = true; s = s.slice(0, -1).trim() }
+ if (!/\d/.test(s)) return null
+ return { neg, symbol, pct, body: s }
+}
+
+/** The digits of a peeled body under ONE convention, or null. */
+function digitsUnder(body: string, point: '.' | ','): number | null {
+ if (!(point === '.' ? NUM_DOT : NUM_COMMA).test(body)) return null
const group = point === '.' ? ',' : '.'
- s = s.split(group).join('')
+ let s = body.split(group).join('')
if (point === ',') s = s.replace(',', '.')
const n = Number(s)
- if (!Number.isFinite(n)) return null
- return neg ? -n : n
+ return Number.isFinite(n) ? n : null
+}
+
+/**
+ * Read a number under ONE convention. `point` is the decimal separator; the
+ * other of . and , is then the grouping separator and must appear only in
+ * groups of three. This is what `inferColumn` votes with, column by column.
+ *
+ * The percent is NOT applied here: a column decides that once, in `coerce`.
+ */
+function readNumber(raw: string, point: '.' | ','): number | null {
+ const p = peel(raw)
+ if (!p) return null
+ const n = digitsUnder(p.body, point)
+ if (n === null) return null
+ return p.neg ? -n : n
+}
+
+/** One typed field, read as a number, with the notation it was written in. */
+export interface EntryNumber {
+ /** the value — a `%` has ALREADY been applied, so `15%` is 0.15 */
+ n: number
+ /** the field carried a `%` */
+ pct: boolean
+ /** the currency mark it carried, verbatim (`$`, `£`, `US$`), or '' */
+ symbol: string
+ /** decimals actually written, so a stamped format can match what was typed */
+ dp: number
+ /** the field carried a thousands separator */
+ group: boolean
+}
+
+/**
+ * ONE field, read as a number — the reading every single-value caller shares:
+ * typing into a spreadsheet cell (cellprops.ts `coerceInput`), a TSV paste, the
+ * formula engine coercing text in arithmetic (formula.ts `num`), and `VALUE()`.
+ *
+ * The SAME digit shapes `inferColumn` votes with, so a value means the same
+ * thing typed, pasted, imported and computed. What a single value cannot do is
+ * vote, so the decimal convention is settled the only other way there is:
+ *
+ * • when the field reads under exactly ONE convention, that one — `3,50` is
+ * 3.5 to everybody, because `,50` cannot be a thousands group;
+ * • when it reads under BOTH (`1,234`, `1.234`), `prefer` decides. A typist's
+ * entry passes the VIEWER's decimal separator, which is what that person
+ * meant by what they typed; the formula engine passes '.', import's own
+ * tie-break, because a formula result is DOCUMENT data and must come out
+ * the same for every reader of the file.
+ *
+ * `strict` is cellprops.ts rule 3: a leading zero (`007`) disqualifies the
+ * field, because in an unformatted cell the zeros are the information.
+ */
+export function readEntryNumber(
+ raw: string, opts: { prefer?: '.' | ','; strict?: boolean } = {},
+): EntryNumber | null {
+ const p = peel(raw)
+ if (!p) return null
+ const prefer = opts.prefer ?? '.'
+ let n: number | null = null
+ let point: '.' | ',' = '.'
+ if (NUM_EXP.test(p.body)) {
+ n = Number(p.body)
+ } else {
+ const dot = digitsUnder(p.body, '.')
+ const comma = digitsUnder(p.body, ',')
+ if (dot !== null && comma !== null) { point = prefer; n = prefer === '.' ? dot : comma }
+ else if (dot !== null) { point = '.'; n = dot }
+ else if (comma !== null) { point = ','; n = comma }
+ }
+ if (n === null || !Number.isFinite(n)) return null
+ if (opts.strict && /^0\d/.test(p.body)) return null
+ const group = point === '.' ? ',' : '.'
+ const eAt = p.body.search(/[eE]/)
+ const mant = eAt < 0 ? p.body : p.body.slice(0, eAt)
+ const at = mant.indexOf(point)
+ let v = p.neg ? -n : n
+ if (p.pct) v /= 100
+ return {
+ n: v,
+ pct: p.pct,
+ symbol: p.symbol,
+ dp: at < 0 ? 0 : mant.length - at - 1,
+ group: mant.includes(group),
+ }
}
const DATE_ISO = /^(\d{4})-(\d{2})-(\d{2})([T ].*)?$/
diff --git a/dash/src/main.ts b/dash/src/main.ts
index 86a2a92b..1fb72a4f 100644
--- a/dash/src/main.ts
+++ b/dash/src/main.ts
@@ -730,9 +730,43 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', sav
// The label names the RANGE, so it is wrong the moment the selection moves.
syncBridge()
}
+ // A formula the grid will not take keeps the bar OPEN with the reason under
+ // it (finding 3.4) — the same refusal the in-cell editor makes. Escape
+ // abandons the edit and puts the cell's own contents back.
+ let fxValueAtFocus = ''
+ const fxTipClear = () => {
+ fxEl.classList.remove('dv-refused')
+ fxEl.removeAttribute('aria-invalid')
+ document.querySelector('.dx-fx-tip')?.remove()
+ }
+ fxEl.addEventListener('focus', () => { fxValueAtFocus = fxEl.value })
+ fxEl.addEventListener('input', fxTipClear)
+ fxEl.addEventListener('blur', fxTipClear)
fxEl.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape') {
+ e.preventDefault()
+ fxEl.value = fxValueAtFocus
+ fxTipClear()
+ fxEl.blur()
+ return
+ }
if (e.key !== 'Enter') return
- grid.setActiveCell(fxEl.value)
+ const why = grid.setActiveCell(fxEl.value)
+ if (why !== null) {
+ e.preventDefault()
+ fxTipClear()
+ fxEl.classList.add('dv-refused')
+ fxEl.setAttribute('aria-invalid', 'true')
+ const tip = document.createElement('div')
+ tip.className = 'dg-refuse-tip dx-fx-tip'
+ tip.setAttribute('role', 'alert')
+ tip.textContent = `${why} ${t('Press Esc to cancel.')}`
+ const r = fxEl.getBoundingClientRect()
+ tip.style.left = `${Math.round(r.left)}px`
+ tip.style.top = `${Math.round(r.bottom + 4)}px`
+ document.body.appendChild(tip)
+ return
+ }
fxEl.blur()
})
diff --git a/dash/src/steps.ts b/dash/src/steps.ts
index efb1e168..1d684a6c 100644
--- a/dash/src/steps.ts
+++ b/dash/src/steps.ts
@@ -758,8 +758,8 @@ function stepLimit(frame: Frame, step: { n?: unknown; offset?: unknown }, at: nu
// where two implementations diverge and where the divergence is invisible.
//
// The five hot ones are open-coded because a group-by over ten million rows
-// cannot afford `evaluate` per group; they reproduce formula.ts's coercion
-// (`num`) EXACTLY rather than approximately, and scripts/test-dash-steps.ts
+// cannot afford `evaluate` per group; they reproduce formula.ts's range reading
+// (`rangeNumber`) EXACTLY rather than approximately, and scripts/test-dash-steps.ts
// cross-checks every one of them against `evaluate` on adversarial data. If
// that rig ever fails, this fast path is wrong and formula.ts is right.
//
@@ -767,19 +767,16 @@ function stepLimit(frame: Frame, step: { n?: unknown; offset?: unknown }, at: nu
// through `evaluate` and costs nothing to support, which is the whole argument
// for having one expression language instead of two.
-/** formula.ts's `num`, reproduced (it is not exported). Non-numeric → null.
- * The blank cases are handled by the CALLER, matching formula.ts's split
- * between `num` (a blank is 0, because `=A1+1` on an empty cell is 1) and
- * `numbersIn` (a blank is absent, because AVERAGE over three numbers and seven
- * empty cells is the mean of three). Getting that split wrong is a wrong
- * answer in exact proportion to how sparse the column is. */
+/** What one cell of a column contributes to an aggregate — formula.ts's
+ * `rangeNumber` (rule 1 above its `num`): a NUMBER, or nothing. Text is
+ * skipped even when it looks like a number, and so are booleans, because a
+ * column handed to SUM is a RANGE, and that is what Excel does with one. This
+ * used to reproduce `num`, which read the text "50%" as 50 — the arithmetic
+ * half of review finding 3.1. The blank cases are handled by the CALLER
+ * (formula.ts `numbersIn`: a blank is absent, because AVERAGE over three
+ * numbers and seven empty cells is the mean of three). */
function fnum(v: Cell): number | null {
- if (isErr(v)) return null
- 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 : null
+ return typeof v === 'number' ? v : null
}
/** Aggregate names this file open-codes, lowercased. */
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index b4a5307e..fb0e93fe 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -11557,3 +11557,47 @@ selection by ROW identity: whole columns stay whole, single-row ranges move
with their row, and a taller block collapses to the cursor cell (its rows no
longer sit together). Point mode inserts a dataset reference in the FILE's
row and column numbering (`tableCellSource`), not the sorted view's.
+
+## 2026-10-20 — bento/dash: what typing into a spreadsheet cell stores, and text in arithmetic
+
+Typing into a spreadsheet cell (and pasting text into one) goes through
+`cellprops.ts coerceInput`. It was written and tested earlier but never wired:
+grid.ts kept a narrower reader, so `15%` and `$5` were stored as TEXT. The rules
+are in cellprops.ts's header. Two of them changed here:
+
+- **Unambiguous dates are read from typing.** ISO (`2026-03-04`) and a named
+ month (`Mar 4 2026`, `4 March 2026`) store the canonical `YYYY-MM-DD` string
+ and stamp the Date format. A slash date stays text from typing even when the
+ day is over 12. Otherwise `13/2/2026` would be a date and `12/2/2026` one row
+ up would be text. In a cell already formatted Date, every unambiguous spelling
+ is read, as before. The refusal of `3/4/2026` is unchanged.
+- **One digit reader.** `import.ts readEntryNumber` reads typed entry, the
+ formula engine's text coercion, and (through the same digit shapes)
+ `inferColumn`. A field that fits only one decimal convention reads that way
+ for everyone (`3,50` is 3.5). A field that fits both (`1,234`) follows the
+ viewer's locale when typed, because the typist meant something by it. The
+ formula engine always uses '.', import's own tie-break, because a computed
+ value is document data and must not depend on who opens the file.
+
+**Text in arithmetic follows Excel** (formula.ts, the block above `num`). A
+range or reference given to an aggregate counts only its numbers: text, even
+numeric-looking text, and booleans are skipped. This includes the step
+engine's open-coded fast path, which test-dash-steps.ts keeps bit-identical. A
+value written directly as an argument is coerced, and #VALUE! if it is not a
+number (COUNT just doesn't count it). Direct arithmetic coerces text only when
+the whole string reads as a typed number (`"15%"` is 0.15, `"(5)"` is -5).
+Anything else is #VALUE!; the old code read whatever digits were left after
+stripping symbols. Aggregates take every argument (`SUM(1,2,3)` was 1), and
+`%` is a postfix operator (`=10*15%` was 150).
+
+**A cell formula that does not parse is refused at entry**, in the cell editor
+and in the formula bar (`cellFormulaProblem` → `formula.ts syntaxProblem`). It
+is never refused on evaluation: formulas already in a file evaluate as
+leniently as before, because refusing them would put a blank where an answer
+was. The formula bar shows a value cell's ENTERED form (`cellprops.ts
+enteredForm`): `100%`, `$300.50`, or `'15%` for text that would otherwise be
+read back as a number. Re-entering what the bar shows always stores the same
+value again.
+
+Guarded by scripts/test-dash-entryparse.ts and
+scripts/test-dash-entryparse-browser.mjs.
diff --git a/scripts/test-dash-canvas.ts b/scripts/test-dash-canvas.ts
index b9ea811d..90b2ffb9 100644
--- a/scripts/test-dash-canvas.ts
+++ b/scripts/test-dash-canvas.ts
@@ -144,8 +144,8 @@ ok(canvasValue('1,200') === 1200, '"1,200" is 1200 — people type separators')
ok(canvasValue('1e3') === 1000, 'exponent notation is a number')
ok(canvasValue('TRUE') === true, '"TRUE" is a boolean')
ok(canvasValue('false') === false, '"false" is a boolean, any case')
-ok(canvasValue('2026-01-01') === '2026-01-01', 'an ISO date stays text, as the dataset path stores it')
-ok(canvasValue('50%') === '50%', 'a percent stays text — coercing it would invent a FORMAT')
+ok(canvasValue('2026-01-01') === '2026-01-01', 'an ISO date is stored as the ISO string, as the dataset path stores a date (the cell also gets the Date format — test-dash-entryparse.ts)')
+ok(canvasValue('50%') === 0.5, 'a percent is the number it denotes, 0.5 — it used to stay TEXT, which SUM then read as 50 (review 3.1)')
ok(canvasValue('N/A') === 'N/A', 'text is text')
ok(canvasValue('.') === '.', '"." is not the number 0')
ok(canvasValue('+') === '+', '"+" is not the number 0')
diff --git a/scripts/test-dash-entryparse-browser.mjs b/scripts/test-dash-entryparse-browser.mjs
new file mode 100644
index 00000000..1fe66450
--- /dev/null
+++ b/scripts/test-dash-entryparse-browser.mjs
@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Typing into a SPREADSHEET cell in the built shell: what the cells show, what
+// the formulas over them compute, what the formula bar says, and what happens
+// to a formula that does not parse.
+//
+// npm run build:single --prefix dash && node scripts/test-dash-entryparse-browser.mjs
+//
+// The review's exact keystrokes (finding 3.1): on the Scratch sheet, G13..G19
+// receive 10, $5, 15%, =SUM(G13:G15), =G13+G14, =COUNT(G13:G15), =G13*G15.
+// Before the fix the grid showed 30, 15, 3 and 150 — "15%" was stored as text
+// and the engine read the text as 15. Now 15.15, 15, 3 and 1.5. Then 2.8 (the
+// bar over 15% says 15%, over a date says the date) and 3.4 (=A11+ is refused
+// in the cell AND in the formula bar, with the reason visible; Esc cancels).
+//
+// node scripts/test-dash-entryparse.ts holds the full table; this row proves
+// the real editor, keyboard and paint reach it.
+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
+
+const SHELL = new URL('../dash/dist-single/Bento_Dash.bento.html', import.meta.url).href
+const SHOTS = process.env.SHOT_DIR
+
+let checks = 0, failures = 0
+const ok = (c, m) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }
+
+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })
+try {
+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'en-US' })
+ const page = await ctx.newPage()
+ const errors = []
+ page.on('pageerror', (e) => errors.push(e.message))
+ await page.goto(SHELL)
+ await page.waitForFunction(() => window.bento?.doc && document.querySelector('.dg-cell'))
+ const cellAt = (row, col) => page.locator(`.dg-row[data-row="${row}"] .dg-cell:not(.dg-gutter)`).nth(col)
+
+ // ---- the review's 2.8 shot, exactly: Pipeline F1, a Percent column showing 100%
+ await page.locator('.dx-tab', { hasText: 'Pipeline' }).click()
+ await page.waitForTimeout(200)
+ await page.locator('.dg-cell[data-col]').filter({ hasText: '100%' }).first().click()
+ ok(await page.locator('.dx-fx-input').inputValue() === '100%',
+ `the formula bar over Pipeline's Probability 100% reads "100%", not "1" (got "${await page.locator('.dx-fx-input').inputValue()}")`)
+
+ await page.locator('.dx-tab', { hasText: 'Scratch' }).click()
+ await page.waitForTimeout(300)
+ const textAt = (row, col) => cellAt(row, col).evaluate((el) => el.textContent.trim())
+ const stored = (key) => page.evaluate((k) => {
+ const s = window.bento.doc.sheets.find((x) => x.name === 'Scratch')
+ return s.cells[k] ?? null
+ }, key)
+
+ // ---- the review's keystrokes, G13 down
+ await cellAt(12, 6).click()
+ for (const t of ['10', '$5', '15%', '=SUM(G13:G15)', '=G13+G14', '=COUNT(G13:G15)', '=G13*G15']) {
+ await page.keyboard.type(t)
+ await page.keyboard.press('Enter')
+ }
+ await page.waitForTimeout(300)
+ const shown = []
+ for (let r = 12; r < 19; r++) shown.push(await textAt(r, 6))
+ console.log(` G13..G19 read: ${shown.join(' | ')}`)
+ ok(shown[1] === '$5' && shown[2] === '15%', `$5 and 15% display as typed ("${shown[1]}", "${shown[2]}")`)
+ ok(JSON.stringify(await stored('G15')) === JSON.stringify({ v: 0.15, format: '0%' }),
+ `15% is STORED as 0.15 with a percent format (${JSON.stringify(await stored('G15'))})`)
+ ok(JSON.stringify(await stored('G14')) === JSON.stringify({ v: 5, format: '$#,##0' }),
+ `$5 is stored as 5 with a currency format that keeps the $ (${JSON.stringify(await stored('G14'))})`)
+ ok(shown[3] === '15.15', `=SUM(G13:G15) shows 15.15 — the review measured 30 (got "${shown[3]}")`)
+ ok(shown[4] === '15', `=G13+G14 shows 15 (got "${shown[4]}")`)
+ ok(shown[5] === '3', `=COUNT(G13:G15) shows 3 (got "${shown[5]}")`)
+ ok(/^1\.50?$/.test(shown[6]), `=G13*G15 shows 1.5 — the review measured 150 (got "${shown[6]}")`)
+
+ // ---- dates
+ await cellAt(12, 7).click()
+ for (const t of ['2026-03-04', 'Mar 4 2026', '3/4/2026']) {
+ await page.keyboard.type(t)
+ await page.keyboard.press('Enter')
+ }
+ await page.waitForTimeout(200)
+ ok((await stored('H13'))?.v === '2026-03-04' && (await stored('H13'))?.format === 'yyyy-mm-dd',
+ `ISO 2026-03-04 is a date (${JSON.stringify(await stored('H13'))})`)
+ ok((await stored('H14'))?.v === '2026-03-04' && (await stored('H14'))?.format === 'yyyy-mm-dd',
+ `"Mar 4 2026" is the same date (${JSON.stringify(await stored('H14'))})`)
+ ok(JSON.stringify(await stored('H15')) === JSON.stringify({ v: '3/4/2026' }),
+ `"3/4/2026" is still refused as a date and kept as text (${JSON.stringify(await stored('H15'))})`)
+
+ // ---- the formula bar shows the ENTERED form (2.8)
+ const fx = page.locator('.dx-fx-input')
+ // the review's own case: a value STORED as a number and THEN formatted as a
+ // percent from the panel — the bar said 1 for a cell reading 100%
+ await cellAt(12, 8).click()
+ await page.keyboard.type('1')
+ await page.keyboard.press('Enter')
+ await cellAt(12, 8).click()
+ const fmtSelect = page.locator('.dp-panel select').filter({ has: page.locator('option[value="percent"]') }).first()
+ await fmtSelect.selectOption('percent')
+ await page.waitForTimeout(150)
+ ok(await textAt(12, 8) === '100%' && (await stored('I13'))?.v === 1,
+ `the cell holds 1 and reads 100% (${await textAt(12, 8)}, ${JSON.stringify(await stored('I13'))})`)
+ await cellAt(13, 8).click()
+ await cellAt(12, 8).click()
+ ok(await fx.inputValue() === '100%', `the formula bar over it reads "100%", not 1 (got "${await fx.inputValue()}")`)
+ await cellAt(14, 6).click()
+ ok(await fx.inputValue() === '15%', `the formula bar over G15 reads "15%", not 0.15 (got "${await fx.inputValue()}")`)
+ await cellAt(13, 6).click()
+ ok(await fx.inputValue() === '$5', `…over G14 reads "$5" (got "${await fx.inputValue()}")`)
+ await cellAt(13, 7).click()
+ ok(await fx.inputValue() === '2026-03-04', `…over H14 reads the date "2026-03-04" (got "${await fx.inputValue()}")`)
+
+ // ---- a malformed formula in the CELL (3.4)
+ await cellAt(19, 6).click()
+ await page.keyboard.type('=A11+')
+ await page.keyboard.press('Enter')
+ await page.waitForTimeout(150)
+ const editing = page.locator('.dg-cell.dg-editing')
+ ok(await editing.count() === 1 && (await editing.textContent()) === '=A11+',
+ 'Enter on =A11+ leaves the editor OPEN with the text in it')
+ ok(await stored('G20') === null, 'and commits nothing')
+ const tip = page.locator('.dg-refuse-tip')
+ const tipBox = (await tip.count()) ? await tip.boundingBox() : null
+ ok(tipBox && await tip.isVisible() && tipBox.y > 0 && tipBox.y + tipBox.height < 900,
+ `the reason is visible under the cell: "${tipBox ? await tip.textContent() : 'NO MESSAGE'}"`)
+ if (SHOTS) await page.screenshot({ path: `${SHOTS}/entryparse-refused.png` })
+ await page.keyboard.press('Escape')
+ await page.waitForTimeout(100)
+ ok(await editing.count() === 0 && await tip.count() === 0 && await stored('G20') === null,
+ 'Escape cancels: editor closed, message gone, nothing written')
+
+ // ---- …and in the formula bar
+ await cellAt(19, 6).click()
+ await fx.click()
+ await fx.fill('=SUM(')
+ await fx.press('Enter')
+ await page.waitForTimeout(100)
+ ok(await stored('G20') === null && await page.locator('.dx-fx-tip').isVisible(),
+ 'the formula bar refuses =SUM( too, with the reason shown')
+ if (SHOTS) await page.screenshot({ path: `${SHOTS}/entryparse-fx-refused.png` })
+ await fx.press('Escape')
+ ok(await page.locator('.dx-fx-tip').count() === 0 && await fx.inputValue() === '',
+ 'Escape in the bar puts the cell\'s own contents back')
+ await cellAt(19, 6).click()
+ await fx.click()
+ await fx.fill('=SUM(G13:G15)')
+ await fx.press('Enter')
+ await page.waitForTimeout(150)
+ ok((await stored('G20'))?.f === '=SUM(G13:G15)' && await textAt(19, 6) === '15.15',
+ 'a formula that parses lands from the bar as before')
+ if (SHOTS) await page.screenshot({ path: `${SHOTS}/entryparse-after.png` })
+
+ ok(errors.length === 0, `no page errors (${errors.join(' | ') || 'none'})`)
+} finally {
+ await browser.close()
+}
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/scripts/test-dash-entryparse.ts b/scripts/test-dash-entryparse.ts
new file mode 100644
index 00000000..8e83258a
--- /dev/null
+++ b/scripts/test-dash-entryparse.ts
@@ -0,0 +1,375 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/dash TYPED-ENTRY rig — what a spreadsheet cell IS after somebody types
+// into it, and what the formula engine then does with it.
+//
+// node scripts/test-dash-entryparse.ts
+//
+// WHY THIS EXISTS. Review finding 3.1, measured in the built shell: on a
+// spreadsheet sheet, typing 10, $5 and 15% and then =SUM over them said 30,
+// =G13*G15 said 150, and COUNT said 3. Excel, Sheets and Numbers say 15.15,
+// 1.5 and 3. Two faults stacked: typing stored "15%" and "$5" as TEXT (grid.ts
+// had its own narrow reader, and the format-aware `coerceInput` in cellprops.ts
+// was written, tested, and never wired), and the formula engine then read that
+// text by stripping every `%`, `$` and `,` it could find — so the text "15%"
+// was the number 15. Each section below has a check that FAILS on that code.
+//
+// Also guarded: 3.2 (ISO and named-month dates, currency that keeps its
+// symbol, accounting negatives), 2.8 (the formula bar shows `100%`, not `1`),
+// and 3.4 (a formula that does not parse is refused at entry, not committed).
+
+import { registerHooks } from 'node:module'
+registerHooks({
+ load(url, context, next) {
+ if (url.endsWith('.css')) return { format: 'module', source: 'export {}', shortCircuit: true }
+ return next(url, context)
+ },
+})
+
+const { installDom } = await import('./lib/dash-dom.ts')
+const dom = installDom()
+// Every reader is reached through the module NAMESPACE, with the old code's
+// behaviour as the fallback, so this rig RUNS on the code before the fix and
+// fails there check by check rather than at an import.
+const CP: Record<string, any> = await import('../dash/src/cellprops.ts')
+const GR: Record<string, any> = await import('../dash/src/grid.ts')
+const IM: Record<string, any> = await import('../dash/src/import.ts')
+type CanvasCellT = import('../dash/src/model.ts').CanvasCell
+/** what TYPING does — the function the grid's editors call, not a helper beside it */
+const coerceInput = (prev: CanvasCellT | undefined, text: string): CanvasCellT | null => GR.canvasCellEdit(prev, text)
+/** what the formula bar shows; before 2.8 it was String(v) */
+const enteredForm = (c: CanvasCellT | undefined): string =>
+ CP.enteredForm ? CP.enteredForm(c) : (c?.v == null ? '' : String(c.v))
+const { inferColumn } = IM
+const readEntryNumber = (s: string) => (IM.readEntryNumber ? IM.readEntryNumber(s) : null)
+const { setViewerLocale } = await import('../dash/src/format.ts')
+const { recalcCells, canvasCellSource, cellKey, evalCell } = await import('../dash/src/cellformula.ts')
+const { isErr } = await import('../dash/src/formula.ts')
+const { parseDoc } = await import('../dash/src/model.ts')
+const { Store } = await import('../dash/src/store.ts')
+const { Grid, canvasShown } = GR
+const formulaRefusal = (src: string): string | null => (GR.formulaRefusal ? GR.formulaRefusal(src) : null)
+const { starterDoc } = await import('../dash/src/starter.ts')
+type CanvasCell = import('../dash/src/model.ts').CanvasCell
+type CanvasSheet = import('../dash/src/model.ts').CanvasSheet
+
+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 show = (v: unknown) => (v === undefined ? 'undefined' : JSON.stringify(v))
+
+setViewerLocale('en-US')
+
+// ===================================================================== 1
+console.log('\n1. what typing stores — value and format (findings 3.1, 3.2)')
+{
+ // [typed, stored value, stamped format]
+ const table: Array<[string, unknown, string | undefined]> = [
+ ['10', 10, undefined],
+ ['15%', 0.15, '0%'],
+ ['12.5%', 0.125, '0.0%'],
+ ['100%', 1, '0%'],
+ ['$5', 5, '$#,##0'],
+ ['$300.50', 300.5, '$#,##0.00'],
+ ['£1,234', 1234, '£#,##0'],
+ ['€3,50', 3.5, '€#,##0.00'], // decimal comma: `,50` cannot be a thousands group
+ ['($1,200.50)', -1200.5, '$#,##0.00'],
+ ['(5)', -5, undefined], // accounting negative, no mark → no format
+ ['-$5', -5, '$#,##0'],
+ ['1,200', 1200, undefined], // a separator is not a mark (rule 5)
+ ['1e3', 1000, undefined],
+ ['2026-03-04', '2026-03-04', 'yyyy-mm-dd'],
+ ['Mar 4 2026', '2026-03-04', 'yyyy-mm-dd'],
+ ['4 March 2026', '2026-03-04', 'yyyy-mm-dd'],
+ ['March 4, 2026', '2026-03-04', 'yyyy-mm-dd'],
+ ['3/4/2026', '3/4/2026', undefined], // THE refusal: 3 April or 4 March
+ ['13/4/2026', '13/4/2026', undefined], // a slash date stays text from typing (readEnteredDate)
+ ['2026-02-31', '2026-02-31', undefined], // no such day
+ ['007', '007', undefined], // rule 3: the zeros are the information
+ ["'15%", '15%', undefined], // rule 2: the apostrophe
+ ['TRUE', true, undefined],
+ ['north', 'north', undefined],
+ ['15 %', 0.15, '0%'],
+ ]
+ for (const [typed, v, fmt] of table) {
+ const c = coerceInput(undefined, typed)
+ ok(c !== null && c.v === v && c.format === fmt,
+ `"${typed}" → v=${show(v)} format=${show(fmt)} (got v=${show(c?.v)} format=${show(c?.format)})`)
+ }
+ // a cell that already SAYS what it is
+ ok(coerceInput({ format: 'yyyy-mm-dd' }, '13/4/2026')?.v === '2026-04-13',
+ 'in a cell formatted Date, an unambiguous slash date IS read (rule 8)')
+ ok(coerceInput({ format: 'yyyy-mm-dd' }, '3/4/2026')?.v === '3/4/2026',
+ '…and an ambiguous one is still refused, even there')
+ ok(coerceInput({ format: '#,##0.00' }, 'Mar 4 2026')?.v === 'Mar 4 2026' &&
+ coerceInput({ format: '#,##0.00' }, 'Mar 4 2026')?.format === '#,##0.00',
+ 'a date typed into a NUMBER-formatted cell does not overwrite the format somebody chose')
+ ok(coerceInput({ format: '@' }, '15%')?.v === '15%', 'the Text format is absolute (rule 1)')
+ ok(coerceInput({ format: '0%' }, '15')?.v === 0.15, 'a bare 15 in a percent cell is 15%')
+}
+
+// ===================================================================== 2
+console.log('\n2. the viewer\'s decimal convention — only where the field cannot say')
+{
+ setViewerLocale('de-DE')
+ ok(coerceInput(undefined, '1,234')?.v === 1.234, 'de: "1,234" is 1,234 — one point two three four')
+ ok(coerceInput(undefined, '1.234')?.v === 1234, 'de: "1.234" is one thousand two hundred and thirty-four')
+ ok(coerceInput(undefined, '3,50 €')?.v === 3.5 && coerceInput(undefined, '3,50 €')?.format === '€#,##0.00',
+ 'de: "3,50 €" is 3.5 euros, the symbol kept')
+ ok(coerceInput(undefined, '1.5')?.v === 1.5, 'de: "1.5" reads under only one convention, so it is 1.5')
+ setViewerLocale('en-GB')
+ ok(coerceInput(undefined, '1,234')?.v === 1234, 'en: "1,234" is 1234')
+ ok(coerceInput(undefined, '3,50')?.v === 3.5, 'en: "3,50" is still 3.5 — it fits only the comma convention, as on import')
+ setViewerLocale('en-US')
+ // the SAME digit shapes import votes with — one reader, not two
+ ok(inferColumn(['€3,50']).parsed === 'comma' && readEntryNumber('€3,50')?.n === 3.5,
+ 'import infers "€3,50" as the comma convention, and the entry reader reads it as 3.5 — the same code')
+}
+
+// ===================================================================== 3
+console.log('\n3. arithmetic over what was TYPED — the review\'s exact case')
+{
+ const sheet = { cells: {} as Record<string, CanvasCell> }
+ const type = (key: string, text: string) => { const c = coerceInput(sheet.cells[key], text); if (c) sheet.cells[key] = c }
+ type('G13', '10'); type('G14', '$5'); type('G15', '15%')
+ type('G16', '=SUM(G13:G15)'); type('G17', '=G13*G15'); type('G18', '=COUNT(G13:G15)'); type('G19', '=G13+G14')
+ const r = recalcCells(canvasCellSource(sheet as Pick<CanvasSheet, 'cells'>))
+ const at = (row: number) => r.values.get(cellKey(row, 6))
+ ok(Math.abs((at(15) as number) - 15.15) < 1e-12, `=SUM over 10, $5, 15% is 15.15 (got ${String(at(15))}; the review measured 30)`)
+ ok(Math.abs((at(16) as number) - 1.5) < 1e-12, `=G13*G15 is 1.5 (got ${String(at(16))}; the review measured 150)`)
+ ok(at(17) === 3, `=COUNT over them is 3 (got ${String(at(17))})`)
+ ok(at(18) === 15, `=G13+G14 is 15 (got ${String(at(18))})`)
+}
+
+// ===================================================================== 4
+console.log('\n4. text in arithmetic — Excel\'s rule (formula.ts, above `num`)')
+{
+ // A1..A6 hold TEXT, as a legacy file (or an apostrophe) leaves them
+ const cells: Record<string, unknown> = { '0,0': 10, '1,0': '$5', '2,0': '15%', '3,0': 'abc', '4,0': true, '5,0': '5' }
+ const read = (r: { row: number; col: number }) => (cells[`${r.row},${r.col}`] ?? null) as never
+ const ev = (f: string) => evalCell(f, read)
+ const num = (f: string, want: number) => {
+ const got = ev(f)
+ ok(typeof got === 'number' && Math.abs(got - want) < 1e-12, `${f} = ${want} (got ${String(got)})`)
+ }
+ const err = (f: string, code: string) => {
+ const got = ev(f)
+ ok(isErr(got) && got.code === code, `${f} is ${code} (got ${String(got)})`)
+ }
+ // rule 1: a range counts only its NUMBERS — numeric-looking text and booleans skipped
+ num('=SUM(A1:A6)', 10)
+ num('=COUNT(A1:A6)', 1)
+ num('=AVERAGE(A1:A3)', 10)
+ num('=MAX(A1:A3)', 10)
+ num('=SUMIF(A1:A6,"<>x",A1:A6)', 10)
+ // every argument, not just the first
+ num('=SUM(1,2,3)', 6)
+ num('=SUM(A1:A2,A1)', 20)
+ // rule 2: a value written directly is coerced; one that will not read is #VALUE!
+ num('=SUM("5",1)', 6)
+ num('=SUM(TRUE,1)', 2)
+ err('=SUM(1,"abc")', '#VALUE!')
+ num('=COUNT(1,"abc","5")', 2)
+ // rule 3: direct arithmetic coerces numeric text exactly
+ num('=A1*A3', 1.5)
+ num('=A1+A2', 15)
+ num('=-A3', -0.15)
+ num('=A6*2', 10)
+ num('=A1+A5', 11)
+ err('=A1+A4', '#VALUE!')
+ err('=A4*1', '#VALUE!')
+ num('="(5)"*1', -5)
+ num('="1,234"+0', 1234)
+ err('="2026-03-04"+1', '#VALUE!')
+ err('="12abc"*1', '#VALUE!') // never the digits that happened to be in it
+ // postfix percent in a formula
+ num('=10*15%', 1.5)
+ num('=50%', 0.5)
+ num('=2^50%*2^50%', 2)
+}
+
+// ===================================================================== 5
+console.log('\n5. the formula bar shows what was ENTERED (finding 2.8), and it round-trips')
+{
+ for (const loc of ['en-US', 'de-DE']) {
+ setViewerLocale(loc)
+ const cases: Array<[string, string, string]> = loc === 'en-US'
+ ? [['100%', '100%', '100%'], ['15%', '15%', '15%'], ['12.5%', '12.5%', '12.5%'], ['7%', '7%', '7%'],
+ ['$300.50', '$300.50', '$300.50'], ['$5', '$5', '$5'], ['($1,200.50)', '-$1200.50', '($1,200.50)'],
+ ['2026-03-04', '2026-03-04', '2026-03-04'], ['Mar 4 2026', '2026-03-04', '2026-03-04'],
+ ['1,234.5', '1234.5', '1,234.5'], ['0.1', '0.1', '0.1'], ["'15%", "'15%", '15%'],
+ ['TRUE', 'TRUE', '✓'], ['north', 'north', 'north']]
+ : [['12,5%', '12,5%', '12,5 %'], ['1,234', '1,234', '1,234'], ['1.234', '1234', '1.234'], ['3,50 €', '€3,50', '€3,50']]
+ for (const [typed, bar] of cases) {
+ const cell = coerceInput(undefined, typed)!
+ const shown = enteredForm(cell)
+ const again = coerceInput(cell, shown)
+ ok(shown === bar, `${loc}: typed "${typed}" → the bar shows "${bar}" (got "${shown}")`)
+ ok(again?.v === cell.v && again?.format === cell.format,
+ `${loc}: …and pressing Enter on "${shown}" stores the same value again (${show(cell.v)})`)
+ }
+ }
+ setViewerLocale('en-US')
+ // binary noise must not leak into the bar
+ const noisy = { v: 0.07, format: '0%' }
+ ok(enteredForm(noisy) === '7%', `0.07 in a percent cell shows 7%, not 7.000000000000001% (got ${enteredForm(noisy)})`)
+ const exact = { v: 0.1 + 0.2 }
+ ok(coerceInput({}, enteredForm(exact))?.v === 0.1 + 0.2,
+ 'a value 15 digits cannot hold is shown with 17, so opening and closing the cell never changes it')
+ // a legacy file's TEXT date reads as text in the bar, so nobody mistakes it for a date
+ ok(enteredForm({ v: '2026-03-04' }) === "'2026-03-04",
+ 'a legacy unformatted "2026-03-04" TEXT wears the apostrophe that keeps it text')
+ ok(canvasShown({ v: 0.15, format: '0%' }, 0.15) === '15%', 'and the CELL still reads 15% (the display is unchanged)')
+}
+
+// ===================================================================== 6
+console.log('\n6. a formula that does not parse is refused at entry (finding 3.4)')
+{
+ const refused: Array<[string, RegExp]> = [
+ ['=A11+', /ends after “\+”/],
+ ['=SUM(', /ends after “\(”|never closed/],
+ ['=(1+2', /never closed/],
+ ['=1 2', /“2” cannot go there/],
+ ['=1+*2', /“\*” cannot go there/],
+ ['=SUM(1,)', /“\)” cannot go there/],
+ ['=A1:', /“:” cannot go there/],
+ ['=A1)', /“\)” cannot go there/],
+ ['=A1 B1', /“B1” cannot go there/], // the reference is named as it was typed
+ ]
+ for (const [src, re] of refused) {
+ const why = formulaRefusal(src)
+ ok(why !== null && re.test(why), `${src} is refused (${why ?? 'ACCEPTED'})`)
+ }
+ const fine = [
+ '=SUM(A1:A3)', '=Pipeline!D1*2', "='My Sheet'!A1+1", '=IF(A1>1,"a","b")', '=-A1%',
+ '=#REF!+1', '=A1&" x"', '=10*15%', '=$A$1+B$2', '=SUM(amount)', '=TODAY()', '=1', '=--A1',
+ '=XLOOKUP(A1,B1:B9,C1:C9)', '=A1:B3*2', '="a, b) c"',
+ ]
+ for (const src of fine) ok(formulaRefusal(src) === null, `${src} is accepted (${formulaRefusal(src) ?? 'ok'})`)
+ // NO FALSE REFUSALS on real formulas: every formula the starter workbook ships
+ const starter = starterDoc()
+ const all: string[] = []
+ for (const s of starter.sheets) {
+ if (s.kind === 'canvas') for (const c of Object.values(s.cells)) if (typeof c?.f === 'string') all.push(c.f)
+ }
+ const bad = all.filter((f) => formulaRefusal(f) !== null)
+ ok(all.length > 0 && bad.length === 0,
+ `every one of the starter's ${all.length} spreadsheet formulas is accepted${bad.length ? ` — refused: ${bad.join(' | ')}` : ''}`)
+}
+
+// ===================================================================== 7
+console.log('\n7. through the REAL editor and formula bar')
+{
+ const r = parseDoc(JSON.stringify({
+ format: 'bento/dash', version: 1, policy: 'bento-dash-1', docId: 'd', title: 't',
+ sheets: [{ id: 'cv1', name: 'Scratch', kind: 'canvas', cells: { A1: { v: 10 }, B1: { v: 1, format: '0%' }, B2: { v: 300.5, format: '$#,##0.00' } } }],
+ }))
+ if (!r.ok) throw new Error('fixture')
+ const host = dom.doc.createElement('div')
+ dom.doc.body.appendChild(host)
+ const store = new Store(r.doc)
+ const grid = new Grid({ el: host as never, store, sheetId: 'cv1' })
+ const scroll = host.querySelector('.dg-scroll')!
+ scroll.clientHeight = 600; scroll.clientWidth = 900
+ grid.paint()
+ const cells = () => (store.doc.sheets[0] as CanvasSheet).cells
+ const key = (k: string) => ({ type: 'keydown', key: k, shiftKey: false, preventDefault() {}, stopPropagation() {} })
+ const typeAt = (row: number, text: string, press = 'Enter') => {
+ grid.sel.moveTo(row, 0); grid.paint()
+ grid.typeInto(text[0])
+ const cell = host.querySelector('.dg-cell.dg-editing')!
+ cell.textContent = text
+ cell.dispatchEvent(key(press))
+ return cell
+ }
+ typeAt(1, '15%')
+ ok(cells().A2?.v === 0.15 && cells().A2?.format === '0%', `typing 15% in the editor stores 0.15 with 0% (got ${show(cells().A2)})`)
+ typeAt(2, '$300.50')
+ ok(cells().A3?.v === 300.5 && cells().A3?.format === '$#,##0.00', `typing $300.50 stores 300.5 with a $ format (got ${show(cells().A3)})`)
+ const ed = typeAt(3, '=A11+')
+ ok(cells().A4 === undefined, 'typing =A11+ and pressing Enter commits NOTHING')
+ ok(ed.classList.contains('dv-refused') && ed.contentEditable === 'true',
+ '…the editor stays open, marked refused, with the text still in it')
+ ok(dom.doc.body.querySelector('.dg-refuse-tip') !== null, '…and the reason is shown under it')
+ ed.dispatchEvent(key('Escape'))
+ ok(cells().A4 === undefined && dom.doc.body.querySelector('.dg-refuse-tip') === null,
+ 'Escape abandons it, and the message goes with it')
+ typeAt(3, '=A1+A2')
+ ok(cells().A4?.f === '=A1+A2', 'a formula that parses is committed as before')
+ // the formula bar
+ let bar = ''
+ grid.onSelectionChange = (_s: string, _r: string, v: string) => { bar = v }
+ grid.sel.moveTo(1, 0); grid.announce()
+ ok(bar === '15%', `the formula bar over 0.15 (0%) reads "15%" (got "${bar}")`)
+ grid.sel.moveTo(2, 0); grid.announce()
+ ok(bar === '$300.50', `the formula bar over $300.50 reads "$300.50" (got "${bar}")`)
+ // the review's own case: a cell STORED as 1 with a percent format (a file,
+ // not a fresh typing) — the bar said 1
+ grid.sel.moveTo(0, 1); grid.announce()
+ ok(bar === '100%', `the formula bar over a stored 1 formatted 0% reads "100%", not "1" (got "${bar}")`)
+ grid.sel.moveTo(1, 1); grid.announce()
+ ok(bar === '$300.50', `the formula bar over a stored 300.5 formatted $#,##0.00 reads "$300.50" (got "${bar}")`)
+ grid.sel.moveTo(5, 0)
+ ok(typeof grid.setActiveCell('=SUM(') === 'string' && cells().A6 === undefined,
+ 'the formula bar refuses =SUM( too, and writes nothing')
+ ok(grid.setActiveCell('=SUM(A1:A3)') === null && cells().A6?.f === '=SUM(A1:A3)',
+ 'and takes a formula that parses')
+ // a TSV PASTE is read the way typing is
+ grid.sel.moveTo(9, 2)
+ grid.pasteTsv('15%\t$1,200.50\n2026-03-04\t(5)\n3/4/2026\t007')
+ const c = cells()
+ ok(c.C10?.v === 0.15 && c.C10?.format === '0%' && c.D10?.v === 1200.5 && c.D10?.format === '$#,##0.00',
+ `a pasted 15% and $1,200.50 are numbers with their formats (${show(c.C10)}, ${show(c.D10)})`)
+ ok(c.C11?.v === '2026-03-04' && c.C11?.format === 'yyyy-mm-dd' && c.D11?.v === -5,
+ `a pasted ISO date is a date and (5) is -5 (${show(c.C11)}, ${show(c.D11)})`)
+ ok(c.C12?.v === '3/4/2026' && c.D12?.v === '007', 'and a paste keeps the same refusals: 3/4/2026 and 007 stay text')
+}
+
+// ===================================================================== 8
+console.log('\n8. the DATASET kind: the bar over a Percent column (the review\'s own 2.8 shot)')
+{
+ const r = parseDoc(JSON.stringify({
+ format: 'bento/dash', version: 1, policy: 'bento-dash-1', docId: 'd3', title: 't',
+ sheets: [{
+ id: 'ds', name: 'Pipeline', kind: 'table', rids: [[1, 2]], nextRid: 3,
+ columns: [
+ { id: 'p', name: 'Probability', type: 'percent', format: '0%' },
+ { id: 'm', name: 'Value', type: 'money', format: '£#,##0.00' },
+ { id: 'n', name: 'Qty', type: 'number' },
+ ],
+ data: { p: { enc: 'raw', v: [1, 0.125] }, m: { enc: 'raw', v: [12400.5, 300] }, n: { enc: 'raw', v: [3, 4] } },
+ steps: [],
+ }],
+ }))
+ if (!r.ok) throw new Error('fixture')
+ const host = dom.doc.createElement('div')
+ dom.doc.body.appendChild(host)
+ const store = new Store(r.doc)
+ const grid = new Grid({ el: host as never, store, sheetId: 'ds' })
+ const scroll = host.querySelector('.dg-scroll')!
+ scroll.clientHeight = 600; scroll.clientWidth = 900
+ grid.paint()
+ let bar = ''
+ grid.onSelectionChange = (_s: string, _r: string, v: string) => { bar = v }
+ const at = (row: number, col: number) => { grid.sel.moveTo(row, col); grid.announce(); return bar }
+ ok(at(0, 0) === '100%', `Probability 1 (shown 100%) reads "100%" in the bar, not "1" (got "${bar}")`)
+ ok(at(1, 0) === '12.5%', `0.125 reads "12.5%" (got "${bar}")`)
+ ok(at(0, 1) === '£12400.50', `money 12400.5 under £#,##0.00 reads "£12400.50" (got "${bar}")`)
+ ok(at(0, 2) === '3', `a plain number reads as itself (got "${bar}")`)
+ // the bar's text reads back to the same value — the round trip
+ const back = (text: string, type: string) => GR.coerceForColumn(text, type)
+ ok(back('100%', 'percent') === 1 && back('12.5%', 'percent') === 0.125 && back('£12400.50', 'money') === 12400.5,
+ 'and each reads back to the value it shows')
+ ok(back('12abc', 'number') === '12abc', 'a dataset number column keeps "12abc" as typed rather than reading 12 out of it')
+ setViewerLocale('de-DE')
+ ok(back('12,5 %', 'percent') === 0.125, 'de: "12,5 %" in a percent column is 0.125')
+ setViewerLocale('en-US')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) { console.log(`${failures} FAILED`); process.exit(1) }