Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
dash: a sheet rename follows its formulas; a row insert moves cross-sheet references; Enter comes home after a Tab run; mistyped numbers are marked (#586)
nyblnetdd4795d26754
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 7a27be1b..fea378f4 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -918,6 +918,17 @@ jobs:- name: bento/dash selection and clipboardrun: node scripts/test-dash-select.ts+ - name: bento/dash data entry through the real editor+ # Widget⇥12⇥4.50⏎ has to come home to column A. select.ts had the+ # Tab-run model and test-dash-select.ts proved it; the editor's finish()+ # never called it. This one drives typeInto + the cell's own onkeydown.+ run: node scripts/test-dash-entry.ts++ - name: bento/dash cross-sheet structure+ # Insert a row on Pipeline and =SUM(Pipeline!D1:D8) on Scratch has to+ # widen. a1.ts had the scope rule; Grid.shiftFormulas walked one sheet.+ run: node scripts/test-dash-xshift.ts+- name: bento/dash sharing state# Start/stop/rotate sharing mark the workbook unsaved (a rotation is# revocation and must reach the file); only a writer copy offers writediff --git a/dash/CHANGELOG.md b/dash/CHANGELOG.mdindex e281a9d8..b988430b 100644--- a/dash/CHANGELOG.md+++ b/dash/CHANGELOG.md@@ -12,6 +12,33 @@ There is no server, so a break here would be permanent.The release that came out of watching somebody use 0.2.0.+- **Renaming a sheet renames it everywhere.** `=SUM(Pipeline!D1:D8)` names the+ sheet by name, and renaming the tab used to leave it pointing at a sheet that+ no longer existed — the starter workbook's own cross-sheet totals read+ `#REF!` after the first rename. Now every formula, column expression and+ defined name that named the sheet is respelled in the same edit, and one undo+ takes the name and the formulas back together.++- **Inserting or deleting rows moves the other sheets' references too.** A row+ added inside Pipeline now widens `Pipeline!D1:D8` on Scratch to `D1:D9`,+ exactly as it already moved Pipeline's own formulas; before, the range stayed+ put and the total quietly summed eight of nine deals. A reference to a deleted+ row becomes `#REF!` on every sheet, never the row that slid into its place.++- **Enter after a Tab run comes home.** Type Widget⇥12⇥4.50⏎ and the cursor+ lands on the next row's first column, not diagonally two columns over. The+ selection model already knew how; the editor's commit never asked it, and a+ document change mid-run forgot the run. A new rig drives the real editor.++- **A word in a number column is marked, not hidden.** A dataset column typed+ Number used to accept "hello" and say nothing; the total silently left it out+ and a formula reading it gave `#VALUE!`. The cell now wears the same ring a+ validation failure wears, with the reason on hover, and the column header+ counts it.++- **The formula bar follows a paste and a right-click.** Both moved the cursor+ without re-reading the cell, so the bar described the value from before.+- **Restoring unsaved changes or an old version keeps this workbook's ownsharing room, keys and identity.** A restore brings back the CONTENT of asnapshot; the snapshot's copies of the docId, the room and its keys, and thediff --git a/dash/src/a1.ts b/dash/src/a1.tsindex 1be3d710..4079c44c 100644--- a/dash/src/a1.ts+++ b/dash/src/a1.ts@@ -267,6 +267,9 @@ interface Unit {to?: CellRef/** The sheet named before `!`, unquoted. Absent = this formula's own sheet. */sheet?: string+ /** Exactly what the author wrote, qualifier included — for a mapper that+ * decides this unit is not its business and must hand it back untouched. */+ text: string}type MapUnit = (u: Unit) => string/** A bare word that is not a reference, not a call and not a qualifier. */@@ -335,6 +338,22 @@ export interface SheetQualifier {* dataset author reaches for and the one a naive `!`-hunt would find while a* reference-only walk would miss.*/+/**+ * Every qualifier naming `from` respelled as `to` — what a sheet rename owes+ * the formulas on every OTHER sheet. Before this existed, renaming the+ * starter's `Pipeline` tab turned the four cross-sheet totals on `Scratch`+ * into `#REF!`, because a qualifier is a NAME and nothing rewrote it.+ *+ * Only the qualifier changes: the reference after it (and its spacing, its+ * case, its `$`) is copied as the author wrote it, so a formula that named the+ * old sheet differs from its old self by exactly the name. Quoting follows the+ * new name — `'Q3 deals'!A1` when it needs it, `Q3!A1` when it does not.+ */+export function renameSheetRefs(src: string, from: string, to: string): string {+ if (src.indexOf('!') < 0 || sameSheet(from, to)) return src+ return rewrite(src, null, undefined, undefined, { from, to })+}+export function sheetQualifiers(src: string): SheetQualifier[] {// Free when there is no `!` at all, which is almost every expression ever// evaluated — this runs in the recalculation hot path.@@ -376,6 +395,7 @@ function rewrite(map: MapUnit | null,mapName?: MapName,onQualifier?: (sheet: string, after: string) => void,+ renameSheet?: { from: string; to: string },): string {const n = src.lengthconst skipSpace = (j: number): number => {@@ -407,10 +427,10 @@ function rewrite(const to = parseRef(src.slice(m, e2))const after = skipSpace(e2)if (to && src[after] !== '(' && src[after] !== '!' && src[after] !== '[') {- return { unit: { from, to }, end: e2 }+ return { unit: { from, to, text: src.slice(j, e2) }, end: e2 }}}- return { unit: { from }, end: e }+ return { unit: { from, text: src.slice(j, e) }, end: e }}/** `'Q3 pipeline'` at `j` — the index after the closing quote, or -1. */@@ -432,7 +452,8 @@ function rewrite(if (src[k] !== '!') return nullconst r = refAt(skipSpace(k + 1))if (!r) return null- return { text: map ? map({ ...r.unit, sheet: name }) : src.slice(at, r.end), end: r.end }+ const text = src.slice(at, r.end)+ return { text: map ? map({ ...r.unit, sheet: name, text }) : text, end: r.end }}let out = ''@@ -464,6 +485,11 @@ function rewrite(const name = q > 0 ? unquoteSheet(src.slice(i, q)) : ''if (q > 0 && src[skipSpace(q)] === '!') {onQualifier?.(name, src.slice(skipSpace(skipSpace(q) + 1), word(skipSpace(skipSpace(q) + 1))))+ // The sheet was renamed: only the qualifier changes, and the `!` and+ // whatever follows it are copied by the loop exactly as written.+ if (renameSheet && sameSheet(name, renameSheet.from)) {+ out += quoteSheet(renameSheet.to); i = q; continue+ }}const hit = q > 0 ? qualified(name, i, q) : nullif (hit) { out += hit.text; i = hit.end; continue }@@ -508,6 +534,11 @@ function rewrite(// unit — dropping the name here is what made `Sheet1!A1` read the local// A1. When what follows is not a reference, the name is left alone.if (src[k] === '!') {+ // A rename spells the qualifier anew and leaves the rest to the loop —+ // `Jan!A1` and `Jan!Amount` alike, since both name the sheet.+ if (renameSheet && sameSheet(text, renameSheet.from)) {+ out += quoteSheet(renameSheet.to); i = j; continue+ }// WHOEVER IS WATCHING hears about the qualifier here, in BOTH of the// branches below, because both are a formula naming another sheet:// `Jan!A1` is one dash cannot mistake, and `Jan!Amount` — a sheet and a@@ -634,8 +665,10 @@ export function shiftRefsForInsert(return rewrite(src, (u) => {if (!sameSheet(u.sheet ?? scope.self, edited)) {- // Another sheet's cells did not move, so neither does this reference.- return qualify(u.sheet, u.to ? `${formatRef(u.from)}:${formatRef(u.to)}` : formatRef(u.from))+ // Another sheet's cells did not move, so neither does this reference —+ // not even its spelling, or `'Pipeline'!D4` would come back as+ // `Pipeline!D4` and read as a change to whoever diffs the two.+ return u.text}const a = moved(val(u.from))if (!u.to) return a === null ? REF_ERR : qualify(u.sheet, formatRef(put(u.from, a)))diff --git a/dash/src/grid.ts b/dash/src/grid.tsindex 96e985d6..77d0229e 100644--- a/dash/src/grid.ts+++ b/dash/src/grid.ts@@ -20,7 +20,7 @@// the type as a control, not a label.import { formatValue, alignFor, TYPE_LABEL } from './format.ts'-import type { CanvasCell, CanvasSheet, Column, ColumnType, Sheet, TableSheet } from './model.ts'+import type { CanvasCell, CanvasSheet, CellOverride, Column, ColumnType, Sheet, TableSheet } from './model.ts'import { appearanceCss } from './cellfmt.ts'import { readCell, type Patch, type Store } from './store.ts'import { recalc, isErr, type Vec } from './formula.ts'@@ -35,7 +35,7 @@ import { t } from './i18n.ts'import { resizeColumn, autoFitWidth, hiddenSet, readFrozen, insertRowsAt } from './rowcol.ts'import {cellKey, isFormula, recalcSheetCells, recalcWorkbook, spillExtent, translateCellFormula,- shiftSheetFormulas, workbookSources,+ shiftSheetFormulas, shiftDefinedNames, workbookSources,} from './cellformula.ts'import { mountFind, type FindUI, type Hit } from './find.ts'// The data-validation stylesheet is imported HERE rather than in datavalid.ts,@@ -348,6 +348,21 @@ export function aggregate(/** What a total with nothing to total looks like. One spelling, two readouts. */export const NO_TOTAL = '—'+const isNumericType = (ty: string): boolean => ty === 'number' || ty === 'money' || ty === 'percent'++/**+ * Why a stored value does not belong in its numeric column, or null.+ * A string that is not blank and not a number is the case: it will be skipped+ * by every aggregate and turn any formula that reads it into #VALUE!, and+ * until this was marked, nothing on screen said so.+ */+export function mistypedWhy(c: Column, v: unknown): string | null {+ if (!isNumericType(c.type) || c.formula) return null+ if (typeof v !== 'string' || v.trim() === '') return null+ if (Number.isFinite(Number(v))) return null+ return t('Not a number — left out of totals, and a formula that reads it gives #VALUE!')+}+// --- the spreadsheet kind (`kind: 'canvas'`) ---------------------------------//// A CANVAS SHEET IS UNBOUNDED, and that is the whole difference. A dataset ends@@ -624,7 +639,15 @@ export class Grid {// left the grid drawing blanks and rows in an order matching nothing.if (this.store.lastTouched.structural || this.store.lastTouched.all) this.applyView()this.sel.resize(this.selRows(), cols(this.sheet).length)+ this.mistyped.clear() // counts are a fact about the document; re-derive after any changethis.paint()+ // …AND ANNOUNCE HERE TOO. The paragraph above says why the formula bar is+ // re-read on every document change — and then applied it to the canvas+ // branch only. On a dataset, paste six cells over D1:E3 and the cell+ // read £9,100, the model held 9100, and the formula bar still said 12400+ // until the cursor moved. Two readouts on one screen disagreeing, and+ // the wrong one was the editable one.+ this.announce()})this.store.on('view', () => this.paint())}@@ -640,21 +663,44 @@ export class Grid {* of wrong numbers that each look perfectly reasonable.*/shiftFormulas(axis: 'row' | 'col', at: number, count: number): Patch[] {- const s = this.sheet- const cells = s.cells- if (!cells) return []- const pairs: Array<[string, string]> = []- for (const k in cells) {- const f = cells[k]?.f- if (typeof f === 'string') pairs.push([k, f])+ const on = this.sheet+ const out: Patch[] = []+ // EVERY SHEET, not just this one. `=SUM(Pipeline!D1:D8)` on Scratch names+ // rows on Pipeline, so a row inserted on Pipeline moves it exactly as it+ // moves Pipeline's own formulas — and until this walked the workbook it+ // stayed `D1:D8` over nine deals, a wrong total wearing a right one's+ // clothes. `scope` is what keeps a reference to any OTHER sheet still.+ for (const s of this.store.doc.sheets) {+ const cells = (s as { cells?: Record<string, { f?: unknown }> }).cells+ if (!cells) continue+ const pairs: Array<[string, string]> = []+ for (const k in cells) {+ const f = cells[k]?.f+ if (typeof f === 'string') pairs.push([k, f])+ }+ const moved = shiftSheetFormulas(pairs, axis, at, count, { on: on.name, self: s.name })+ if (!moved.length) continue+ if (s.kind === 'canvas') {+ const next: Record<string, CanvasCell> = {}+ for (const [k, f] of moved) next[k] = { ...(cells[k] as CanvasCell), f }+ out.push({ op: 'setCanvasCells', sheet: s.id, cells: next })+ } else {+ out.push({+ op: 'setOverrides', sheet: s.id,+ keys: moved.map(([k]) => k),+ v: moved.map(([k, f]) => ({ ...(cells[k] as CellOverride), f })),+ })+ }+ }+ // A defined name that points INTO this sheet by qualifier moves with it;+ // an unqualified one has no sheet of its own and is left where it is.+ const names = shiftDefinedNames(this.store.doc.names, axis, at, count, { on: on.name })+ if (names.length) {+ const next = { ...this.store.doc.names }+ for (const [k, ref] of names) next[k] = { ...next[k], ref }+ out.push({ op: 'setDocProps', props: { names: next } })}- const moved = shiftSheetFormulas(pairs, axis, at, count)- if (!moved.length) return []- return [{- op: 'setOverrides', sheet: s.id,- keys: moved.map(([k]) => k),- v: moved.map(([k, f]) => ({ ...cells[k], f })),- }]+ return out}/**@@ -939,7 +985,9 @@ export class Grid {`<span class="dg-hmain">` +`<span class="dg-name" title="${esc(c.formula ? `= ${c.formula}` : c.name)}">${esc(c.name)}${arrow}</span>` +(c.formula ? `<span class="dg-fx" title="${esc('= ' + c.formula)}">fx</span>` : '') +- (c.failed ? `<span class="dg-warn" title="${esc(t('{n} value(s) could not be read as {type}').replace('{n}', String(c.failed)).replace('{type}', t(TYPE_LABEL[c.type])))}">!</span>` : '') ++ ((c.failed ?? 0) + this.mistypedCount(c) > 0+ ? `<span class="dg-warn" title="${esc(t('{n} value(s) could not be read as {type}').replace('{n}', String((c.failed ?? 0) + this.mistypedCount(c))).replace('{type}', t(TYPE_LABEL[c.type])))}">!</span>`+ : '') +`<span class="dg-filter" data-filter="${c.id}" title="${esc(t('Filter and sort this column'))}">▾</span>` +`</span>` +`<span class="dg-grip" data-grip="${c.id}" title="${esc(t('Drag to resize, double-click to fit the widest value'))}"></span>` +@@ -1424,7 +1472,14 @@ export class Grid {// the data is what somebody actually has), and a `list` rule puts a// real dropdown arrow in the cell.const rule = dvRules.get(c.id)- const why = rule ? violationOf(rule, v) : null+ // THE COLUMN'S TYPE IS ITS FIRST RULE. Typing "hello" into a Money+ // column was accepted, painted right-aligned like a number, left out+ // of SUM without a word, and the only signal anywhere on screen was+ // a #VALUE! in a DIFFERENT column that happened to read it. The+ // panel's own copy promises "anything that breaks it is marked+ // instead" — so it is marked, here, with the same ring a validation+ // rule draws and a title that says what the number did.+ const why = rule ? violationOf(rule, v) : mistypedWhy(c, v)const dvCls = (why !== null ? ` ${INVALID_CLASS}` : '') + (rule && hasDropdown(rule) ? ' dv-list' : '')const dvArrow = rule && hasDropdown(rule) ? DROPDOWN_HTML : ''const dvTitle = why !== null ? ` title="${esc(why)}"` : ''@@ -1469,6 +1524,29 @@ export class Grid {}+ /**+ * How many stored values in a numeric column are not numbers — a cache,+ * cleared on every `doc` event, because the header is repainted on every+ * scroll and a full-column scan per scroll is the wrong cost model.+ * `Column.failed` is the import-time count of values that were BLANKED and+ * whose originals live in the import step; this is the live count of values+ * that are still there and still not numbers. The badge shows their sum.+ */+ private mistyped = new Map<string, number>()+ private mistypedCount(c: Column): number {+ if (!isNumericType(c.type) || c.formula) return 0+ const hit = this.mistyped.get(c.id)+ if (hit !== undefined) return hit+ const d = this.sheet.data[c.id]+ let n = 0+ if (d) {+ const rows = rowCount(this.sheet)+ for (let r = 0; r < rows; r++) if (mistypedWhy(c, readCell(d, r)) !== null) n+++ }+ this.mistyped.set(c.id, n)+ return n+ }+/** The formula stored at a canonical position, if any. */private formulaAtPos(row: number, col: number): string | undefined {const s = this.sheet@@ -2946,8 +3024,15 @@ export class Grid {}}if (move) {- const d = move === 'down' ? [1, 0] : move === 'up' ? [-1, 0] : move === 'right' ? [0, 1] : [0, -1]- this.sel.move(d[0], d[1], {})+ // THROUGH tab()/enter(), NOT A BARE move(). select.ts records a "Tab+ // run" so that Enter after Widget⇥12⇥4.50 comes home to column A —+ // the help card promises it — but that only ever ran for Tab pressed+ // on a cell that was NOT being edited. Real entry is type-then-Tab,+ // which lands here, and this was a plain directional move: no run+ // recorded, no homing, and Enter after a row of typing sat in the last+ // column typed. Measured: Gadget⇥3⏎ left the cursor on row 3 col B.+ if (move === 'right' || move === 'left') this.sel.tab(move === 'left')+ else this.sel.enter(move === 'up')this.scrollIntoView()}this.paint()@@ -3300,7 +3385,10 @@ export class Grid {el.oncontextmenu = (e) => {e.preventDefault()if (!this.sel.ranges().some((rg) => contains(rg, row, ci))) {- this.sel.moveTo(row, ci); this.paint()+ // announce, as the row-gutter and column-header menus already do: a+ // right-click that moves the cursor left the name box and formula bar+ // describing the cell it had left+ this.sel.moveTo(row, ci); this.paint(); this.announce()}this.onContextMenu?.(row, ci, e.clientX, e.clientY)}@@ -3425,8 +3513,15 @@ export class Grid {// leaves the cursor where it was makes you reach for the mouse between// every value, which is most of what data entry is.if (move) {- const d = move === 'down' ? [1, 0] : move === 'up' ? [-1, 0] : move === 'right' ? [0, 1] : [0, -1]- this.sel.move(d[0], d[1], {})+ // THROUGH tab()/enter(), NOT A BARE move(). select.ts records a "Tab+ // run" so that Enter after Widget⇥12⇥4.50 comes home to column A —+ // the help card promises it — but that only ever ran for Tab pressed+ // on a cell that was NOT being edited. Real entry is type-then-Tab,+ // which lands here, and this was a plain directional move: no run+ // recorded, no homing, and Enter after a row of typing sat in the last+ // column typed. Measured: Gadget⇥3⏎ left the cursor on row 3 col B.+ if (move === 'right' || move === 'left') this.sel.tab(move === 'left')+ else this.sel.enter(move === 'up')this.scrollIntoView()}this.paint()diff --git a/dash/src/i18n/de.ts b/dash/src/i18n/de.tsindex 994ba34b..b989b335 100644--- a/dash/src/i18n/de.ts+++ b/dash/src/i18n/de.ts@@ -750,4 +750,5 @@ export const de: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "„{name}“ hat das ältere Excel-Format. In Excel öffnen und als .xlsx speichern, dann kann dash sie lesen.","…or cut at character positions": "…oder an Zeichenpositionen schneiden","+ Comment on the selected cell": "+ Kommentar zur ausgewählten Zelle",+ "Not a number — left out of totals, and a formula that reads it gives #VALUE!": "Keine Zahl — aus den Summen ausgenommen, und eine Formel, die sie liest, ergibt #VALUE!",}diff --git a/dash/src/i18n/es.ts b/dash/src/i18n/es.tsindex 3726563e..965751e9 100644--- a/dash/src/i18n/es.ts+++ b/dash/src/i18n/es.ts@@ -750,4 +750,5 @@ export const es: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "“{name}” tiene el formato antiguo de Excel. Ábrelo en Excel y guárdalo como .xlsx, y dash podrá leerlo.","…or cut at character positions": "…o cortar en posiciones de carácter","+ Comment on the selected cell": "+ Comentar la celda seleccionada",+ "Not a number — left out of totals, and a formula that reads it gives #VALUE!": "No es un número: queda fuera de los totales, y una fórmula que lo lea da #VALUE!",}diff --git a/dash/src/i18n/fr.ts b/dash/src/i18n/fr.tsindex 30a97b6b..a26488fc 100644--- a/dash/src/i18n/fr.ts+++ b/dash/src/i18n/fr.ts@@ -750,4 +750,5 @@ export const fr: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "« {name} » est à l’ancien format Excel. Ouvrez-le dans Excel et enregistrez-le en .xlsx, et dash pourra le lire.","…or cut at character positions": "…ou couper à des positions de caractère","+ Comment on the selected cell": "+ Commenter la cellule sélectionnée",+ "Not a number — left out of totals, and a formula that reads it gives #VALUE!": "Pas un nombre — exclu des totaux, et une formule qui le lit donne #VALUE!",}diff --git a/dash/src/i18n/it.ts b/dash/src/i18n/it.tsindex 2ec97a76..9bca6077 100644--- a/dash/src/i18n/it.ts+++ b/dash/src/i18n/it.ts@@ -750,4 +750,5 @@ export const it: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "“{name}” è nel vecchio formato Excel. Aprilo in Excel e salvalo come .xlsx, e dash lo leggerà.","…or cut at character positions": "…oppure taglia a posizioni di carattere","+ Comment on the selected cell": "+ Commenta la cella selezionata",+ "Not a number — left out of totals, and a formula that reads it gives #VALUE!": "Non è un numero — escluso dai totali, e una formula che lo legge dà #VALUE!",}diff --git a/dash/src/i18n/ja.ts b/dash/src/i18n/ja.tsindex bdd4d1bd..6b0bfca4 100644--- a/dash/src/i18n/ja.ts+++ b/dash/src/i18n/ja.ts@@ -750,4 +750,5 @@ export const ja: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "「{name}」は古い形式の Excel ファイルです。Excel で開いて .xlsx で保存すれば、dash が読み取れます。","…or cut at character positions": "…または文字位置で区切る","+ Comment on the selected cell": "+ 選択したセルにコメント",+ "Not a number — left out of totals, and a formula that reads it gives #VALUE!": "数値ではありません — 合計から除外され、これを参照する数式は #VALUE! になります",}diff --git a/dash/src/i18n/packed.ts b/dash/src/i18n/packed.tsindex 6be5e71a..cf05f41d 100644--- a/dash/src/i18n/packed.ts+++ b/dash/src/i18n/packed.ts@@ -344,6 +344,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"No versions kept yet — they accumulate as you edit.": ["保存されたバージョンはまだありません — 編集するにつれて増えていきます。","尚未保留任何版本 — 版本会随着编辑逐步积累。","尚未保留任何版本 — 版本會隨著編輯逐漸累積。","Todavía no se guarda ninguna versión: se van acumulando a medida que editas.","Aucune version conservée pour l’instant — elles s’accumulent au fil des modifications.","Noch keine Versionen vorhanden — sie sammeln sich beim Bearbeiten an.","Ancora nessuna versione conservata — si accumulano man mano che modifichi."],"None": ["なし","无","無","Ninguno","Aucune","Keine","Nessuno"],"Normal — 12mm": ["標準 — 12mm","常规 — 12mm","標準 — 12mm","Normal — 12 mm","Normales — 12 mm","Normal — 12 mm","Normali — 12 mm"],+ "Not a number — left out of totals, and a formula that reads it gives #VALUE!": ["数値ではありません — 合計から除外され、これを参照する数式は #VALUE! になります","不是数字 — 未计入合计,读取它的公式会得到 #VALUE!","不是數字 — 未計入合計,讀取它的公式會得到 #VALUE!","No es un número: queda fuera de los totales, y una fórmula que lo lea da #VALUE!","Pas un nombre — exclu des totaux, et une formule qui le lit donne #VALUE!","Keine Zahl — aus den Summen ausgenommen, und eine Formel, die sie liest, ergibt #VALUE!","Non è un numero — escluso dai totali, e una formula che lo legge dà #VALUE!"],"Nothing has been flagged on this sheet yet.": ["このシートにはまだ何も指摘されていません。","此工作表上还没有任何标记。","此工作表上還沒有標記任何內容。","Aún no se ha marcado nada en esta hoja.","Rien n’a encore été signalé sur cette feuille.","Auf diesem Blatt wurde noch nichts markiert.","In questo foglio non è ancora stato segnalato nulla."],"Nothing in this column matches that search.": ["この列にはその検索に一致するものがありません。","此列中没有与该搜索匹配的内容。","此欄中沒有符合該搜尋的內容。","Nada en esta columna coincide con esa búsqueda.","Rien dans cette colonne ne correspond à cette recherche.","Nichts in dieser Spalte passt zu dieser Suche.","Nulla in questa colonna corrisponde a quella ricerca."],"Nothing numeric to plot for this selection.": ["この選択範囲にはグラフにできる数値がありません。","当前选择没有可绘制的数值。","此選取範圍沒有可繪製的數值。","No hay nada numérico que representar en esta selección.","Rien de numérique à représenter pour cette sélection.","Für diese Auswahl gibt es nichts Numerisches zum Darstellen.","Niente di numerico da rappresentare per questa selezione."],diff --git a/dash/src/i18n/zh-Hans.ts b/dash/src/i18n/zh-Hans.tsindex cb57c251..ac9417ab 100644--- a/dash/src/i18n/zh-Hans.ts+++ b/dash/src/i18n/zh-Hans.ts@@ -750,4 +750,5 @@ export const zhHans: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "“{name}”是旧版 Excel 格式。请在 Excel 中打开并另存为 .xlsx,dash 就能读取。","…or cut at character positions": "…或按字符位置切分","+ Comment on the selected cell": "+ 为所选单元格添加评论",+ "Not a number — left out of totals, and a formula that reads it gives #VALUE!": "不是数字 — 未计入合计,读取它的公式会得到 #VALUE!",}diff --git a/dash/src/i18n/zh-Hant.ts b/dash/src/i18n/zh-Hant.tsindex 53da1675..4529849d 100644--- a/dash/src/i18n/zh-Hant.ts+++ b/dash/src/i18n/zh-Hant.ts@@ -750,4 +750,5 @@ export const zhHant: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "「{name}」是舊版的 Excel 格式。請在 Excel 中開啟並另存為 .xlsx,dash 就能讀取。","…or cut at character positions": "…或按字元位置切分","+ Comment on the selected cell": "+ 為選取的儲存格加註解",+ "Not a number — left out of totals, and a formula that reads it gives #VALUE!": "不是數字 — 未計入合計,讀取它的公式會得到 #VALUE!",}diff --git a/dash/src/panels.ts b/dash/src/panels.tsindex c32d07c5..8a3fd7d6 100644--- a/dash/src/panels.ts+++ b/dash/src/panels.ts@@ -44,7 +44,7 @@ import {buildValidationSection, canvasEntryAt, canvasRulePatch, canvasRules, columnRule,countViolations, columnRulePatch, boxRef, type DataRule,} from './datavalid.ts'-import { mountTabs, renameSheetPatch } from './tabs.ts'+import { mountTabs, renameSheetPatches } from './tabs.ts'import { inferComputedType } from './computedtype.ts'import { buildCondFmtSection, condFmtPatch, readCondFmt } from './condfmtui.ts'import { toast } from './saveui.ts'@@ -63,7 +63,7 @@ import {* about sheets, not about which file happens to draw them today.*/export {- blankSheet, mintSheetId, mintSheetName, renameSheetPatch,+ blankSheet, mintSheetId, mintSheetName, renameSheetPatch, renameSheetPatches,} from './tabs.ts'/**@@ -673,8 +673,8 @@ export function mountPanels(host: PanelsHost): Panels {function buildSheetSection(sheet: TableSheet): void {section(right, t('Sheet'))row(right, t('Name'), text(sheet.name, (v) => {- const p = renameSheetPatch(sheet, v)- if (p) commit(p)+ const p = renameSheetPatches(store.doc, sheet, v)+ if (p.length) commit(p)}))readonlyRow(right, t('Rows'), String(rowsOf(sheet)))readonlyRow(right, t('Columns'), String(sheet.columns.length))diff --git a/dash/src/select.ts b/dash/src/select.tsindex f55e5e2c..cc5fd6fe 100644--- a/dash/src/select.ts+++ b/dash/src/select.ts@@ -506,7 +506,17 @@ export class Selection {this.active = fix(this.active)this.extra = this.extra.map(fix)this.cursor = this.clamp(this.cursor.row, this.cursor.col)- this.run = null+ // THE RUN SURVIVES A RESIZE THAT DID NOT MOVE IT. The grid calls resize()+ // on EVERY document event — a typed value included — and this used to+ // clear the run unconditionally. So the one thing that always happens+ // between a Tab and the Enter that should come home is the commit of+ // what was typed, and that commit erased the run just before enter()+ // looked for it. Every Enter after a Tab run then moved plainly down,+ // and the typist walked diagonally across their table — the exact bug+ // test-dash-select.ts names and proves the model does not have, because+ // the model was never told the grid does this. The run only goes when the+ // sheet actually shrank past it.+ if (this.run && (this.run.row >= this.rows || this.run.col >= this.cols)) this.run = nullreturn this}diff --git a/dash/src/tabs.ts b/dash/src/tabs.tsindex 2cfd825a..db1d878e 100644--- a/dash/src/tabs.ts+++ b/dash/src/tabs.ts@@ -47,6 +47,7 @@ import type { Column, DashDoc, Sheet, TableSheet, CanvasSheet } from './model.tsimport type { Patch, Store } from './store.ts'import type { Grid } from './grid.ts'import type { SetSheetProps } from './rowcol.ts'+import { renameSheetRefs } from './a1.ts'/** Remembered per browser, never in the document: this is a viewer preference. */const LS_SHUT = 'bento-dash-tabs-shut'@@ -94,6 +95,64 @@ export function renameSheetPatch(sheet: { id: string; name: string }, name: strireturn { op: 'setSheetProps', sheet: sheet.id, props: { name: n } }}+/**+ * The rename, AND every formula in the workbook that reached the sheet by its+ * old name — one step, so no document ever exists in which the tab says one+ * thing and `=SUM(Pipeline!D1:D8)` says another. That document did exist:+ * renaming the starter's Pipeline tab left four `#REF!`s on Scratch, and a+ * reader had no way to know the two events were the same event.+ *+ * Cell formulas on both kinds of sheet, column expressions and defined names+ * are the three places a qualifier can be written. Each is rewritten through+ * the op that owns it, so undo puts the name AND the formulas back together.+ */+export function renameSheetPatches(doc: DashDoc, sheet: { id: string; name: string }, name: string): Patch[] {+ const head = renameSheetPatch(sheet, name)+ if (!head) return []+ const from = sheet.name+ const to = head.props.name as string+ const out: Patch[] = [head]+ const fix = (f: unknown): string | null => {+ if (typeof f !== 'string') return null+ const next = renameSheetRefs(f, from, to)+ return next === f ? null : next+ }+ for (const s of doc.sheets) {+ if (s.kind === 'canvas') {+ const cells: Record<string, CanvasSheet['cells'][string]> = {}+ let n = 0+ for (const [k, c] of Object.entries(s.cells)) {+ const f = fix(c?.f)+ if (f !== null) { cells[k] = { ...c, f }; n++ }+ }+ if (n) out.push({ op: 'setCanvasCells', sheet: s.id, cells })+ } else if (s.kind === 'table') {+ const t = s as TableSheet+ for (const c of t.columns) {+ const f = fix(c.formula)+ if (f !== null) out.push({ op: 'setColumn', sheet: t.id, col: c.id, patch: { formula: f } })+ }+ const keys: string[] = []+ const v: NonNullable<TableSheet['cells']>[string][] = []+ for (const [k, c] of Object.entries(t.cells ?? {})) {+ const f = fix(c?.f)+ if (f !== null) { keys.push(k); v.push({ ...c, f }) }+ }+ if (keys.length) out.push({ op: 'setOverrides', sheet: t.id, keys, v })+ }+ }+ if (doc.names) {+ let changed = false+ const names = { ...doc.names }+ for (const [k, d] of Object.entries(doc.names)) {+ const ref = fix(d?.ref)+ if (ref !== null) { names[k] = { ...d, ref }; changed = true }+ }+ if (changed) out.push({ op: 'setDocProps', props: { names } })+ }+ return out+}+/*** A sheet id nothing in the workbook has taken.*@@ -841,8 +900,8 @@ export function mountTabs(host: TabsHost): Tabs {done = truerenaming = falseif (write) {- const p = renameSheetPatch(sheet, input.value)- if (p) commit(p)+ const p = renameSheetPatches(store.doc, sheet, input.value)+ if (p.length) commit(p)}refresh(true)}diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex fa50419e..d781a0c9 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -7557,6 +7557,44 @@ rigs treat a drawn arrow as a deliberate difference: named in`test-maths-lite.ts`, counted with the identical ones in the coverage floor.Cost: +966 B of shell.+## 2026-09-13 — dash: a sheet's name is a reference key, so a rename is a formula edit++Cross-sheet references in dash are by NAME (`Pipeline!D1:D8`), as in Excel, and+that was the whole of the design: a1.ts could parse, quote and shift them, and+cellformula.ts resolved them. What nobody had written down was the consequence —+if the name is the key, then renaming the sheet is an edit to every formula+that holds the key, and it has to land in the same commit or a document exists+in which the tab says one thing and the formulas say another. It did exist:+renaming the starter's Pipeline tab turned Scratch's four totals into `#REF!`.++Decided:++- `renameSheetPatches(doc, sheet, name)` (tabs.ts) is the rename. It returns+ the props patch AND a rewrite for every cell formula on every sheet kind,+ every column expression, and every defined name that qualified with the old+ name — through the op each one is owned by, so undo is one step. Both the tab+ strip and the panel's Name field go through it; `renameSheetPatch` stays as+ the one-patch primitive the rigs already cover.+- `renameSheetRefs(src, from, to)` (a1.ts) respells ONLY the qualifier. The+ reference after it is copied as the author wrote it; quoting follows the new+ name's needs (`'Q3 deals'!A1`, `Deals!A1`, and `'Q3'!A1` because `Q3` is+ cell-shaped). Strings, values that look like references, and other sheets'+ qualifiers are untouched. Case-insensitive, as `sameSheet` already was.+- The same session found the mirror bug: `shiftRefsForInsert` had carried a+ `scope` (which sheet the edit was on, which sheet the formula lives on) since+ sheets could be named, and `Grid.shiftFormulas` never passed it — it walked+ the edited sheet's own formulas and nothing else, so a row inserted on+ Pipeline left `Pipeline!D1:D8` on Scratch summing eight of nine deals. It now+ walks every sheet with `{on, self}` plus the defined names, and a reference to+ another sheet is handed back as the author spelled it (`Unit.text`) rather+ than re-canonicalised, so an unaffected formula never reads as changed.+- Rig: `scripts/test-dash-xshift.ts` drives the grid's patch factory over a+ three-sheet workbook and reads the recalculated numbers back; the rename+ cases live in `test-dash-tabs.ts`. Both are the shape this repo keeps+ finding — a correct engine and an interface that did not call it — and both+ were found by using the built shell as a first-time user, not by reading code.++## 2026-10-04 — CORRECTION: `file://` documents share one storage originThe 2026-08-02 entry "bento/home is closed; the host is a WebExtension" saysdiff --git a/scripts/test-dash-entry.ts b/scripts/test-dash-entry.tsnew file mode 100644index 00000000..31ea058f--- /dev/null+++ b/scripts/test-dash-entry.ts@@ -0,0 +1,103 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/dash DATA-ENTRY rig — the keys a typist presses, through the real editor.+//+// node scripts/test-dash-entry.ts (Node ≥ 23.6 strips types natively)+//+// WHY THIS EXISTS. select.ts records a "Tab run" so that Enter after+// Widget⇥12⇥4.50 comes home to column A, and test-dash-select.ts proves the+// MODEL does that — it even names the failure, "the bug that walks a typist+// diagonally across their table". It passed, and the typist was walked+// diagonally anyway: the editor's `finish()` moved with a bare `sel.move()`+// for every direction and never called `tab()` or `enter()`, so the run was+// never recorded on the one path real entry takes — type, then Tab. A feature+// complete, correct and UNREACHABLE, which is the shape this repo keeps+// finding. So this rig drives the EDITOR: `typeInto` opens it exactly as a+// keypress does, and the cell's own onkeydown finishes it exactly as Tab and+// Enter do.++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()+const { parseDoc } = await import('../dash/src/model.ts')+const { Store } = await import('../dash/src/store.ts')+const { Grid } = await import('../dash/src/grid.ts')++let checks = 0, failures = 0+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }++const doc = parseDoc(JSON.stringify({+ format: 'bento/dash', version: 1, policy: 'bento-dash-1', docId: 'd', title: 't',+ sheets: [{+ id: 's1', name: 'S', kind: 'table', rids: [[1, 4]], nextRid: 5,+ columns: [+ { id: 'a', name: 'Item', type: 'text' },+ { id: 'b', name: 'Qty', type: 'number' },+ { id: 'c', name: 'Price', type: 'number' },+ ],+ data: { a: { enc: 'raw', v: [null, null, null, null] }, b: { enc: 'raw', v: [null, null, null, null] }, c: { enc: 'raw', v: [null, null, null, null] } },+ steps: [],+ }],+})).doc++dom.doc.body.children = []+const host = dom.doc.createElement('div')+dom.doc.body.appendChild(host)+const store = new Store(doc)+const grid = new Grid({ el: host as never, store, sheetId: 's1' })+const scroll = host.querySelector('.dg-scroll')!+scroll.clientHeight = 600; scroll.clientWidth = 900+grid.setSheet('s1')++/** Type a value into the cursor cell through the real editor, then press `key`. */+function typeThen(text: string, key: 'Tab' | 'Enter', shift = false) {+ ok(grid.typeInto(text[0]), `typing "${text[0]}" opens the editor on the cursor cell`)+ const cell = host.querySelector('.dg-editing') as unknown as { textContent: string; onkeydown: (e: unknown) => void } | null+ if (!cell) { ok(false, 'an editing cell exists'); return }+ cell.textContent = text+ cell.onkeydown({ key, shiftKey: shift, preventDefault() {}, stopPropagation() {} })+}+const at = () => [grid.sel.cursor.row, grid.sel.cursor.col] as const+const eq = (a: readonly [number, number], b: readonly [number, number], m: string) =>+ ok(a[0] === b[0] && a[1] === b[1], `${m} — cursor at [${a}], wanted [${b}]`)+const cellVal = (col: string, row: number) => (doc.sheets[0] as { data: Record<string, { v: unknown[] }> }).data[col].v[row]++console.log('a row typed with Tab between the fields, then Enter')+{+ grid.sel.moveTo(0, 0)+ typeThen('Widget', 'Tab'); eq(at(), [0, 1], 'Tab commits and moves right')+ typeThen('12', 'Tab'); eq(at(), [0, 2], 'Tab again')+ typeThen('4.50', 'Enter'); eq(at(), [1, 0], 'ENTER COMES HOME to the column the run started in, one row down')+ ok(cellVal('a', 0) === 'Widget' && cellVal('b', 0) === 12 && cellVal('c', 0) === 4.5,+ 'and all three values landed in row 1 — Widget, 12, 4.5')+ // the landing cell is the new run start+ typeThen('Gadget', 'Tab'); typeThen('3', 'Enter')+ eq(at(), [2, 0], 'the next row does the same: Gadget⇥3⏎ lands on row 3 column A')+ ok(cellVal('a', 1) === 'Gadget' && cellVal('b', 1) === 3, 'with both values in row 2')+}++console.log('\nEnter with no Tab since is a plain move down')+{+ grid.sel.moveTo(0, 1)+ typeThen('7', 'Enter'); eq(at(), [1, 1], 'no run, so Enter stays in its column')+}++console.log('\nshift reverses both')+{+ grid.sel.moveTo(2, 2)+ typeThen('x', 'Tab', true); eq(at(), [2, 1], 'shift+Tab commits and moves LEFT')+ // the run started at column C (where shift+Tab was pressed), so home is C —+ // the mirror of Tab from A then Enter coming back to A+ typeThen('y', 'Enter', true); eq(at(), [1, 2], 'shift+Enter comes home one row UP, to the column the reverse run started in')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-dash-tabs.ts b/scripts/test-dash-tabs.tsindex 1fe88c3a..c6a30f3b 100644--- a/scripts/test-dash-tabs.ts+++ b/scripts/test-dash-tabs.ts@@ -51,7 +51,7 @@ registerHooks({const {dropIndex, moveSheetPatches, nudgeSheetPatches, duplicateSheetPatches,deleteSheetPlan, sheetAfterDelete, stepSheet, blankSheet, mintSheetId,- mintSheetName, renameSheetPatch, describeKind, isTable,+ mintSheetName, renameSheetPatch, renameSheetPatches, describeKind, isTable,} = await import('../dash/src/tabs.ts')const { parseDoc } = await import('../dash/src/model.ts')@@ -515,6 +515,82 @@ console.log('\na name belongs to a SHEET, not to a dataset')'a sheet that is not in the workbook is still refused LOUDLY — a silent no-op is an edit the user believes landed')}+// ================================== a rename follows the formulas that name it+//+// A cross-sheet reference names the sheet by NAME, so the rename has to reach+// every formula in the workbook or it strands them. It did: renaming the+// starter's Pipeline tab left `=SUM(Pipeline!D1:D8)` on Scratch reading `#REF!`+// — four of them, in the first workbook every reader opens. The rename and the+// rewrites are one commit, and one undo takes the whole thing back.+console.log('\na rename rewrites every formula that named the sheet')+{+ const withRefs = (): DashDoc => {+ const d = fresh()+ const r = parseDoc(JSON.stringify({+ ...d,+ names: { Top: { ref: 'Alpha!X1' }, Rate: { v: 0.2 } },+ sheets: [+ {+ ...d.sheets[0],+ columns: [{ id: 'x', name: 'X', type: 'number' }, { id: 'dbl', name: 'Dbl', type: 'number', formula: 'X * 2' }],+ cells: { 'x:2': { note: 'hand-checked', f: '=Beta!Y1' } },+ },+ {+ ...d.sheets[1],+ columns: [{ id: 'y', name: 'Y', type: 'text' }, { id: 'k', name: 'K', type: 'number', formula: 'SUM(alpha!X)' }],+ },+ ...d.sheets.slice(2),+ {+ id: 'ss', name: 'Scratch', kind: 'canvas',+ cells: {+ A1: { f: '=SUM(Alpha!X1:X3)', format: '£#,##0' },+ A2: { f: "='Alpha'!$X$1 + Beta!Y1" },+ A3: { f: '="Alpha!X1 is " & 1' },+ A4: { v: 'Alpha!X1' },+ },+ },+ ],+ }))+ if (!r.ok) throw new Error(`fixture does not parse: ${JSON.stringify(r)}`)+ return r.doc+ }+ const st = new Store(withRefs())+ const shape = (d: DashDoc): string => JSON.stringify({ ...d, modified: undefined })+ const before = shape(st.doc)+ const ps = renameSheetPatches(st.doc, st.doc.sheets[0], 'Q3 deals')+ st.commit(ps)+ const ss = st.doc.sheets.find((s) => s.id === 'ss') as CanvasSheet+ const a = st.doc.sheets[0] as TableSheet+ const b = st.doc.sheets[1] as TableSheet+ ok(a.name === 'Q3 deals', 'the tab is renamed')+ ok(ss.cells.A1?.f === "=SUM('Q3 deals'!X1:X3)", `a spreadsheet formula follows it, quoted because the new name needs it — ${ss.cells.A1?.f}`)+ ok(ss.cells.A1?.format === '£#,##0', 'and keeps the rest of the cell')+ ok(ss.cells.A2?.f === "='Q3 deals'!$X$1 + Beta!Y1", `both spellings of the old name change, the other sheet's qualifier does not — ${ss.cells.A2?.f}`)+ ok(ss.cells.A3?.f === '="Alpha!X1 is " & 1', 'a string literal is not a reference')+ ok(ss.cells.A4?.v === 'Alpha!X1', 'and a VALUE that happens to look like one is not touched')+ ok(a.cells?.['x:2']?.f === '=Beta!Y1' && a.cells?.['x:2']?.note === 'hand-checked',+ 'a dataset cell naming a DIFFERENT sheet is left alone, note and all')+ ok(b.columns[1]?.formula === "SUM('Q3 deals'!X)", `a column expression on another dataset follows too, case-insensitively — ${b.columns[1]?.formula}`)+ ok(a.columns[1]?.formula === 'X * 2', 'a column expression with no qualifier is untouched')+ ok(st.doc.names?.Top?.ref === "'Q3 deals'!X1", `a defined name follows — ${st.doc.names?.Top?.ref}`)+ ok(st.doc.names?.Rate?.v === 0.2, 'and one with no reference is untouched')+ st.undo()+ ok(shape(st.doc) === before, 'ONE undo puts the name and every formula back — it was one edit (`modified` aside)')++ // Renaming to a bare word drops the quotes — unless the word is cell-shaped,+ // which `Q3` is (column Q, row 3), and then the quotes are what keeps the+ // scanner from reading it as an address. A rename nothing references is one patch.+ const st2 = new Store(withRefs())+ st2.commit(renameSheetPatches(st2.doc, st2.doc.sheets[0], 'Deals'))+ const f1 = (): string | undefined => (st2.doc.sheets.find((s) => s.id === 'ss') as CanvasSheet).cells.A1?.f+ ok(f1() === '=SUM(Deals!X1:X3)', `a bare-word name is written bare — ${f1()}`)+ st2.commit(renameSheetPatches(st2.doc, st2.doc.sheets[0], 'Q3'))+ ok(f1() === "=SUM('Q3'!X1:X3)", `a cell-shaped name stays quoted, so it can never be read as an address — ${f1()}`)+ ok(renameSheetPatches(st2.doc, st2.doc.sheets[2], 'Totals').length === 1,+ 'renaming a sheet nothing references is the one props patch and nothing else')+ ok(renameSheetPatches(st2.doc, st2.doc.sheets[0], ' ').length === 0, 'a blank rename is still refused')+}+// ============================================================ what a tab saysconsole.log('\nnon-table sheets are named as what they are')diff --git a/scripts/test-dash-xshift.ts b/scripts/test-dash-xshift.tsnew file mode 100644index 00000000..519fe601--- /dev/null+++ b/scripts/test-dash-xshift.ts@@ -0,0 +1,145 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/dash CROSS-SHEET STRUCTURE rig — a row inserted on one sheet moves the+// formulas on every OTHER sheet that name its rows.+//+// node scripts/test-dash-xshift.ts (Node ≥ 23.6 strips types natively)+//+// WHY THIS EXISTS. `shiftRefsForInsert` has carried a `scope` — "which sheet+// the edit was on, which sheet the formula lives on" — and the rule that a+// reference moves only when the two agree. test-dash-a1.ts proves it. And the+// grid never passed it: `Grid.shiftFormulas` walked the formulas of the sheet+// being edited and no other, so `=SUM(Pipeline!D1:D8)` on Scratch stayed+// `D1:D8` after a ninth deal was inserted into the middle of Pipeline. The+// starter workbook's own cross-sheet total was one insert away from being+// wrong — silently, a number that looks right. The same shape as the Tab-run+// bug in test-dash-entry.ts: a correct engine and an interface that did not+// call it. So this rig drives the GRID's patch factory over a real workbook.++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()+const { parseDoc } = await import('../dash/src/model.ts')+const { Store } = await import('../dash/src/store.ts')+const { Grid } = await import('../dash/src/grid.ts')+const { insertRowsAt, deleteRowsAt } = await import('../dash/src/rowcol.ts')+const { recalcWorkbook, workbookSources, cellKey } = await import('../dash/src/cellformula.ts')+const { parseRef } = await import('../dash/src/a1.ts')+type CanvasSheet = import('../dash/src/model.ts').CanvasSheet+type TableSheet = import('../dash/src/model.ts').TableSheet++let checks = 0, failures = 0+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }++const fresh = () => parseDoc(JSON.stringify({+ format: 'bento/dash', version: 1, policy: 'bento-dash-1', docId: 'd', title: 't',+ names: { Third: { ref: 'Pipeline!D3' }, Local: { ref: 'D3' } },+ sheets: [+ {+ id: 'p', name: 'Pipeline', kind: 'table', rids: [[1, 4]], nextRid: 5,+ columns: [+ { id: 'a', name: 'Region', type: 'text' }, { id: 'b', name: 'Owner', type: 'text' },+ { id: 'c', name: 'Stage', type: 'text' }, { id: 'd', name: 'Value', type: 'number' },+ ],+ data: {+ a: { enc: 'raw', v: ['N', 'S', 'E', 'W'] }, b: { enc: 'raw', v: ['p', 'q', 'r', 's'] },+ c: { enc: 'raw', v: ['Won', 'Open', 'Won', 'Lost'] }, d: { enc: 'raw', v: [10, 20, 30, 40] },+ },+ cells: { 'd:3': { f: '=D2*2' } },+ steps: [],+ },+ {+ id: 'o', name: 'Other', kind: 'table', rids: [[1, 3]], nextRid: 4,+ columns: [{ id: 'x', name: 'X', type: 'number' }],+ data: { x: { enc: 'raw', v: [1, 2, 3] } },+ cells: { 'x:1': { f: '=Pipeline!D4' }, 'x:2': { f: '=X1+1' } },+ steps: [],+ },+ {+ id: 's', name: 'Scratch', kind: 'canvas',+ cells: {+ A1: { f: '=SUM(Pipeline!D1:D4)' },+ A2: { f: '=Pipeline!D3' },+ A3: { f: '=SUM(A1:A2)' },+ A4: { f: "='Pipeline'!$D$4" },+ B1: { v: 5 }, B2: { v: 6 }, B3: { f: '=SUM(B1:B2)' },+ },+ },+ ],+})).doc++const mount = () => {+ dom.doc.body.children = []+ const host = dom.doc.createElement('div')+ dom.doc.body.appendChild(host)+ const store = new Store(fresh())+ const grid = new Grid({ el: host as never, store, sheetId: 'p' })+ const scroll = host.querySelector('.dg-scroll')!+ scroll.clientHeight = 600; scroll.clientWidth = 900+ grid.setSheet('p')+ return { store, grid }+}+const scratch = (store: InstanceType<typeof Store>) => (store.doc.sheets.find((s) => s.id === 's') as CanvasSheet).cells+const other = (store: InstanceType<typeof Store>) => (store.doc.sheets.find((s) => s.id === 'o') as TableSheet).cells ?? {}+const pipe = (store: InstanceType<typeof Store>) => (store.doc.sheets.find((s) => s.id === 'p') as TableSheet).cells ?? {}+const valueOf = (store: InstanceType<typeof Store>, addr: string): unknown => {+ const r = recalcWorkbook(workbookSources(store.doc))+ const ref = parseRef(addr)!+ return r.get('s')?.values.get(cellKey(ref.row, ref.col))+}++console.log('insert a row INSIDE the range, on the sheet the others reference')+{+ const { store, grid } = mount()+ // D3 is the per-cell formula =D2*2 = 40, so the four deals are 10+20+40+40+ ok(valueOf(store, 'A1') === 110 && valueOf(store, 'A2') === 40, `the cross-sheet total is 110 and D3 is 40 before anything moves — ${valueOf(store, 'A1')}, ${valueOf(store, 'A2')}`)+ // `nextRid` is monotonic by design (a row id is never reused) and `modified` is a clock+ const shape = (d: typeof store.doc) => JSON.stringify({ ...d, modified: undefined, sheets: d.sheets.map((x) => ({ ...x, nextRid: undefined })) })+ const before = shape(store.doc)+ // a row at canonical index 1 — between the first and second deal+ store.commit([...insertRowsAt(grid.sheet, 1, 1), ...grid.shiftFormulas('row', 1, 1)])+ ok(scratch(store).A1?.f === '=SUM(Pipeline!D1:D5)', `the range on Scratch WIDENS to take the new row in — ${scratch(store).A1?.f}`)+ ok(scratch(store).A2?.f === '=Pipeline!D4', `a single reference past the insert moves down — ${scratch(store).A2?.f}`)+ // (a reference that MOVED is respelled canonically — the quotes go because+ // `Pipeline` never needed them; one that did not move keeps its spelling)+ ok(scratch(store).A4?.f === '=Pipeline!$D$5', `\`$\` does not pin it: the cell moved — ${scratch(store).A4?.f}`)+ ok(scratch(store).A3?.f === '=SUM(A1:A2)' && scratch(store).B3?.f === '=SUM(B1:B2)', 'Scratch\'s OWN references do not move — nothing was inserted on Scratch')+ ok(other(store)['x:1']?.f === '=Pipeline!D5' && other(store)['x:2']?.f === '=X1+1', `a dataset on a third sheet follows the same rule — ${other(store)['x:1']?.f}, ${other(store)['x:2']?.f}`)+ ok(pipe(store)['d:3']?.f === '=D3*2', `Pipeline's own local formula still moves as it always did — ${pipe(store)['d:3']?.f}`)+ ok(store.doc.names?.Third?.ref === 'Pipeline!D4', `a defined name INTO Pipeline moves — ${store.doc.names?.Third?.ref}`)+ ok(store.doc.names?.Local?.ref === 'D3', 'an unqualified defined name has no sheet to have moved on, and stays')+ ok(valueOf(store, 'A1') === 110 && valueOf(store, 'A2') === 40, `and the numbers are the SAME numbers: total still 110, the deal that was 40 is still 40 — ${valueOf(store, 'A1')}, ${valueOf(store, 'A2')}`)+ store.undo()+ ok(shape(store.doc) === before, 'one undo puts every sheet back')+}++console.log('\ndelete a row the others point at')+{+ const { store, grid } = mount()+ store.commit([...deleteRowsAt(grid.sheet, 2, 1), ...grid.shiftFormulas('row', 2, -1)])+ ok(scratch(store).A1?.f === '=SUM(Pipeline!D1:D3)', `the range SHRINKS — ${scratch(store).A1?.f}`)+ ok(scratch(store).A2?.f === '=#REF!', `a reference to the deleted row is #REF!, never the row that slid into its place — ${scratch(store).A2?.f}`)+ ok(scratch(store).A4?.f === '=Pipeline!$D$3', `a reference below it moves up — ${scratch(store).A4?.f}`)+ ok(other(store)['x:1']?.f === '=Pipeline!D3', `on the third sheet too — ${other(store)['x:1']?.f}`)+ ok(valueOf(store, 'A1') === 70, `the total is the three deals that remain — ${valueOf(store, 'A1')}`)+}++console.log('\nan edit on a sheet nobody references touches nothing else')+{+ const { store, grid } = mount()+ grid.setSheet('o')+ const ps = grid.shiftFormulas('row', 0, 1)+ ok(ps.every((p) => (p as { sheet?: string }).sheet === 'o'), `every patch is for Other itself — ${ps.map((p) => (p as { sheet?: string }).sheet ?? p.op).join(',')}`)+ ok(ps.length === 1, 'and it is one patch: Other\'s own X1+1')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)