Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

bento/dash: a total over nothing, the menu that explains dash, and a chart that survives the file (#410)

nyblnetf15eb1b96d66
diff --git a/dash/src/grid.ts b/dash/src/grid.ts
index bf6065d0..96e985d6 100644
--- a/dash/src/grid.ts
+++ b/dash/src/grid.ts
@@ -305,12 +305,31 @@ export const ariaColCount = (visCols: number): number => 1 + visCols
*/
export const ARIA_UNKNOWN = -1
+/**
+ * `null` MEANS THERE IS NO ANSWER, and that is the whole point of the type.
+ *
+ * This returned a plain number, so a total over nothing returned 0 — and 0 is a
+ * value, drawn in the column's own format, indistinguishable from a real
+ * result. Filter the starter sheet to a stage that matches no deal and the
+ * footer said `sum £0` and `avg 0%` under an empty grid: a confident answer to
+ * a question with no answer, which is the same failure as the footer that
+ * ignored the filter (see `totalsRow`) wearing different clothes. Someone
+ * filters to a rep with no closed deals and reads off a £0 pipeline.
+ *
+ * COUNT IS THE EXCEPTION and keeps returning a number: "how many did I see" has
+ * the answer 0, truthfully, and an empty view honestly counts zero rows.
+ *
+ * NOT A CHANGE TO `SUM()`. Excel's SUM over an empty range is 0 and dash's
+ * formula function agrees — that lives in `formula.ts` and is untouched. This
+ * is the footer READOUT, where the reader cannot see the range and 0 is
+ * therefore unreadable as "nothing to add up".
+ */
export function aggregate(
spec: TotalSpec,
read: (i: number) => unknown,
n: number,
rows: number[] | null,
-): number {
+): number | null {
let acc = 0
let seen = 0
for (let j = 0; j < n; j++) {
@@ -321,9 +340,14 @@ export function aggregate(
else if (spec === 'max') acc = seen === 1 ? v : Math.max(acc, v)
else acc += v
}
- return spec === 'avg' ? (seen ? acc / seen : 0) : spec === 'count' ? seen : acc
+ if (spec === 'count') return seen
+ if (!seen) return null
+ return spec === 'avg' ? acc / seen : acc
}
+/** What a total with nothing to total looks like. One spelling, two readouts. */
+export const NO_TOTAL = '—'
+
// --- the spreadsheet kind (`kind: 'canvas'`) ---------------------------------
//
// A CANVAS SHEET IS UNBOUNDED, and that is the whole difference. A dataset ends
@@ -1020,14 +1044,19 @@ export class Grid {
// footer reading "[object Object] £97,050" is not a statement about
// anything.
const label = typeof spec === 'string' ? spec : 'fx'
- const hint = typeof spec === 'string' ? t('Click to change or remove this total') : `= ${spec.f}`
+ const hint = out === null
+ // The dash is not an error and must not read as one. It says the
+ // population is empty, which is a fact about the VIEW — so the hint
+ // names the filter, the only thing that can have emptied it.
+ ? t('No rows to total — the filter leaves none showing.')
+ : typeof spec === 'string' ? t('Click to change or remove this total') : `= ${spec.f}`
// A COUNT IS NOT MONEY. `formatValue` dresses the answer in the column's
// own format, which is right for sum/avg/min/max — they are quantities of
// the same thing — and wrong for a count, which is a number of ROWS:
// eight deals in a £ column rendered as "count £8.00". Nobody hit this
// while the only way to choose `count` was a dropdown in a side panel;
// it is one click from the number now.
- const shown = spec === 'count' ? fmtNum(out) : formatValue(out, c)
+ const shown = out === null ? NO_TOTAL : spec === 'count' ? fmtNum(out) : formatValue(out, c)
return `<div class="dg-cell${fz.cls}${filtered ? ' dg-part' : ''}${this.store.readOnly ? '' : ' dg-tot'}"${aria} ` +
`${this.store.readOnly ? '' : `data-tcol="${c.id}" title="${esc(hint)}" `}` +
`style="${w};text-align:${alignFor(c.type)}">` +
diff --git a/dash/src/i18n/de.ts b/dash/src/i18n/de.ts
index 70850de0..994ba34b 100644
--- a/dash/src/i18n/de.ts
+++ b/dash/src/i18n/de.ts
@@ -581,6 +581,7 @@ export const de: Catalog = {
"Top {n}": "Obere {n}",
"Total": "Gesamt",
"Totals": "Summen",
+ "No rows to total — the filter leaves none showing.": "Keine Zeilen zum Summieren – der Filter lässt keine sichtbar.",
"Totals cover the {n} row(s) the filter leaves showing, not all {all}.": "Die Summen umfassen die {n} vom Filter angezeigte(n) Zeile(n), nicht alle {all}.",
"Transpose": "Transponieren",
"Try again": "Erneut versuchen",
diff --git a/dash/src/i18n/es.ts b/dash/src/i18n/es.ts
index 446f57aa..3726563e 100644
--- a/dash/src/i18n/es.ts
+++ b/dash/src/i18n/es.ts
@@ -581,6 +581,7 @@ export const es: Catalog = {
"Top {n}": "Primeros {n}",
"Total": "Total",
"Totals": "Totales",
+ "No rows to total — the filter leaves none showing.": "No hay filas que sumar: el filtro no deja ninguna a la vista.",
"Totals cover the {n} row(s) the filter leaves showing, not all {all}.": "Los totales abarcan las {n} fila(s) que deja ver el filtro, no las {all}.",
"Transpose": "Transponer",
"Try again": "Reintentar",
diff --git a/dash/src/i18n/fr.ts b/dash/src/i18n/fr.ts
index 56c053a5..30a97b6b 100644
--- a/dash/src/i18n/fr.ts
+++ b/dash/src/i18n/fr.ts
@@ -581,6 +581,7 @@ export const fr: Catalog = {
"Top {n}": "{n} premiers",
"Total": "Total",
"Totals": "Totaux",
+ "No rows to total — the filter leaves none showing.": "Aucune ligne à totaliser — le filtre n’en laisse aucune visible.",
"Totals cover the {n} row(s) the filter leaves showing, not all {all}.": "Les totaux portent sur les {n} ligne(s) laissées par le filtre, pas sur les {all}.",
"Transpose": "Transposer",
"Try again": "Réessayer",
diff --git a/dash/src/i18n/it.ts b/dash/src/i18n/it.ts
index c355215f..2ec97a76 100644
--- a/dash/src/i18n/it.ts
+++ b/dash/src/i18n/it.ts
@@ -581,6 +581,7 @@ export const it: Catalog = {
"Top {n}": "Primi {n}",
"Total": "Totale",
"Totals": "Totali",
+ "No rows to total — the filter leaves none showing.": "Nessuna riga da totalizzare: il filtro non ne lascia visibile nessuna.",
"Totals cover the {n} row(s) the filter leaves showing, not all {all}.": "I totali riguardano le {n} riga/righe lasciate dal filtro, non tutte le {all}.",
"Transpose": "Trasponi",
"Try again": "Riprova",
diff --git a/dash/src/i18n/ja.ts b/dash/src/i18n/ja.ts
index 04cdf86e..bdd4d1bd 100644
--- a/dash/src/i18n/ja.ts
+++ b/dash/src/i18n/ja.ts
@@ -581,6 +581,7 @@ export const ja: Catalog = {
"Top {n}": "上位 {n} 件",
"Total": "計",
"Totals": "合計",
+ "No rows to total — the filter leaves none showing.": "合計する行がありません — フィルターで 1 行も表示されていません。",
"Totals cover the {n} row(s) the filter leaves showing, not all {all}.": "合計はフィルターで表示されている {n} 行が対象です(全 {all} 行ではありません)。",
"Transpose": "行列を入れ替え",
"Try again": "もう一度試す",
diff --git a/dash/src/i18n/packed.ts b/dash/src/i18n/packed.ts
index 4b92061f..6be5e71a 100644
--- a/dash/src/i18n/packed.ts
+++ b/dash/src/i18n/packed.ts
@@ -336,6 +336,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"No numeric values in this column for the current selection.": ["現在の選択範囲では、この列に数値がありません。","在当前选择下,此列没有数值。","在目前的選取範圍中,此欄沒有數值。","No hay valores numéricos en esta columna para la selección actual.","Aucune valeur numérique dans cette colonne pour la sélection actuelle.","Keine numerischen Werte in dieser Spalte für die aktuelle Auswahl.","Nessun valore numerico in questa colonna per la selezione corrente."],
"No page header": ["ページヘッダーなし","不要页眉","不要頁首","Sin encabezado de página","Aucun en-tête de page","Keine Seitenkopfzeile","Nessuna intestazione di pagina"],
"No rows match the current selection.": ["現在の選択条件に一致する行はありません。","没有行符合当前选择。","沒有符合目前選取範圍的列。","Ninguna fila coincide con la selección actual.","Aucune ligne ne correspond à la sélection actuelle.","Keine Zeilen passen zur aktuellen Auswahl.","Nessuna riga corrisponde alla selezione corrente."],
+ "No rows to total — the filter leaves none showing.": ["合計する行がありません — フィルターで 1 行も表示されていません。","没有可合计的行——筛选后没有任何行显示。","沒有可合計的列——篩選後沒有任何列顯示。","No hay filas que sumar: el filtro no deja ninguna a la vista.","Aucune ligne à totaliser — le filtre n’en laisse aucune visible.","Keine Zeilen zum Summieren – der Filter lässt keine sichtbar.","Nessuna riga da totalizzare: il filtro non ne lascia visibile nessuna."],
"No rule": ["規則なし","无规则","無規則","Sin regla","Aucune règle","Keine Regel","Nessuna regola"],
"No sheet is open, so there is nothing for this to run on.": ["シートが開かれていないため、実行する対象がありません。","没有打开任何工作表,因此无处可执行。","沒有開啟任何工作表,因此無處可執行。","No hay ninguna hoja abierta, así que no hay nada sobre lo que ejecutarlo.","Aucune feuille n’est ouverte : il n’y a rien sur quoi l’exécuter.","Es ist kein Blatt geöffnet, also gibt es nichts, worauf das laufen könnte.","Nessun foglio è aperto, quindi non c’è nulla su cui eseguirlo."],
"No table sheet is open.": ["テーブルシートが開かれていません。","当前没有打开表格工作表。","目前沒有開啟任何表格工作表。","No hay ninguna hoja de tabla abierta.","Aucune feuille de tableau n’est ouverte.","Es ist kein Tabellenblatt geöffnet.","Nessun foglio tabella è aperto."],
diff --git a/dash/src/i18n/zh-Hans.ts b/dash/src/i18n/zh-Hans.ts
index 4e0dea18..cb57c251 100644
--- a/dash/src/i18n/zh-Hans.ts
+++ b/dash/src/i18n/zh-Hans.ts
@@ -581,6 +581,7 @@ export const zhHans: Catalog = {
"Top {n}": "最高 {n} 项",
"Total": "合计",
"Totals": "合计",
+ "No rows to total — the filter leaves none showing.": "没有可合计的行——筛选后没有任何行显示。",
"Totals cover the {n} row(s) the filter leaves showing, not all {all}.": "合计仅包含筛选后显示的 {n} 行,而非全部 {all} 行。",
"Transpose": "转置",
"Try again": "重试",
diff --git a/dash/src/i18n/zh-Hant.ts b/dash/src/i18n/zh-Hant.ts
index 12512f87..53da1675 100644
--- a/dash/src/i18n/zh-Hant.ts
+++ b/dash/src/i18n/zh-Hant.ts
@@ -581,6 +581,7 @@ export const zhHant: Catalog = {
"Top {n}": "最高 {n} 項",
"Total": "合計",
"Totals": "合計",
+ "No rows to total — the filter leaves none showing.": "沒有可合計的列——篩選後沒有任何列顯示。",
"Totals cover the {n} row(s) the filter leaves showing, not all {all}.": "合計僅包含篩選後顯示的 {n} 列,而非全部 {all} 列。",
"Transpose": "轉置",
"Try again": "重試",
diff --git a/dash/src/main.ts b/dash/src/main.ts
index 3b403056..9c4aa1bb 100644
--- a/dash/src/main.ts
+++ b/dash/src/main.ts
@@ -100,7 +100,7 @@ import {
import { planTableSplit, planCanvasSplit, type SplitSpec } from './tocolumns.ts'
import { importDelimited } from './import.ts'
import { TYPE_LABEL } from './format.ts'
-import { defaultBinding, renderChart, chartHeading, type ChartBinding } from './chart.ts'
+import { defaultBinding, renderChart, chartHeading, missingColumns, type ChartBinding } from './chart.ts'
import { readCell } from './store.ts'
import { hiddenSet } from './rowcol.ts'
import { FUNCTIONS, dependencies, recalc } from './formula.ts'
@@ -776,7 +776,18 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', sav
if (sheet) void editFormula(store, sheet, col)
}
- // --- chart: bound to columns, derived at render, never stored
+ // --- chart: the NUMBERS are derived at render and never stored; the CHOICE
+ // of what to chart is document state (`doc.chart`, model.ts `OpenChart`).
+ //
+ // Both used to live in the two `let`s below and nowhere else, under a comment
+ // saying "never stored". Deriving the numbers is right — a chart must never
+ // be a stale copy of the sheet. But "these columns, on that sheet, as a pie"
+ // is a choice somebody made, and it was lost on reload, on closing the tab,
+ // and on saving the file and sending it: the reader opened a workbook with no
+ // chart and nothing to say one had ever been drawn.
+ //
+ // The `let`s stay as the live copy — every redraw path already reads them —
+ // and `rememberChart` mirrors each change into the document.
const chartEl = app.querySelector<HTMLElement>('.dx-chart')!
const chartBody = app.querySelector<HTMLElement>('.dx-chart-body')!
const chartTitle = app.querySelector<HTMLElement>('.dx-chart-title')!
@@ -797,6 +808,30 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', sav
return s && s.kind === 'table' ? s : null
}
+ /**
+ * Mirror the live chart choice into `doc.chart`, so it survives the file.
+ *
+ * THROUGH `setDocProps`, which is the existing doc-level patch and gives an
+ * inverse for free — so ⌘Z takes back "I switched it to a pie", which is a
+ * change to the document like any other now that it is IN the document.
+ *
+ * GUARDED AGAINST A NO-OP COMMIT. `drawChart` runs on every `doc` event, so
+ * writing unconditionally from there would commit on its own commit forever.
+ * Comparing the serialized shape is enough: the binding is four plain fields
+ * and an id, and this is the one place the comparison is made.
+ */
+ const rememberChart = (): void => {
+ if (store.readOnly) return
+ const want = binding && chartSheetId && !chartEl.hidden
+ ? { sheet: chartSheetId, binding }
+ : null
+ const have = store.doc.chart ?? null
+ if (JSON.stringify(want) === JSON.stringify(have)) return
+ store.commit(want
+ ? { op: 'setDocProps', props: { chart: structuredClone(want) } }
+ : { op: 'setDocProps', props: {}, drop: ['chart'] })
+ }
+
const drawChart = () => {
if (!binding || chartEl.hidden) return
teardown?.()
@@ -804,7 +839,16 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', sav
// The sheet it was about has been deleted. There is nothing left to be
// truthful about, so the panel closes rather than keeping the last numbers
// it happens to be holding on screen.
- if (!sheet) { teardown = null; binding = null; chartSheetId = null; chartEl.hidden = true; return }
+ if (!sheet) {
+ teardown = null; binding = null; chartSheetId = null; chartEl.hidden = true
+ // `drawChart` runs INSIDE the `doc` emit, and `rememberChart` commits —
+ // re-entering the store from its own event. Deferred by a microtask so
+ // the drop is an ordinary commit after this one finishes, which is also
+ // what makes it a separate, undoable step rather than a rider on the
+ // delete.
+ queueMicrotask(rememberChart)
+ return
+ }
// THE SHEET ON SCREEN, READ WITHOUT NARROWING. This was `grid.sheet`, and
// `drawChart` runs on `doc`, on `view` and on every sheet change — so with a
// chart open, switching to a SPREADSHEET tab threw out of the redraw, and
@@ -843,11 +887,35 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', sav
}
binding = next
chartSheetId = to.id
+ rememberChart()
drawChart()
},
})
}
- store.on('doc', drawChart)
+ /**
+ * THE PANEL FOLLOWS THE DOCUMENT, not only the gestures in this file.
+ *
+ * `doc.chart` can change without anybody touching the chart controls: ⌘Z, a
+ * redo, "Replace from JSON…", a restored version, or a collaborator's op.
+ * Measured after the field first landed: closing the chart dropped it
+ * correctly and ONE undo put `doc.chart` back — with the panel still shut. The
+ * file said there was a chart and the screen said there was not, which is the
+ * same two-readouts-disagreeing failure as the footer that ignored the filter,
+ * one layer up.
+ *
+ * `viz` owns the panel when 3D is up, so this stands aside for it rather than
+ * fighting it for the same element.
+ */
+ const syncChartPanel = (): void => {
+ if (viz) return
+ const want = store.doc.chart
+ if (want && !binding) reopenStoredChart()
+ else if (!want && binding) {
+ teardown?.(); teardown = null
+ binding = null; chartSheetId = null; chartEl.hidden = true
+ } else drawChart()
+ }
+ store.on('doc', syncChartPanel)
// FILTERING AND SORTING ARE VIEW STATE: `store.view()` emits `view` and never
// `doc` (that is the point — they must not dirty the file). Listening only for
// `doc` is why the chart ignored a filter completely: nothing redrew it.
@@ -860,10 +928,15 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', sav
}
if (!binding) return
binding.kind = KINDS[(KINDS.indexOf(binding.kind) + 1) % KINDS.length]
+ rememberChart()
drawChart()
})
app.querySelector('.dx-chart-close')!.addEventListener('click', () => {
chartEl.hidden = true
+ // Closing the panel is closing the chart — the document should not keep a
+ // chart the reader has just dismissed and would not see on reopening.
+ binding = null; chartSheetId = null
+ rememberChart()
clearPivot()
teardown?.(); teardown = null
vizDown?.(); vizDown = null; viz = null; vizSheetId = null
@@ -877,8 +950,38 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', sav
chartSheetId = sheet.id
if (!binding) { showFindings(findingsEl, [{ message: t('This sheet has no numeric column to chart yet.') }]); return }
chartEl.hidden = false
+ rememberChart()
drawChart()
})
+ /**
+ * REOPEN THE CHART THE FILE WAS SAVED WITH.
+ *
+ * Everything it needs is validated here rather than trusted, because the
+ * field is additive and the workbook may have been round-tripped through a
+ * build that has never heard of it: the sheet can have been deleted, or
+ * turned into a spreadsheet, and the columns can have been removed or
+ * renamed. Any of those and the panel simply does not open — an empty axis
+ * against columns that no longer exist is the failure `chartHeading` and
+ * `drawChart` were already written to avoid, arriving one step earlier.
+ *
+ * It does NOT call `rememberChart`: reopening is not a change, and committing
+ * one would dirty a file the reader has only looked at.
+ */
+ const reopenStoredChart = (): void => {
+ const stored = store.doc.chart
+ if (!stored || typeof stored.sheet !== 'string' || !stored.binding) return
+ const sheet = store.doc.sheets.find((x) => x.id === stored.sheet)
+ if (!sheet || sheet.kind !== 'table') return
+ const b = stored.binding
+ if (!KINDS.includes(b.kind) || typeof b.x !== 'string' || !Array.isArray(b.series)) return
+ if (missingColumns(sheet, b).length) return
+ binding = { ...b, series: [...b.series] }
+ chartSheetId = sheet.id
+ chartEl.hidden = false
+ drawChart()
+ }
+ reopenStoredChart()
+
app.querySelector('[data-act="formula"]')!.addEventListener('click', () => {
// THE SHEET IS CAPTURED HERE, not read again when the dialog closes. The
// form is modal but the document is not frozen behind it: a remote op or a
diff --git a/dash/src/model.ts b/dash/src/model.ts
index 76971448..4cb6664b 100644
--- a/dash/src/model.ts
+++ b/dash/src/model.ts
@@ -611,6 +611,14 @@ export interface DashDoc {
measures?: Record<string, Measure>
/** the data story — see the Story block at the foot of this file */
story?: Story
+ /**
+ * The chart panel, if one is open. See `OpenChart`.
+ *
+ * ADDITIVE, like `story`: a build that has never heard of it keeps it on a
+ * round trip and opens with no chart, which is exactly what every build did
+ * before this field existed.
+ */
+ chart?: OpenChart
/** Defined names — see the DEFINED NAMES block just above `DashDoc`. */
names?: Record<string, DefinedName>
views?: View[]
@@ -916,6 +924,35 @@ export const rowCount = (doc: DashDoc): number =>
import type { ChartBinding } from './chart.ts'
import type { Viz3dBinding } from './viz3d.ts'
+/**
+ * THE CHART PANEL IS DOCUMENT STATE, and it was not.
+ *
+ * `binding` and the id of the sheet it is pinned to lived in two module-local
+ * `let`s in main.ts, under a comment reading "derived at render, never stored".
+ * Deriving it at render is right — the numbers must never be a stale copy of
+ * the sheet — but "which columns am I charting, on which sheet" is not derived
+ * from anything. It is a choice somebody made, and it was thrown away by a
+ * reload, by closing the tab, and by saving the file and sending it: the
+ * recipient opened a workbook with no chart in it and no way to know one had
+ * ever been drawn.
+ *
+ * ONE, NOT A LIST, because the panel is one. A second stored chart would have
+ * no way to be shown, and a field the UI cannot express is a field that goes
+ * wrong quietly. `views` is the place a workbook keeps many charts.
+ *
+ * `sheet` is an id and may DANGLE — the sheet it named can be deleted by a
+ * build that does not know this field exists, which is the whole point of an
+ * additive field. Nothing may throw on that: `main.ts` drops the panel and
+ * `validate.ts` reports it, exactly as they already do when the sheet is
+ * deleted in front of you.
+ */
+export interface OpenChart {
+ /** the id of the TABLE sheet the chart is an argument about */
+ sheet: string
+ /** the same binding shape chart.ts and StoryStep use — columns, not numbers */
+ binding: ChartBinding
+}
+
// --- data story --------------------------------------------------------------
//
// An ADDITIVE top-level field (`DashDoc.story`). A build that has never heard of
diff --git a/dash/src/print.ts b/dash/src/print.ts
index 88faa62c..4f0ed541 100644
--- a/dash/src/print.ts
+++ b/dash/src/print.ts
@@ -107,7 +107,7 @@ import { colToLetters } from './a1.ts'
import { recalc, isErr, type Vec } from './formula.ts'
import { evaluateRules, type CellStyle } from './condfmt.ts'
import {
- aggregate, canvasAlign, canvasKey, canvasShown, canvasUsed, viewStatusText,
+ aggregate, NO_TOTAL, canvasAlign, canvasKey, canvasShown, canvasUsed, viewStatusText,
type TotalSpec,
} from './grid.ts'
import { cellKey, recalcWorkbook, workbookSources } from './cellformula.ts'
@@ -661,7 +661,11 @@ function tableMarkup(
const comp = view.computed?.get(c.id)
const value = aggregate(spec, (idx) => (comp ? comp[idx] : readCell(sheet.data[c.id], idx)), n, order)
const label = typeof spec === 'string' ? (AGG_LABEL[spec] ?? spec.toUpperCase()) : 'ƒ'
- const shown = spec === 'count' ? nf(value) : formatValue(value, c)
+ // `null` = nothing in view to total. Paper has no tooltip to explain the
+ // dash, but printing a fabricated 0 that the screen no longer shows
+ // would break this row's one promise: the paper cannot say a number the
+ // screen does not.
+ const shown = value === null ? NO_TOTAL : spec === 'count' ? nf(value) : formatValue(value, c)
return `<td style="text-align:${alignFor(c.type)}">` +
`<span class="dxpr-agg">${esc(label)}</span> ${esc(shown)}</td>`
})
diff --git a/dash/src/tabs.css b/dash/src/tabs.css
index 0a1c7477..62690de7 100644
--- a/dash/src/tabs.css
+++ b/dash/src/tabs.css
@@ -290,6 +290,35 @@
/* 0.35 — one figure for a dead control across the app; see .dx-btn[disabled] */
.dx-tab-menu button:disabled { color: var(--muted); opacity: 0.35; cursor: default; }
.dx-tab-sep { height: 1px; margin: 4px 2px; background: var(--line); }
+
+/* ————— a row that TEACHES, rather than naming a command —————
+ The two kinds of sheet are this product's central distinction, and this menu
+ is the only place it is ever explained. The rows were built as a title plus a
+ subtitle span (tabs.ts, the + handler) and then given NO rules of their own,
+ so they inherited the one-line ellipsis above — which is right for "Rename"
+ and cut "Typed columns — for volume, joins and charts" mid-phrase inside a
+ 220px menu. A truncated explanation of the central concept explains nothing
+ and reads as a bug.
+
+ So: the row wraps, and the menu holding these rows is wide enough to wrap
+ into. `nowrap` and the ellipsis are undone explicitly rather than by
+ specificity accident — a later menu row will inherit whichever it asks for. */
+.dx-tab-menu-kinds { max-width: 296px; min-width: 248px; }
+.dx-tab-menu button.dx-tab-menu-row {
+ display: grid;
+ gap: 1px;
+ padding: 7px 9px;
+ white-space: normal;
+ overflow: visible;
+ text-overflow: clip;
+}
+.dx-tab-menu-title { font-weight: 600; }
+.dx-tab-menu-why {
+ font-size: var(--fs-small);
+ line-height: 1.35;
+ color: var(--muted);
+}
+
.dx-tab-note {
margin: 2px 4px 6px;
font-size: var(--fs-small);
diff --git a/dash/src/tabs.ts b/dash/src/tabs.ts
index 868192a2..2cfd825a 100644
--- a/dash/src/tabs.ts
+++ b/dash/src/tabs.ts
@@ -1048,6 +1048,9 @@ export function mountTabs(host: TabsHost): Tabs {
addBtn.addEventListener('click', () => {
if (ro()) return
const menu = popover(addBtn)
+ // Widens the menu and lets its rows wrap — the explanation is the point of
+ // this menu, and at the shared 220px it was ellipsed mid-phrase.
+ menu.classList.add('dx-tab-menu-kinds')
const row = (label: string, why: string, kind: 'table' | 'canvas'): void => {
const b = document.createElement('button')
b.className = 'dx-tab-menu-row'
diff --git a/dash/src/validate.ts b/dash/src/validate.ts
index f15be742..3f7f224e 100644
--- a/dash/src/validate.ts
+++ b/dash/src/validate.ts
@@ -315,6 +315,7 @@ export function validateDoc(doc: DashDoc): ValidateResult {
checkMeasures(doc, sheetIds, tables, add)
checkViews(doc, tables, kinds, add)
checkStory(doc, tables, kinds, add)
+ checkOpenChart(doc, tables, kinds, add)
return result(findings)
}
@@ -920,6 +921,46 @@ function checkViews(
})
}
+// --- the open chart panel -----------------------------------------------------
+//
+// `doc.chart` (model.ts `OpenChart`) is additive, so a workbook can reach this
+// build having been through one that never heard of it: the sheet it names can
+// have been deleted or turned into a spreadsheet, and its columns can have been
+// removed. main.ts already declines to reopen the panel in each of those cases,
+// which is the safe behaviour and also a SILENT one — the chart the file was
+// saved with simply is not there. Saying so is this function's whole job.
+
+function checkOpenChart(
+ doc: DashDoc, tables: Map<string, TableSheet>, kinds: Map<string, string>,
+ add: (f: Finding) => void,
+): void {
+ const chart = (doc as unknown as Record<string, unknown>).chart
+ if (!isObj(chart)) return
+ const sid = typeof chart.sheet === 'string' ? chart.sheet : ''
+ const src = tables.get(sid)
+ if (!src) {
+ add({ code: 'chart-missing-sheet', severity: 'suspicious', path: 'chart',
+ message: kinds.has(sid)
+ ? `The saved chart is about sheet ${q(sid)}, which is a ${kinds.get(sid)} sheet and has no columns to chart — the panel does not open.`
+ : `The saved chart is about sheet ${q(sid)}, which is not in this workbook — the panel does not open, so a reader sees no chart and nothing saying one was saved.` })
+ return
+ }
+ const bind = isObj(chart.binding) ? chart.binding : null
+ if (!bind) {
+ add({ code: 'bad-chart', severity: 'suspicious', path: 'chart.binding',
+ message: 'The saved chart has no binding, so there is nothing to draw and the panel does not open.' })
+ return
+ }
+ const cols = new Set((arr(src.columns) as Column[]).filter(isObj).map((c) => c.id as string))
+ const named = (field: string, id: unknown): void => {
+ if (typeof id !== 'string' || cols.has(id)) return
+ add({ code: 'chart-missing-column', severity: 'suspicious', path: `chart.binding.${field}`, column: id, sheet: sid,
+ message: `The saved chart binds column ${q(id)}, which sheet ${q(sid)} does not have — the panel does not open at all rather than drawing an axis against a column that is gone.` })
+ }
+ named('x', bind.x)
+ arr(bind.series).forEach((c, i) => named(`series[${i}]`, c))
+}
+
// --- the data story ----------------------------------------------------------
function checkStory(
diff --git a/scripts/test-dash-chart.ts b/scripts/test-dash-chart.ts
index 23adbf97..fd409e72 100644
--- a/scripts/test-dash-chart.ts
+++ b/scripts/test-dash-chart.ts
@@ -291,5 +291,86 @@ const cats = (o: Record<string, unknown>) => (o.xAxis as { data: string[] }).dat
ok(defaultBinding(s) === null, 'a sheet with no numeric column has no default chart')
}
+// ------------------------------------------------- the chart the FILE remembers
+//
+// `doc.chart` (model.ts `OpenChart`). The binding and the sheet it is pinned to
+// lived in two module-local `let`s in main.ts and nowhere else, so the choice
+// of what to chart was lost on reload, on closing the tab, and on saving the
+// file and sending it — the reader opened a workbook with no chart in it and
+// nothing to say one had ever been drawn.
+//
+// main.ts BOOTS ON EVALUATION and can never be imported, so what is provable
+// here is the mechanism: the field round-trips, the commit that writes it has a
+// working inverse, it is stored by VALUE, and a stale one is reported rather
+// than drawn. The wiring itself is exercised in a browser against the built
+// shell, which is the only place it can be.
+{
+ const { registerHooks } = await import('node:module')
+ registerHooks({
+ load(url: string, context: unknown, next: (u: string, c: unknown) => unknown) {
+ if (url.endsWith('.css')) return { format: 'module', source: 'export {}', shortCircuit: true }
+ return next(url, context)
+ },
+ } as never)
+ const { parseDoc } = await import('../dash/src/model.ts')
+ const { Store } = await import('../dash/src/store.ts')
+ const { validateDoc } = await import('../dash/src/validate.ts')
+
+ const bind: ChartBinding = { x: 'region', series: ['value'], kind: 'bar', aggregate: 'sum' }
+ const base = () => ({
+ format: 'bento/dash', version: 1, policy: 'bento-dash-1', docId: 'd', title: 't',
+ sheets: [sheet()],
+ })
+
+ // ADDITIVITY (PLATFORM §3): a build that has never heard of the field keeps
+ // it. `parseDoc` is that build for this purpose — it must not drop it.
+ const withChart = { ...base(), chart: { sheet: 'sh', binding: bind } }
+ const parsed = parseDoc(JSON.stringify(withChart)).doc
+ ok(JSON.stringify(parsed.chart) === JSON.stringify(withChart.chart),
+ 'a saved chart survives parseDoc unchanged — the field is additive, not a field parseDoc knows')
+
+ // THE COMMIT, AND ITS INVERSE. Writing it through `setDocProps` is what makes
+ // switching the chart to a pie an undoable change to the document rather than
+ // a thing that happens to the screen.
+ const st = new Store(parseDoc(JSON.stringify(base())).doc)
+ ok(st.doc.chart === undefined, 'a workbook with no chart has no field — absent, not an empty object')
+ st.commit({ op: 'setDocProps', props: { chart: { sheet: 'sh', binding: { ...bind } } } })
+ ok(st.doc.chart?.sheet === 'sh' && st.doc.chart?.binding.kind === 'bar', 'opening a chart records it')
+ st.commit({ op: 'setDocProps', props: { chart: { sheet: 'sh', binding: { ...bind, kind: 'pie' } } } })
+ ok(st.doc.chart?.binding.kind === 'pie', 'switching kind records the new kind')
+ st.undo()
+ ok(st.doc.chart?.binding.kind === 'bar', 'and ONE undo puts the bar chart back')
+ st.undo()
+ ok(st.doc.chart === undefined,
+ 'a second undo removes the field entirely rather than leaving an empty chart behind')
+
+ // BY VALUE, NOT BY REFERENCE — the quiet one. main.ts keeps a live `binding`
+ // object and cycles `binding.kind` in place. Store the reference and that
+ // mutation edits the DOCUMENT with no commit: no op, no undo entry, nothing
+ // for a collaborator to receive, and a file that is dirty without being
+ // marked dirty. `rememberChart` clones for exactly this reason.
+ const live: ChartBinding = { ...bind }
+ const st2 = new Store(parseDoc(JSON.stringify(base())).doc)
+ st2.commit({ op: 'setDocProps', props: { chart: structuredClone({ sheet: 'sh', binding: live }) } })
+ live.kind = 'line'
+ ok(st2.doc.chart?.binding.kind === 'bar',
+ 'mutating the live binding does NOT reach into the document — a change with no op behind it is a file dirty in secret')
+
+ // A STALE ONE IS REPORTED. main.ts declines to reopen the panel when the
+ // sheet or a column is gone, which is right and also silent; validate is
+ // where the silence gets a sentence.
+ const gone = parseDoc(JSON.stringify({ ...base(), chart: { sheet: 'nope', binding: bind } })).doc
+ ok(validateDoc(gone).findings.some((f) => f.code === 'chart-missing-sheet'),
+ 'a chart naming a sheet that is not in the workbook is reported')
+ const noCol = parseDoc(JSON.stringify({
+ ...base(), chart: { sheet: 'sh', binding: { ...bind, series: ['value', 'ghost'] } },
+ })).doc
+ ok(validateDoc(noCol).findings.some((f) => f.code === 'chart-missing-column'),
+ 'and so is one binding a column the sheet no longer has')
+ const fine = parseDoc(JSON.stringify(withChart)).doc
+ ok(!validateDoc(fine).findings.some((f) => f.code.startsWith('chart-')),
+ 'while a chart that still resolves is reported as nothing at all')
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`)
if (failures) process.exit(1)
diff --git a/scripts/test-dash-coltype.ts b/scripts/test-dash-coltype.ts
index c7e8b528..7b57e999 100644
--- a/scripts/test-dash-coltype.ts
+++ b/scripts/test-dash-coltype.ts
@@ -67,14 +67,20 @@ const mk = (v: unknown[], type = 'text'): any => parseDoc(JSON.stringify({
}],
})).doc
-const sumOf = (st: any, n: number): number =>
+const sumOf = (st: any, n: number): number | null =>
aggregate('sum', (i: number) => readCell((st.doc.sheets[0] as any).data.amt, i), n, null)
console.log('1 · the reported bug: the total after a type change')
{
const rows = ['1200.50', '3000', '6108.35', '0']
const st = new Store(mk(rows))
- ok(sumOf(st, 4) === 0, 'a TEXT column of numeric strings totals 0 — correct, they are text')
+ // `null`, NOT 0 — and this rig is the reason the difference matters. The
+ // point here has always been that four numeric-looking STRINGS have no total,
+ // because nothing in the column is a number. `0` said that badly: it is a
+ // quantity, drawn in the column's format, and a reader sees "SUM £0" under
+ // rows plainly containing £1200.50. `—` says the true thing, that there is
+ // nothing here to add up.
+ ok(sumOf(st, 4) === null, 'a TEXT column of numeric strings has NO total — they are text, and none of them is a number')
st.commit({ op: 'setColumn', sheet: 's1', col: 'amt', patch: { type: 'number' } })
ok(sumOf(st, 4) === 10308.85,
'and after setting the type to number the footer total is RIGHT (10308.85, was 0)')
@@ -102,7 +108,7 @@ console.log('\n2 · undo restores the bytes, not only the declaration')
ok(sh.data.amt.v.join('|') === '1200.50|3000',
'AND the original strings BYTE FOR BYTE — text→number→text loses "1200.50" to "1200.5", ' +
'which a typeof check cannot see')
- ok(sumOf(st, 2) === 0, 'so the total reads 0 again, which is what a text column should total')
+ ok(sumOf(st, 2) === null, 'so the total is blank again, which is what a text column should total — nothing')
ok(validateDoc(st.doc).findings.every((f: any) => f.code !== 'type-storage-mismatch'),
'and undo does not leave the document disagreeing with itself either')
}
diff --git a/scripts/test-dash-filter.ts b/scripts/test-dash-filter.ts
index dadf073a..9a92a2dc 100644
--- a/scripts/test-dash-filter.ts
+++ b/scripts/test-dash-filter.ts
@@ -405,10 +405,28 @@ ok(eq(order([{ col: 'amount', pred: { op: 'topN', n: 0 } }], []), []),
'avg divides by the numbers it actually saw (6), not by the row count (8) — an average over blanks is not an average')
ok(aggregate('count', read, all, null) === 6, 'and count agrees with it')
- // an empty filter result must not invent a number
- ok(aggregate('sum', read, 0, []) === 0 && aggregate('avg', read, 0, []) === 0,
- 'a filter matching nothing totals 0 rather than NaN')
- ok(aggregate('min', read, 0, []) === 0, 'and min over nothing is 0, not Infinity')
+ // AN EMPTY POPULATION HAS NO ANSWER, and these three lines used to assert the
+ // bug. The old text read "a filter matching nothing totals 0 rather than
+ // NaN": it was written to rule out NaN and Infinity, which it did, and then
+ // settled on 0 — a VALUE, drawn in the column's format, indistinguishable
+ // from a real result. Filter to a stage no deal is in and the footer said
+ // `sum £0` and `avg 0%` under an empty grid. That is failure 6 in this file's
+ // own header wearing different clothes: a real number answering a question
+ // nobody could have asked. Guarding NaN was right and stopping there was not.
+ ok(aggregate('sum', read, 0, []) === null && aggregate('avg', read, 0, []) === null,
+ 'a filter matching nothing has NO total — null, not a confident 0')
+ ok(aggregate('min', read, 0, []) === null && aggregate('max', read, 0, []) === null,
+ 'and min/max over nothing are null, not 0 and not Infinity')
+ ok(aggregate('count', read, 0, []) === 0,
+ 'COUNT is the exception: "how many did I see" is answerable, and the answer is 0')
+
+ // The same hole without a filter: a numeric column that is entirely blank.
+ // `n` rows exist, none is a number, so `seen` is 0 by a different route.
+ const blanks = [null, null, 'n/a']
+ ok(aggregate('sum', (i) => blanks[i], 3, null) === null,
+ 'a column of blanks has no sum either — the emptiness is the population, not the row count')
+ ok(aggregate('count', (i) => blanks[i], 3, null) === 0,
+ 'and count says plainly that it saw none of them')
}
diff --git a/scripts/test-dash-functions.ts b/scripts/test-dash-functions.ts
index 3c0ff5c9..b2069322 100644
--- a/scripts/test-dash-functions.ts
+++ b/scripts/test-dash-functions.ts
@@ -513,19 +513,25 @@ const grid = (v: Vec, cols: number): Vec => {
ok(aggregate('sum', read, sorted.length, sorted) === whole,
'and a sorted view totals the same, because sorting hides nothing')
- // THE ONE PLACE THEY DO NOT AGREE, measured rather than papered over. A view
- // that hides EVERY row leaves the footer's `avg` at 0 (grid.ts `aggregate`
- // divides by `seen` and returns 0 when it saw nothing) while SUBTOTAL(101)
- // says `#DIV/0!`, which is this file's long-standing rule: an average of
- // nothing is not zero. The formula is the one that is right, the footer is
- // not this agent's file, and a rig that quietly asserted whichever it found
- // would hide the difference — so it is asserted as a DIFFERENCE.
+ // THEY AGREE NOW, AND THIS BLOCK IS THE RECORD OF THEM NOT HAVING. It used to
+ // read "the one place they do not agree": a view that hid EVERY row left the
+ // footer's `avg` at 0 while SUBTOTAL(101) said `#DIV/0!`, and the comment
+ // said the formula was the one that was right and the footer was not this
+ // agent's file to change. It is now — `aggregate` returns `null` for a
+ // population it never saw a number in, and the footer draws `—`.
+ //
+ // Kept as two assertions rather than folded into one, because the two
+ // surfaces reach the same answer by different routes and a rig that checked
+ // only one would not notice them parting again. They are ALLOWED to spell it
+ // differently: a formula lives in a cell and can carry an error value, a
+ // footer has one line and no error state, so `#DIV/0!` and `—` are the same
+ // claim in the vocabulary each surface has.
const none = buildOrder(6, get, [{ col: 'region', pred: { op: 'isOneOf', set: new Set(['Nowhere']) } }], [])
ok(none.length === 0, 'a filter can hide every row')
- ok(aggregate('avg', read, none.length, none) === 0,
- 'the footer prints 0 for the average of no rows')
+ ok(aggregate('avg', read, none.length, none) === null,
+ 'the footer has no average for no rows — null, drawn as an em dash, not a confident 0')
ok(code(ev('SUBTOTAL(101, v)', { v: markHidden([...amount], amount.map(() => true)) })) === '#DIV/0!',
- 'while SUBTOTAL(101) says #DIV/0! — an average of nothing is not zero (reported, not reconciled)')
+ 'and SUBTOTAL(101) says #DIV/0! — the same claim in the vocabulary a cell has')
ok(code(ev('SUBTOTAL(50, v)', { v: [1, 2] as Vec })) === '#VALUE!',
'a function number SUBTOTAL does not have is refused rather than defaulted to SUM')