From 9160a543d028843998d81ab9f8e47110137e9904 Mon Sep 17 00:00:00 2001 From: James Briggs <35938317+jamescalam@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:35:36 +0800 Subject: [PATCH 01/10] Sheets: a formula whose ranges add up past the budget stops before it reads a cell =SUMPRODUCT(A1:T10000, ...) with 16 ranges of 200,000 cells read each range before SUMPRODUCT ran. The budget charged each read, so it ended in #CALC! only at the 16th range, after 3 million cell reads: about 2 s on a laptop, and over 3 s on CI's runners, where the hostile test timed out. A person's sheet with such a formula froze for as long. Now, before a formula is worked out, the engine adds up the cells of every range it is sure to read (all of them, except the parts of IF, IFERROR, IFNA and IFS past the first, which may never be worked out). Each of those reads would be charged its cells anyway, so a total past the budget ends in #CALC! at once, with no cell read. A highlight's test gets the same check. refRange's span moves into refSpan, which both use. Co-authored-by: Pointman Co-authored-by: Claude --- sheets/references/sheet-template.html | 31 +++++++++++++++++++++------ tests/hostile.js | 19 ++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/sheets/references/sheet-template.html b/sheets/references/sheet-template.html index 81ac251..2d69c23 100644 --- a/sheets/references/sheet-template.html +++ b/sheets/references/sheet-template.html @@ -394,7 +394,7 @@

SHEET TITLE

if (!inp) v = null; else if (inp.formula !== undefined) { this.busy[key] = true; - try { v = ++this.steps > LIMIT.steps ? ERR("#CALC!") : this.evaluate(parse(inp.formula), tabName, 0, 0); } catch (e) { v = ERR(typeof e === "string" ? e : "#ERROR!"); } + try { var tree = parse(inp.formula); v = ++this.steps + this.sureReads(tree, tabName, 0, 0) > LIMIT.steps ? ERR("#CALC!") : this.evaluate(tree, tabName, 0, 0); } catch (e) { v = ERR(typeof e === "string" ? e : "#ERROR!"); } if (isRange(v)) v = v.rows[0][0]; if (v === undefined) v = ERR("#VALUE!"); // a function given too few arguments if (typeof v === "number" && !isFinite(v)) v = ERR("#NUM!"); @@ -403,9 +403,10 @@

SHEET TITLE

} else v = inp.value; this.memo[key] = v; return v; }; - Book.prototype.refRange = function (tok, here, dr, dc) { + // A reference's cells: a span, or null where refRange gives #REF! (no such tab, or a range off the sheet). + Book.prototype.refSpan = function (tok, here, dr, dc) { var tabName = tok.tab || here; - if (!this.raw[String(tabName).toLowerCase()]) return ERR("#REF!"); + if (!this.raw[String(tabName).toLowerCase()]) return null; var parts = tok.v.split(":"), self = this; function cell(s, isEnd) { var colOnly = /^\$?([A-Z]{1,3})$/.exec(s); @@ -413,10 +414,28 @@

SHEET TITLE

var m = /^(\$?)([A-Z]{1,3})(\$?)(\d+)$/.exec(s); if (!m) return null; return { c: colNum(m[2]) + (m[1] ? 0 : dc), r: +m[4] + (m[3] ? 0 : dr) }; } - var s = span(cell(parts[0], false), parts[1] ? cell(parts[1], true) : cell(parts[0], false)); + return span(cell(parts[0], false), parts[1] ? cell(parts[1], true) : cell(parts[0], false)); + }; + Book.prototype.refRange = function (tok, here, dr, dc) { + var tabName = tok.tab || here, s = this.refSpan(tok, here, dr, dc), self = this; if (!s) return ERR("#REF!"); var got = mk(s.r1 - s.r0 + 1, s.c1 - s.c0 + 1, function (r, c) { return self.value(tabName, addr(s.r0 + r, s.c0 + c)); }); - return parts[1] ? got : got.rows[0][0]; + return tok.v.indexOf(":") >= 0 ? got : got.rows[0][0]; + }; + // The cells a formula is sure to read: every range it names, except in the parts of IF, IFERROR, IFNA and IFS + // past their first, which may never be worked out. Each read is charged its cells (mk), so a formula whose sure + // reads are past the budget ends in #CALC! without reading a cell, where it once read millions first. + var LAZY = map({ IF: 1, IFERROR: 1, IFNA: 1, IFS: 1 }); + Book.prototype.sureReads = function (n, here, dr, dc) { + var self = this, s, f, a; + switch (n.k) { + case "ref": s = this.refSpan(n, here, dr, dc); return s ? s.n : 0; + case "neg": case "pct": return this.sureReads(n.x, here, dr, dc); + case "bin": return this.sureReads(n.l, here, dr, dc) + this.sureReads(n.r, here, dr, dc); + case "call": f = n.f.replace(/^_XLFN\./, ""); a = LAZY[f] ? n.a.slice(0, 1) : F[f] ? n.a : []; + return a.reduce(function (t, x) { return t + self.sureReads(x, here, dr, dc); }, 0); + } + return 0; }; var KEEP_RANGE = null; Book.prototype.evaluate = function (n, here, dr, dc) { @@ -493,7 +512,7 @@

SHEET TITLE

// A rule's formula is written for the top-left cell of its range; dr/dc move it to another cell. Book.prototype.ruleAt = function (formula, tabName, dr, dc) { if (++this.steps > LIMIT.steps) return false; - try { var v = this.evaluate(parse(String(formula).replace(/^=/, "")), tabName, dr, dc); if (isRange(v)) v = v.rows[0][0]; var b = bool(v); return isErr(b) ? false : b; } catch (e) { return false; } + try { var tree = parse(String(formula).replace(/^=/, "")); if (this.steps + this.sureReads(tree, tabName, dr, dc) > LIMIT.steps) return false; var v = this.evaluate(tree, tabName, dr, dc); if (isRange(v)) v = v.rows[0][0]; var b = bool(v); return isErr(b) ? false : b; } catch (e) { return false; } }; function expand(range) { // "A2:C9" -> list of {r,c} var p = String(range).toUpperCase().replace(/\$/g, "").split(":"), s = span(parseAddr(p[0]), parseAddr(p[1] || p[0])), out = []; diff --git a/tests/hostile.js b/tests/hostile.js index 2779ac5..cfb3f81 100644 --- a/tests/hostile.js +++ b/tests/hostile.js @@ -89,6 +89,25 @@ module.exports = function ({ E, test, script, within, ROOT }) { assert.strictEqual(one("=SUMPRODUCT((A1:A20=0)*(A1:T1=0))"), 400); // a small one still works assert.ok(Date.now() - t0 < 4000, `took ${Date.now() - t0} ms`); }); + test("a formula whose ranges add up past the budget ends in #CALC! before it reads a cell of them", () => { + const passes = Math.ceil(E.LIMIT.steps / 200000) + 1, big = "SUMPRODUCT(" + Array(passes).fill("A1:T10000").join(",") + ")"; + const counted = (cells) => { + const book = new E.Book({ tabs: [{ name: "T", cells: Object.assign({ A1: 1 }, cells) }] }), value = book.value; + book.reads = []; book.value = function (t, a) { this.reads.push(a); return value.call(this, t, a); }; + return book; + }; + let b = counted({ Z1: "=" + big }); + assert.strictEqual(errOf(within(3000, () => b.value("T", "Z1"))), "#CALC!"); + assert.strictEqual(b.reads.length, 1, `read ${b.reads.length} cells`); // the cell itself, and none of its 3.2 million + b = counted({ Z1: "=SUM(A1:A3)+A1" }); + assert.strictEqual(b.value("T", "Z1"), 2); // within the budget, it reads what it names + assert.deepStrictEqual(b.reads, ["Z1", "A1", "A2", "A3", "A1"]); + b = counted({ Z1: "=IF(A1=1, 5, " + big + ")", Z2: "=IFERROR(A1, " + big + ")", Z3: "=IFS(A1=1, 7, TRUE, " + big + ")" }); + assert.deepStrictEqual(["Z1", "Z2", "Z3"].map((a) => b.value("T", a)), [5, 1, 7]); // a part that may never be worked out isn't counted + b = counted({}); + assert.strictEqual(within(3000, () => b.ruleAt("=" + big + ">0", "T", 0, 0)), false); // a highlight's test, the same + assert.strictEqual(b.reads.length, 0, `read ${b.reads.length} cells`); + }); test("text a formula makes is charged by its length, not only by its cells", () => { const t = (b1) => within(3000, () => new E.Book({ tabs: [{ name: "T", cells: { B1: b1, C1: "=SUMPRODUCT(LEN(UPPER(A1:A2000&B1)))" } }] }).value("T", "C1")); assert.strictEqual(t("x"), 2000); From d9c7e4aaabcf886963826d508d3d32d5999af9c0 Mon Sep 17 00:00:00 2001 From: James Briggs <35938317+jamescalam@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:09:06 +0800 Subject: [PATCH 02/10] Sheets: a chart is drawn at the width it's shown at, so its labels stay 12 px on a phone MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The chart was a 760-unit drawing scaled to its box, so at 390 px its text drew at about 6 px and the month labels ran together; at 1280 it scaled up and "May 2026" touched "Jun 2026". Now the drawing is as wide as its box (at most 860 px) and is drawn again when that width changes. Its axes come from the engine's new chartAxes, which the tests call: - value steps are round (£0, £500, £1,000, £1,500), not quarters of the biggest bar; - month labels drop the year when the title names their one year; - labels sit in a row while they fit; months and dates then thin to every 2nd, 3rd... one, and names are cut to 12 characters and angled, thinned only when even angled ones can't all fit; - one series has no key when the title names it. Co-authored-by: Pointman Co-authored-by: Claude --- sheets/references/sheet-template.html | 71 ++++++++++++++++++++++----- tests/run.js | 65 ++++++++++++++++++++++++ 2 files changed, 125 insertions(+), 11 deletions(-) diff --git a/sheets/references/sheet-template.html b/sheets/references/sheet-template.html index 2d69c23..72d9374 100644 --- a/sheets/references/sheet-template.html +++ b/sheets/references/sheet-template.html @@ -561,6 +561,42 @@

SHEET TITLE

return inp && inp.date && f !== "date" && f !== "month" ? "date" : f; } + // --- a chart's axes, laid out for the width it's drawn at: one unit is one CSS pixel, so its 12 px text is 12 px + // on a phone too. Round value steps (£0, £500, £1,000). Month names without the year when the title names their + // one year. Category labels never overlap: in a row while they fit (up to 20 characters); else months and dates + // thin to every 2nd, 3rd … one, and names are cut to 12 characters and angled, thinned only when even angled ones + // can't all fit. A key only when the title doesn't name the one series. measure(text): its width in px at 12 px. + function chartAxes(o) { + var FS = 12, PAD = 16, RIGHT = 12, data = o.data || {}, fmt = o.fmt || "int", W = o.width, measure = o.measure; + var max = o.max > 0 ? o.max : 1, raw = max / 5, mag = Math.pow(10, Math.floor(Math.log10(raw))), f = raw / mag; + var step = (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * mag; + if ((fmt === "int" || fmt === "money") && step < 1) step = 1; + var n = Math.max(1, Math.ceil(max / step - 1e-9)), ticks = []; + for (var i = 0; i <= n; i++) { var tv = Number((step * i).toPrecision(12)); ticks.push({ v: tv, text: fmtValue(tv, fmt, data) }); } + var labs = o.labels || [], title = String(o.title || ""); + var months = labs.length > 0 && labs.every(function (l) { return l.fmt === "month" && typeof l.v === "number"; }); + var year = months ? fromSerial(labs[0].v).y : 0; + var short = months && title.indexOf(String(year)) >= 0 && labs.every(function (l) { return fromSerial(l.v).y === year; }); + var mon = short && new Intl.DateTimeFormat(data.locale || "en-GB", { month: "short", timeZone: "UTC" }); + var full = labs.map(function (l) { return short ? mon.format(new Date(Date.UTC(year, fromSerial(l.v).m - 1, 1))) : String(l.text); }); + var cut = function (n) { return full.map(function (s) { return s.length > n ? s.slice(0, n - 1) + "…" : s; }); }, text = cut(20); + var widest = function (a) { return a.reduce(function (m, s) { return Math.max(m, measure(s)); }, 0); }; + var left = Math.min(Math.round(W * 0.4), Math.max(36, Math.ceil(widest(ticks.map(function (t) { return t.text; }))) + 14)), wl = widest(text), cnt = text.length || 1; + var gap = (W - left - RIGHT) / cnt, angle = 0, every = 1, bottom = FS + 18; + if (wl + 8 > gap) { + if (labs.every(function (l) { return typeof l.v === "number"; })) every = Math.ceil((wl + 8) / gap); + else { + text = cut(12); wl = widest(text); var drop = wl * Math.SQRT1_2; angle = 45; + left = Math.min(Math.round(W * 0.4), Math.max(left, Math.ceil(drop + 8 - gap / 2))); gap = (W - left - RIGHT) / cnt; + every = Math.ceil(FS * 1.3 / (gap * Math.SQRT1_2)); bottom = Math.ceil(drop + FS + 14); + } + } + var plot = Math.round(Math.min(224, Math.max(160, W * 0.5))), names = o.series || []; + return { ticks: ticks, top: ticks[n].v, labels: text, show: text.map(function (s, k) { return k % every === 0; }), angle: angle, every: every, + left: left, right: RIGHT, pad: PAD, gap: gap, plot: plot, height: PAD + plot + bottom, + key: !(names.length === 1 && title.toLowerCase().indexOf(String(names[0]).toLowerCase()) >= 0) }; + } + // --- .xlsx: a stored (uncompressed) zip of SpreadsheetML parts --- var CRC = (function () { var t = []; for (var n = 0; n < 256; n++) { var c = n; for (var k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })(); function crc32(b) { var c = 0xFFFFFFFF; for (var i = 0; i < b.length; i++) c = CRC[(c ^ b[i]) & 255] ^ (c >>> 8); return (c ^ 0xFFFFFFFF) >>> 0; } @@ -769,7 +805,7 @@

SHEET TITLE

book.order.forEach(function (n) { rules[n.toLowerCase()] = ruleHits(book, book.tabs[n.toLowerCase()]); }); return { values: values, rules: rules, delta: delta(data, overlay, book) }; } - return { Book: Book, parse: parse, fmtValue: fmtValue, cellFmt: cellFmt, xlsx: xlsx, csv: csv, report: report, expand: expand, parseAddr: parseAddr, addr: addr, colName: colName, isErr: isErr, serial: serial, NAMES: NAMES, applyDelta: applyDelta, BATCH: BATCH, LIMIT: LIMIT, isCell: isCell, drawSize: drawSize, kept: kept, cleanEdits: cleanEdits, mergeEdits: mergeEdits, map: map, calc: calc, ruleHits: ruleHits, makeFile: makeFile }; + return { Book: Book, parse: parse, fmtValue: fmtValue, cellFmt: cellFmt, chartAxes: chartAxes, xlsx: xlsx, csv: csv, report: report, expand: expand, parseAddr: parseAddr, addr: addr, colName: colName, isErr: isErr, serial: serial, NAMES: NAMES, applyDelta: applyDelta, BATCH: BATCH, LIMIT: LIMIT, isCell: isCell, drawSize: drawSize, kept: kept, cleanEdits: cleanEdits, mergeEdits: mergeEdits, map: map, calc: calc, ruleHits: ruleHits, makeFile: makeFile }; })(); if (typeof module !== "undefined") module.exports = SheetEngine; @@ -999,32 +1035,45 @@

SHEET TITLE

// --- charts: bar and line, from computed cells --- var PAL = ["#1a5fd0", "#e07b00", "#0f7b55", "#7a4fd1", "#b23a6a", "#5f6b7a"]; function seriesValues(tabName, range) { var out = []; E.expand(range).forEach(function (p) { var v = book.value(tabName, E.addr(p.r, p.c)); out.push(typeof v === "number" ? v : 0); }); return out; } + // Drawn at the width it's shown at (at most 860 px), so text keeps its size; drawn again when that width changes. + var chartW = 0, ruler = null; + function chartWidth() { var h = document.getElementById("charts"); return Math.min(860, Math.max(260, (h && h.clientWidth) || 760)); } + function measure(s) { + if (ruler === null) { var cv = document.createElement("canvas"); ruler = (cv.getContext && cv.getContext("2d")) || false; if (ruler) ruler.font = "12px " + getComputedStyle(document.body).fontFamily; } + return ruler ? ruler.measureText(s).width : s.length * 7; + } function renderCharts() { var host = document.getElementById("charts"); host.textContent = ""; - var tab = tabObj(); + var tab = tabObj(), W = chartW = chartWidth(); (tab.charts || []).forEach(function (ch, idx) { - var labels = E.expand(ch.labels).map(function (p) { var v = book.value(tab.name, E.addr(p.r, p.c)), raw = book.raw[tab.name.toLowerCase()][E.addr(p.r, p.c)]; return shown(v, E.cellFmt(tab, E.addr(p.r, p.c), raw) || (typeof v === "number" && v > 30000 && v < 80000 ? "month" : null)); }); + var labels = E.expand(ch.labels).map(function (p) { var a = E.addr(p.r, p.c), v = book.value(tab.name, a), raw = book.raw[tab.name.toLowerCase()][a], f = E.cellFmt(tab, a, raw) || (typeof v === "number" && v > 30000 && v < 80000 ? "month" : null); return { v: v, fmt: f, text: shown(v, f) }; }); var series = (ch.series || []).map(function (s) { return { name: s.name, vals: seriesValues(tab.name, s.range) }; }); var max = series.reduce(function (m, s) { return s.vals.reduce(function (n, v) { return v > n ? v : n; }, m); }, 0) || 1; - var W = 760, H = 300, L = 70, B = 60, T = 16, pw = W - L - 16, ph = H - T - B, n = labels.length || 1; + var ax = E.chartAxes({ labels: labels, max: max, fmt: ch.fmt || "int", title: ch.title, series: series.map(function (s) { return s.name; }), width: W, measure: measure, data: data }); + var L = ax.left, T = ax.pad, ph = ax.plot, H = ax.height, top = ax.top, step = ax.gap, base = T + ph; var box = el("figure", { class: "chart", "data-ss-id": "chart-" + slug(tab.name) + "-" + idx }); box.style.margin = "0"; box.appendChild(el("h3", null, ch.title || "")); var svgNS = "http://www.w3.org/2000/svg", svg = document.createElementNS(svgNS, "svg"); svg.setAttribute("viewBox", "0 0 " + W + " " + H); svg.setAttribute("role", "img"); svg.setAttribute("aria-label", (ch.title || "Chart") + ": " + series.map(function (s) { return s.name; }).join(", ")); function add(tag, at, text) { var nd = document.createElementNS(svgNS, tag); Object.keys(at).forEach(function (k) { nd.setAttribute(k, at[k]); }); if (text !== undefined) nd.textContent = text; svg.appendChild(nd); return nd; } - for (var k = 0; k <= 4; k++) { var y = T + ph - ph * k / 4; add("line", { x1: L, x2: W - 16, y1: y, y2: y, stroke: "#e5e7eb" }); add("text", { x: L - 8, y: y + 4, "text-anchor": "end", "font-size": 12, fill: "#52514a" }, E.fmtValue(max * k / 4, ch.fmt || "int", data)); } - var step = pw / n; - labels.forEach(function (lb, i) { add("text", { x: L + step * i + step / 2, y: H - B + 18, "text-anchor": "middle", "font-size": 12, fill: "#52514a" }, String(lb).slice(0, 12)); }); + ax.ticks.forEach(function (t) { var y = base - ph * t.v / top; add("line", { x1: L, x2: W - ax.right, y1: y, y2: y, stroke: "#e5e7eb" }); add("text", { x: L - 8, y: y + 4, "text-anchor": "end", "font-size": 12, fill: "#52514a" }, t.text); }); + ax.labels.forEach(function (lb, i) { + if (!ax.show[i]) return; + var x = L + step * i + step / 2; + if (ax.angle) add("text", { x: x + 4, y: base + 14, "text-anchor": "end", transform: "rotate(-" + ax.angle + " " + (x + 4) + " " + (base + 14) + ")", "font-size": 12, fill: "#52514a" }, lb); + else add("text", { x: x, y: base + 18, "text-anchor": "middle", "font-size": 12, fill: "#52514a" }, lb); + }); series.forEach(function (s, si) { var col = PAL[si % PAL.length]; - if (ch.type === "line") { var pts = s.vals.map(function (v, i) { return (L + step * i + step / 2) + "," + (T + ph - ph * v / max); }).join(" "); add("polyline", { points: pts, fill: "none", stroke: col, "stroke-width": 2.5 }); } - else { var bw = Math.max(2, (step * 0.8) / series.length); s.vals.forEach(function (v, i) { var h = ph * v / max; add("rect", { x: L + step * i + step * 0.1 + bw * si, y: T + ph - h, width: bw - 1, height: h, fill: col }); }); } + if (ch.type === "line") { var pts = s.vals.map(function (v, i) { return (L + step * i + step / 2) + "," + (base - ph * v / top); }).join(" "); add("polyline", { points: pts, fill: "none", stroke: col, "stroke-width": 2.5 }); } + else { var bw = Math.max(2, (step * 0.8) / series.length); s.vals.forEach(function (v, i) { var h = ph * v / top; add("rect", { x: L + step * i + step * 0.1 + bw * si, y: base - h, width: bw - 1, height: h, fill: col }); }); } }); box.appendChild(svg); - var keys = el("div", { class: "keys" }); series.forEach(function (s, si) { var sp = el("span"); sp.appendChild(el("i", { style: "background:" + PAL[si % PAL.length] })); sp.appendChild(document.createTextNode(s.name)); keys.appendChild(sp); }); - box.appendChild(keys); host.appendChild(box); + if (ax.key) { var keys = el("div", { class: "keys" }); series.forEach(function (s, si) { var sp = el("span"); sp.appendChild(el("i", { style: "background:" + PAL[si % PAL.length] })); sp.appendChild(document.createTextNode(s.name)); keys.appendChild(sp); }); box.appendChild(keys); } + host.appendChild(box); }); } + addEventListener("resize", function () { if (book && chartWidth() !== chartW) renderCharts(); }); // --- people's edits: one shared record each, newest edit to a cell wins --- function write(a, value) { if (!state.loaded || !state.signedIn) return; diff --git a/tests/run.js b/tests/run.js index 639174a..95f98f4 100644 --- a/tests/run.js +++ b/tests/run.js @@ -81,6 +81,71 @@ test("report lists every error cell", () => { assert.deepStrictEqual(errs.sort(), ["Summary!B10 #CYCLE!", "Summary!B11 #NAME?", "Summary!B12 #DIV/0!", "Summary!B13 #REF!", "Summary!B9 #CYCLE!", "Summary!C10 #CYCLE!"].sort()); }); +// --- a chart's axes: readable at a phone's width, round steps, no labels on top of each other --- +const GB = { locale: "en-GB", currency: "GBP" }; +const width7 = (s) => s.length * 7; // about system-ui at 12 px +const monthsOf = (y, n) => Array.from({ length: n }, (_, i) => { const v = E.serial(y + Math.floor(i / 12), i % 12 + 1, 1); return { v, fmt: "month", text: E.fmtValue(v, "month", GB) }; }); +// Each label drawn, where the page draws it: none may touch the next (4 px apart in a row, 12 px apart angled). +function assertApart(ax, what) { + const xs = ax.labels.map((s, i) => ({ s, x: ax.left + ax.gap * i + ax.gap / 2 })).filter((_, i) => ax.show[i]); + for (let i = 1; i < xs.length; i++) { + const a = xs[i - 1], b = xs[i], space = ax.angle ? (b.x - a.x) * Math.SQRT1_2 : b.x - a.x - (width7(a.s) + width7(b.s)) / 2; + assert.ok(space >= (ax.angle ? 12 : 4), `${what}: "${a.s}" and "${b.s}" are ${space.toFixed(1)} px apart`); + } + assert.ok(ax.show[0], `${what}: the first label shows`); +} +test("a chart's value axis steps are round: £0, £500, £1,000, £1,500, not quarters of the biggest bar", () => { + const ax = E.chartAxes({ labels: monthsOf(2026, 12), max: 1362, fmt: "money", title: "Revenue by month, 2026", series: ["Revenue"], width: 760, measure: width7, data: GB }); + assert.deepStrictEqual(Array.from(ax.ticks, (t) => t.text), ["£0", "£500", "£1,000", "£1,500"]); + assert.strictEqual(ax.top, 1500); + const pct = E.chartAxes({ labels: [], max: 0.83, fmt: "pct", width: 760, measure: width7, data: GB }); + assert.deepStrictEqual(Array.from(pct.ticks, (t) => t.text), ["0%", "20%", "40%", "60%", "80%", "100%"]); + const few = E.chartAxes({ labels: [], max: 3, fmt: "int", width: 760, measure: width7, data: GB }); + assert.deepStrictEqual(Array.from(few.ticks, (t) => t.text), ["0", "1", "2", "3"]); // whole numbers stay whole +}); +test("twelve months say Jan … Dec when the title names their year, and fit in a row at 1280 and thin to every other on a phone", () => { + const o = { labels: monthsOf(2026, 12), max: 1362, fmt: "money", title: "Revenue by month, 2026", series: ["Revenue"], measure: width7, data: GB }; + const wide = E.chartAxes(Object.assign({ width: 860 }, o)), phone = E.chartAxes(Object.assign({ width: 358 }, o)); + assert.deepStrictEqual(wide.labels, ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"]); + assert.deepStrictEqual([wide.every, wide.angle], [1, 0]); + assert.deepStrictEqual([phone.every, phone.angle], [2, 0]); + assertApart(wide, "1280"); assertApart(phone, "390"); + assert.strictEqual(phone.key, false); // the title names the only series +}); +test("months keep their year when the title doesn't name it, or they span two years, and still never touch", () => { + const noYear = E.chartAxes({ labels: monthsOf(2026, 12), max: 900, fmt: "money", title: "Revenue by month", width: 358, measure: width7, data: GB }); + assert.strictEqual(noYear.labels[0], "Jan 2026"); + assertApart(noYear, "no year in the title"); + const two = E.chartAxes({ labels: monthsOf(2025, 18), max: 900, fmt: "money", title: "Revenue, 2025", width: 860, measure: width7, data: GB }); + assert.strictEqual(two.labels[12], "Jan 2026"); + assertApart(two, "two years"); +}); +test("category names are angled so each still shows on a phone, and thinned only when even angled ones can't fit", () => { + const names = ["House Espresso", "Brazil Cerrado", "Colombia Huila", "Ethiopia Yirgacheffe", "Swiss Water Decaf"].map((s) => ({ v: s, fmt: null, text: s })); + const phone = E.chartAxes({ labels: names, max: 4200, fmt: "money", title: "Revenue by product", series: ["Revenue", "Orders"], width: 358, measure: width7, data: GB }); + assert.strictEqual(phone.angle, 45); + assert.deepStrictEqual(phone.show, [true, true, true, true, true]); + assert.strictEqual(phone.labels[3], "Ethiopia Yi…"); + assert.ok(phone.left - phone.labels.reduce((m, s) => Math.max(m, width7(s)), 0) * Math.SQRT1_2 + phone.gap / 2 >= 0, "the first angled label starts inside the chart"); + assert.strictEqual(phone.key, true); // two series need their key + const wide = E.chartAxes({ labels: names, max: 4200, fmt: "money", title: "Revenue by product", width: 860, measure: width7, data: GB }); + assert.deepStrictEqual([wide.angle, wide.labels[3]], [0, "Ethiopia Yirgacheffe"]); // room for the whole name in a row + assertApart(wide, "names at 1280"); + const many = Array.from({ length: 40 }, (_, i) => ({ v: "Branch " + (i + 1), fmt: null, text: "Branch " + (i + 1) })); + const crowded = E.chartAxes({ labels: many, max: 10, fmt: "int", width: 358, measure: width7, data: GB }); + assert.ok(crowded.every > 1); assertApart(crowded, "40 names"); + const days = Array.from({ length: 60 }, (_, i) => { const v = E.serial(2026, 11, 1) + i; return { v, fmt: "date", text: E.fmtValue(v, "date", GB) }; }); + assertApart(E.chartAxes({ labels: days, max: 10, fmt: "int", width: 358, measure: width7, data: GB }), "60 days"); +}); +test("a chart's axes come out whole for any values a sheet can hold", () => { + const vals = [0, -5, 1e-9, 0.5, 7, 1362, 1e15, 1e308, NaN]; + for (const max of vals) for (const fmt of ["money", "money2", "int", "num", "pct", "pct1", "nope"]) for (const width of [260, 358, 860]) { + const ax = E.chartAxes({ labels: [{ v: { e: "#REF!" }, fmt: null, text: "#REF!" }, { v: null, fmt: null, text: "" }, { v: 46000, fmt: "month", text: "x" }], max, fmt, width, measure: width7, data: GB }); + assert.ok(ax.ticks.length >= 2 && ax.ticks.length <= 12 && ax.ticks.every((t) => isFinite(t.v) && typeof t.text === "string"), `${max} ${fmt}`); + assert.ok(ax.top > 0 && isFinite(ax.top) && ax.every >= 1 && ax.height > ax.plot, `${max} ${fmt} ${width}`); + } +}); + // --- what the page's scripts may never do with cell data --- test("the page's scripts never write HTML or run text as code", () => { const code = script("sheet-engine") + script("sheet-ui"); From 564db7df0f6b303b234c47ba9fd68b4a11903970 Mon Sep 17 00:00:00 2001 From: James Briggs <35938317+jamescalam@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:44:17 +0800 Subject: [PATCH 03/10] Sheets: on a phone the grid starts on the first screen: the description folds to two lines, and one Download button At 390 px the title, six lines of description, two rows of buttons and the status came before the grid, which started at 438-460 px. Now, at phone width only: - The description shows two lines. "more" at the end of the second line, or a tap on the description, opens the rest; "less" folds it again. "more" shows only when there is more: checked after each draw, on resize, and when a push changes the description. - "Download CSV (this tab)" and "Download .xlsx (all tabs)" sit under one Download button, as "CSV (this tab)" and ".xlsx (all tabs)". It opens from the keyboard onto the first choice; Esc, a choice, or a tap outside closes it. The grid now starts at 321 px on both test sheets, with 10 rows whole on an 844 px screen (was 7-8). Every control stays at least 44 px. Wider screens draw the header exactly as before. The open states are a class and attributes the page never writes, so a save that morphs the page in place keeps them when it has the page before, and closes both cleanly when it doesn't. Also: Enter on a focused button now presses it. The grid's key handler took Enter to the formula bar from anywhere but a field, so Enter on "Show formulas" (or Download) did nothing. Co-authored-by: Pointman Co-authored-by: Claude --- sheets/references/sheet-template.html | 60 ++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 5 deletions(-) diff --git a/sheets/references/sheet-template.html b/sheets/references/sheet-template.html index 72d9374..7ee81ef 100644 --- a/sheets/references/sheet-template.html +++ b/sheets/references/sheet-template.html @@ -73,16 +73,43 @@ .keys i{display:inline-block;width:12px;height:12px;border-radius:2px;margin-right:4px;vertical-align:-1px} @media (max-width:600px){.grid th,.grid td{height:44px}.grid tr.frozen td,.grid tr.frozen th.rn{top:44px}.bar button,.tabs button,.fx input{min-height:44px}.wrap{max-height:62vh} .grid thead th:nth-child(2),.grid tbody td:first-of-type{min-width:0!important;max-width:42vw}} +/* On a phone the grid starts on the first screen: the description folds to two lines, and "more" (or a tap on it) + opens the rest; the two downloads sit under one Download button. Wider screens show both in full, as before. */ +.lede-more,.dl-btn{display:none} +.dl,.dl-menu{display:contents} +@media (max-width:600px){.ledebox{position:relative;margin:0 0 10px}.ledebox .lede{margin:0} +.ledebox:not(.open) .lede{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;line-clamp:2;overflow:hidden} +.ledebox.folds:not(.open) .lede{cursor:pointer} +.lede-more{display:flex;align-items:flex-end;min-height:44px;padding:0;border:none;background:none;color:var(--accent);font:inherit;font-weight:600;cursor:pointer} +.lede-more[hidden]{display:none} +.ledebox:not(.open) .lede-more{position:absolute;right:0;bottom:0;padding-left:32px;background:linear-gradient(to right,transparent,var(--paper) 28px) bottom/100% 1.45em no-repeat} +.ledebox.open .lede-more .m,.ledebox:not(.open) .lede-more .l{display:none} +.dl{display:block;position:relative} +.bar .dl-btn{display:inline-flex;align-items:center;gap:6px} +.dl-btn::after{content:"";width:7px;height:7px;border:solid currentColor;border-width:0 2px 2px 0;transform:translateY(-2px) rotate(45deg)} +.dl.open .dl-btn::after{transform:translateY(2px) rotate(-135deg)} +.dl-menu{display:none;position:absolute;left:0;top:calc(100% + 4px);z-index:20;flex-direction:column;gap:2px;min-width:200px;padding:4px;background:var(--cell);border:1px solid var(--line);border-radius:10px;box-shadow:0 8px 24px var(--edge)} +.dl.open .dl-menu{display:flex} +.bar .dl-menu button{border-color:transparent;text-align:left} +.dl-word{display:none}} .chart svg text{fill:var(--muted)}.chart svg line{stroke:var(--rule)}

SHEET TITLE

-

ONE OR TWO SENTENCES: what the sheet holds and who updates it.

+
+

ONE OR TWO SENTENCES: what the sheet holds and who updates it.

+ +
- - +
+ +
+ + +
+
Loading…
@@ -982,7 +1009,7 @@

SHEET TITLE

tb.appendChild(tr); } g.appendChild(tb); - renderBar(); renderLegend(); renderCharts(); renderStatus(); renderDelta(); edges(); settle(); + renderBar(); renderLegend(); renderCharts(); renderStatus(); renderDelta(); edges(); fold(); settle(); var sf = document.getElementById("show-f"); sf.setAttribute("aria-pressed", String(state.showF)); sf.textContent = state.showF ? "Show values" : "Show formulas"; } // A shade and "More columns" at the right edge while columns are hidden past it. @@ -1136,13 +1163,36 @@

SHEET TITLE

if (document.activeElement === fx || /INPUT|SELECT|TEXTAREA/.test((document.activeElement || {}).tagName || "")) return; var mv = E.map({ ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] })[e.key]; if (mv) { e.preventDefault(); move(mv[0], mv[1]); } - else if (e.key === "Enter" || e.key === "F2") { e.preventDefault(); fx.focus(); } + else if ((e.key === "Enter" && (document.activeElement || {}).tagName !== "BUTTON") || e.key === "F2") { e.preventDefault(); fx.focus(); } // Enter on a button presses it }); document.getElementById("show-f").onclick = function () { state.showF = !state.showF; render(); }; function download(name, type, bytes) { var url = URL.createObjectURL(new Blob([bytes], { type: type })), a = el("a", { href: url, download: name }); document.body.appendChild(a); a.click(); a.remove(); setTimeout(function () { URL.revokeObjectURL(url); }, 2000); } function base() { return slug(data.title || "sheet"); } document.getElementById("dl-csv").onclick = function () { var name = base() + "-" + slug(tabObj().name) + ".csv"; makeFile("csv", function (bytes) { download(name, "text/csv", bytes); }); }; document.getElementById("dl-xlsx").onclick = function () { makeFile("xlsx", function (bytes) { download(base() + ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", bytes); }); }; + // On a phone the two downloads open from one Download button. The open state is a class and an attribute the page + // never changes, so a save, which morphs the page in place, leaves it as the person set it. + var dl = document.getElementById("dl"), dlBtn = document.getElementById("dl-btn"); + function dlOpen(on, back) { dl.classList.toggle("open", on); dlBtn.setAttribute("aria-expanded", String(on)); if (back) dlBtn.focus(); } + dlBtn.onclick = function (e) { var on = !dl.classList.contains("open"); dlOpen(on); if (on && e.detail === 0) document.getElementById("dl-csv").focus(); }; // from the keyboard: onto the first choice + document.getElementById("dl-menu").addEventListener("click", function (e) { if (e.target.closest("button")) dlOpen(false); }); + document.addEventListener("click", function (e) { if (dl.classList.contains("open") && !dl.contains(e.target)) dlOpen(false); }); + document.addEventListener("keydown", function (e) { if (e.key === "Escape" && dl.classList.contains("open")) dlOpen(false, dl.contains(document.activeElement)); }); + // On a phone the description shows two lines; "more", or a tap on it, opens the rest. "more" shows only when + // there is more: checked after each draw, on resize, and when a push changes the description. + var ledeBox = document.getElementById("ledebox"), ledeMore = document.getElementById("lede-more"); + function fold() { + if (!ledeBox) return; // a draw before this part of the script has run + var p = ledeBox.querySelector(".lede"), open = ledeBox.classList.contains("open"); + var more = !!p && (open || p.scrollHeight > p.clientHeight + 1); + ledeMore.hidden = !more; ledeBox.classList.toggle("folds", more); ledeMore.setAttribute("aria-expanded", String(open)); + } + function ledeOpen(on) { ledeBox.classList.toggle("open", on); fold(); } + ledeMore.onclick = function (e) { e.stopPropagation(); ledeOpen(!ledeBox.classList.contains("open")); }; + ledeBox.addEventListener("click", function () { if (ledeBox.classList.contains("folds") && !ledeBox.classList.contains("open")) ledeOpen(true); }); + addEventListener("resize", fold); + document.addEventListener("ss:live", fold); + if (document.fonts && document.fonts.ready) document.fonts.ready.then(fold); // The person's place in this browser tab (tab, cell, scroll, typing), kept as it changes and put back at start, so // a whole-page rewrite or a reload doesn't lose it. Where storage is blocked, the page starts fresh as before. // The key is this sheet's address without a version's part (/v//, where a save reloads the frame) and without From e5ab035d2135e42f523de816f566028d9056dde7 Mon Sep 17 00:00:00 2001 From: James Briggs <35938317+jamescalam@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:58:57 +0800 Subject: [PATCH 04/10] Sheets: a value its format can't show is shown as it is, and can't stop the grid drawing or lose the edit Typing 1000000000 into a date or month cell made the formatter build a Date past what JS holds; Intl threw "Invalid time value", the grid stopped drawing (the cell's row was gone), the edit was never sent, and the status line still said "No error cells". - The engine's new show(v, fmt, data) gives a value's text and never throws: when the format can't take the value (a date past the dates a Date holds, a currency code Intl refuses), it gives the value as it is, marked bad. fmtValue says plainly "not a date" for such a serial, rather than leaving it to Intl. - The page shows values only through it. Each grid cell is drawn under its own guard, and each chart too: anything a cell can't draw shows its value as it is, marked, and the rest goes on. - Such a cell is marked as an error, and the status line names it: "C3 can't be shown in its format, so it shows the value as it is." - An edit is sent before the page draws it, so what was typed is kept even if something on the page can't show it. - CSV gives the number, not "NaN-aN-aN"; "What changed in this version" and chart labels show it too. In .xlsx it keeps its date format, which Excel shows as ####. Co-authored-by: Pointman Co-authored-by: Claude --- sheets/references/sheet-template.html | 57 ++++++++++++++++++++------- tests/hostile.js | 35 ++++++++++++++++ 2 files changed, 77 insertions(+), 15 deletions(-) diff --git a/sheets/references/sheet-template.html b/sheets/references/sheet-template.html index 7ee81ef..3e76cf3 100644 --- a/sheets/references/sheet-template.html +++ b/sheets/references/sheet-template.html @@ -193,6 +193,7 @@

SHEET TITLE

var EPOCH = Date.UTC(1899, 11, 30); function serial(y, m, d) { return Math.round((Date.UTC(y, m - 1, d) - EPOCH) / 864e5); } function fromSerial(n) { var t = new Date(EPOCH + Math.floor(n) * 864e5); return { y: t.getUTCFullYear(), m: t.getUTCMonth() + 1, d: t.getUTCDate(), wd: t.getUTCDay() }; } + function dateOk(n) { return typeof n === "number" && isFinite(n) && !isNaN(new Date(EPOCH + Math.floor(n) * 864e5).getTime()); } // a JS Date holds about 273,000 years either side of 1970 var ISO = /^(\d{4})-(\d{2})-(\d{2})$/; var DATEF = /^=\s*(DATE|EDATE|EOMONTH|TODAY|DATEVALUE|WORKDAY)\s*\(/i; // a formula that gives a date @@ -561,6 +562,13 @@

SHEET TITLE

// --- formats --- var SYM = map({ GBP: "£", USD: "$", EUR: "€" }); + // What a cell shows: its value in its format or, when the format can't take it (1000000000 as a date, a currency + // code Intl doesn't know), the value as it is, marked bad. It never throws: the page shows every value through it, + // so no value in one cell can stop the grid, a chart or the status drawing. It calls the exported fmtValue. + function show(v, fmt, data) { + try { return { text: api.fmtValue(v, fmt, data), bad: false }; } + catch (e) { return { text: v === null || v === undefined ? "" : isErr(v) ? v.e : String(v), bad: true }; } + } function fmtValue(v, fmt, data) { if (isErr(v)) return v.e; if (v === null || v === undefined) return ""; @@ -574,8 +582,8 @@

SHEET TITLE

case "num": return new Intl.NumberFormat(loc, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(v); case "pct": return new Intl.NumberFormat(loc, { style: "percent", maximumFractionDigits: 0 }).format(v); case "pct1": return new Intl.NumberFormat(loc, { style: "percent", minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(v); - case "date": { var d = fromSerial(v); return new Intl.DateTimeFormat(loc, { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(new Date(Date.UTC(d.y, d.m - 1, d.d))); } - case "month": { var e = fromSerial(v); return new Intl.DateTimeFormat(loc, { month: "short", year: "numeric", timeZone: "UTC" }).format(new Date(Date.UTC(e.y, e.m - 1, 1))); } + case "date": { if (!dateOk(v)) throw new RangeError("not a date"); var d = fromSerial(v); return new Intl.DateTimeFormat(loc, { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(new Date(Date.UTC(d.y, d.m - 1, d.d))); } + case "month": { if (!dateOk(v)) throw new RangeError("not a date"); var e = fromSerial(v); return new Intl.DateTimeFormat(loc, { month: "short", year: "numeric", timeZone: "UTC" }).format(new Date(Date.UTC(e.y, e.m - 1, 1))); } default: return new Intl.NumberFormat(loc, { maximumFractionDigits: 10 }).format(Math.round(v * 1e10) / 1e10); } } @@ -722,7 +730,7 @@

SHEET TITLE

var row = []; for (var c = 1; c <= sz.cols; c++) { var a = addr(r, c), ex = book.exported(tabName, a), v = ex.v, f = cellFmt(tab, a, ex.raw, ex.inp); - var s = isErr(v) ? v.e : v === null ? "" : (typeof v === "number" && (f === "date" || f === "month")) ? (function (d) { return d.y + "-" + ("0" + d.m).slice(-2) + "-" + ("0" + d.d).slice(-2); })(fromSerial(v)) : str(v); + var s = isErr(v) ? v.e : v === null ? "" : (typeof v === "number" && (f === "date" || f === "month") && dateOk(v)) ? (function (d) { return d.y + "-" + ("0" + d.m).slice(-2) + "-" + ("0" + d.d).slice(-2); })(fromSerial(v)) : str(v); if (typeof v === "string" && RISKY.test(s)) s = "'" + s; // text an app could read as a formula; numbers stay numbers row.push(/[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s); } @@ -805,7 +813,7 @@

SHEET TITLE

var nv = book.value(t.name, a), ov = ob.value(t.name, a); if (JSON.stringify(nv) === JSON.stringify(ov)) return; var p = parseAddr(a), head = book.value(t.name, addr(1, p.c)), rowName = book.value(t.name, addr(p.r, 1)), fmt = cellFmt(t, a, raw[a], inp); - out.push({ cell: t.name + "!" + a, label: [rowName, head].filter(function (v) { return typeof v === "string" && v; }).join(" · "), was: fmtValue(ov, fmt, data), now: fmtValue(nv, fmt, data) }); + out.push({ cell: t.name + "!" + a, label: [rowName, head].filter(function (v) { return typeof v === "string" && v; }).join(" · "), was: show(ov, fmt, data).text, now: show(nv, fmt, data).text }); }); }); return out; @@ -832,7 +840,8 @@

SHEET TITLE

book.order.forEach(function (n) { rules[n.toLowerCase()] = ruleHits(book, book.tabs[n.toLowerCase()]); }); return { values: values, rules: rules, delta: delta(data, overlay, book) }; } - return { Book: Book, parse: parse, fmtValue: fmtValue, cellFmt: cellFmt, chartAxes: chartAxes, xlsx: xlsx, csv: csv, report: report, expand: expand, parseAddr: parseAddr, addr: addr, colName: colName, isErr: isErr, serial: serial, NAMES: NAMES, applyDelta: applyDelta, BATCH: BATCH, LIMIT: LIMIT, isCell: isCell, drawSize: drawSize, kept: kept, cleanEdits: cleanEdits, mergeEdits: mergeEdits, map: map, calc: calc, ruleHits: ruleHits, makeFile: makeFile }; + var api = { Book: Book, parse: parse, fmtValue: fmtValue, show: show, cellFmt: cellFmt, chartAxes: chartAxes, xlsx: xlsx, csv: csv, report: report, expand: expand, parseAddr: parseAddr, addr: addr, colName: colName, isErr: isErr, serial: serial, NAMES: NAMES, applyDelta: applyDelta, BATCH: BATCH, LIMIT: LIMIT, isCell: isCell, drawSize: drawSize, kept: kept, cleanEdits: cleanEdits, mergeEdits: mergeEdits, map: map, calc: calc, ruleHits: ruleHits, makeFile: makeFile }; + return api; })(); if (typeof module !== "undefined") module.exports = SheetEngine; @@ -945,7 +954,9 @@

SHEET TITLE

if (calc.ver !== state.ver) { calc.ver = state.ver; recalc(); } formulas(function (key) { book.memo[key] = key in calc.vals ? calc.vals[key] : PENDING; }); // the page itself works nothing out } - function shown(v, fmt) { return v === PENDING ? "…" : E.fmtValue(v, fmt, data); } + // A value's text, never an exception (E.show). A cell its format can't show is noted for the status line. + var unshown = [], unchart = []; // per render: such cells on this tab, and charts that couldn't be drawn + function shown(v, fmt, a) { if (v === PENDING) return "…"; var s = E.show(v, fmt, data); if (s.bad && a) unshown.push(a); return s.text; } function tabObj() { return data.tabs[state.tab]; } function el(tag, attrs, text) { var n = document.createElement(tag); if (attrs) Object.keys(attrs).forEach(function (k) { n.setAttribute(k, attrs[k]); }); if (text !== undefined) n.textContent = text; return n; } // A tab's name in the link, with every character the viewer's # check doesn't take (!'()*~ too) as %XX. @@ -969,7 +980,7 @@

SHEET TITLE

function render() { rebuild(); renderTabs(); var tab = tabObj(); lookups = buildLookups(tab); var ds = E.drawSize(book, tab), rows = ds.rows, cols = ds.cols, k = E.kept(book, tab); state.cut = k.out ? k.rows : 0; state.out = k.out; - var g = document.getElementById("grid"); g.textContent = ""; + var g = document.getElementById("grid"); g.textContent = ""; unshown = []; unchart = []; var thead = el("thead"), hr = el("tr"); hr.appendChild(el("th", { class: "rn", scope: "col" }, "")); for (var c = 1; c <= cols; c++) { var th = el("th", { scope: "col" }, E.colName(c)); var w = (tab.cols || [])[c - 1]; if (w && w.w) th.style.minWidth = w.w + "px"; hr.appendChild(th); } thead.appendChild(hr); g.appendChild(thead); @@ -979,8 +990,10 @@

SHEET TITLE

var tr = el("tr"); if (tab.freeze && r <= tab.freeze) tr.className = "frozen"; tr.appendChild(el("th", { class: "rn", scope: "row" }, String(r))); for (var cc = 1; cc <= cols; cc++) { - var a = E.addr(r, cc), raw = book.raw[tname][a], v = book.value(tab.name, a), inp = book.input(tab.name, a); - var td = el("td", { "data-cell": a, "data-ss-id": "c-" + slug(tab.name) + "-" + a.toLowerCase() }); + var a = E.addr(r, cc), raw, v, inp, td; + try { + raw = book.raw[tname][a]; v = book.value(tab.name, a); inp = book.input(tab.name, a); + td = el("td", { "data-cell": a, "data-ss-id": "c-" + slug(tab.name) + "-" + a.toLowerCase() }); var fmt = E.cellFmt(tab, a, raw, inp), cls = []; if (typeof v === "number") cls.push("num"); if (E.isErr(v)) cls.push("error"); @@ -1002,7 +1015,11 @@

SHEET TITLE

sel.disabled = !state.loaded || !state.signedIn; (function (a) { sel.onchange = function (ev) { write(a, ev.target.value); }; })(a); td.appendChild(sel); - } else td.textContent = state.showF && inp && inp.formula !== undefined ? "=" + inp.formula : shown(v, fmt); + } else if (state.showF && inp && inp.formula !== undefined) td.textContent = "=" + inp.formula; + else { var had = unshown.length; td.textContent = shown(v, fmt, a); if (unshown.length > had) td.classList.add("error"); } // marked as well as named + } catch (e) { // anything else this cell can't draw: its value as it is, marked, and the grid goes on + td = el("td", { "data-cell": a, class: "error" }, v === undefined || v === null ? "" : E.isErr(v) ? v.e : String(v)); unshown.push(a); + } (function (a) { td.onclick = function (ev) { if (ev.target.tagName === "INPUT" || ev.target.tagName === "SELECT") return; select(a); }; td.ondblclick = function () { select(a); document.getElementById("fx").focus(); }; })(a); tr.appendChild(td); } @@ -1056,8 +1073,11 @@

SHEET TITLE

if (calc.here) who = "This page can't start a worker, so the sheet is worked out here, with a smaller limit. " + who; if (state.cut) who = "Only the first " + state.cut + " rows are drawn and downloaded; " + state.out + " more are left out. " + who; if (state.draft && state.draft.under) who = "The cell you're typing in changed: Enter keeps yours, Esc takes the new value. " + who; + var odd = unshown.length ? "⚠ " + (unshown.length > 1 ? unshown.length + " cells can't be shown in their format, so they show the value as it is: " + unshown.slice(0, 5).join(", ") + ". " : unshown[0] + " can't be shown in its format, so it shows the value as it is. ") : ""; + if (unchart.length) odd += "⚠ " + unchart.map(function (t) { return "“" + t + "”"; }).join(", ") + " can't be drawn. "; + if (odd) who = odd + who; if (rep.errors.length) { st.textContent = "⚠ " + rep.errors.length + " cell" + (rep.errors.length > 1 ? "s show" : " shows") + " an error: " + rep.errors.slice(0, 5).join(", ") + ". " + who; st.className = "status err"; } - else { st.textContent = "No error cells. " + who; st.className = "status"; } + else { st.textContent = odd ? who : "No error cells. " + who; st.className = odd ? "status err" : "status"; } } // --- charts: bar and line, from computed cells --- var PAL = ["#1a5fd0", "#e07b00", "#0f7b55", "#7a4fd1", "#b23a6a", "#5f6b7a"]; @@ -1072,7 +1092,13 @@

SHEET TITLE

function renderCharts() { var host = document.getElementById("charts"); host.textContent = ""; var tab = tabObj(), W = chartW = chartWidth(); - (tab.charts || []).forEach(function (ch, idx) { + (tab.charts || []).forEach(function (ch, idx) { try { drawChart(host, tab, ch, idx, W); } catch (e) { // the rest of the page goes on + var box = el("figure", { class: "chart", "data-ss-id": "chart-" + slug(tab.name) + "-" + idx }); box.style.margin = "0"; + box.appendChild(el("h3", null, ch.title || "")); box.appendChild(el("p", { class: "status err" }, "This chart can't be drawn from its cells.")); host.appendChild(box); unchart.push(ch.title || "a chart"); + } }); + } + function drawChart(host, tab, ch, idx, W) { + { var labels = E.expand(ch.labels).map(function (p) { var a = E.addr(p.r, p.c), v = book.value(tab.name, a), raw = book.raw[tab.name.toLowerCase()][a], f = E.cellFmt(tab, a, raw) || (typeof v === "number" && v > 30000 && v < 80000 ? "month" : null); return { v: v, fmt: f, text: shown(v, f) }; }); var series = (ch.series || []).map(function (s) { return { name: s.name, vals: seriesValues(tab.name, s.range) }; }); var max = series.reduce(function (m, s) { return s.vals.reduce(function (n, v) { return v > n ? v : n; }, m); }, 0) || 1; @@ -1098,19 +1124,20 @@

SHEET TITLE

box.appendChild(svg); if (ax.key) { var keys = el("div", { class: "keys" }); series.forEach(function (s, si) { var sp = el("span"); sp.appendChild(el("i", { style: "background:" + PAL[si % PAL.length] })); sp.appendChild(document.createTextNode(s.name)); keys.appendChild(sp); }); box.appendChild(keys); } host.appendChild(box); - }); + } } - addEventListener("resize", function () { if (book && chartWidth() !== chartW) renderCharts(); }); + addEventListener("resize", function () { if (book && chartWidth() !== chartW) { unchart = []; renderCharts(); renderStatus(); } }); // --- people's edits: one shared record each, newest edit to a cell wins --- function write(a, value) { if (!state.loaded || !state.signedIn) return; var tab = tabObj(), key = tab.name + "!" + a, v = value; if (typeof v === "string") { var s = v.trim(); if (s !== "" && s.charAt(0) !== "=" && !isNaN(Number(s.replace(/,/g, ""))) && !/^0\d/.test(s)) v = Number(s.replace(/,/g, "")); else if (/^(true|false)$/i.test(s)) v = /^true$/i.test(s); } state.mine[key] = { v: v, at: new Date().toISOString() }; state.ver++; state.draft = null; - render(); select(a); + // Sent before it's drawn: what they typed is kept even if something on the page can't show it. fetch(API + "/records/" + COL + "/mine", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ data: { edits: state.mine } }) }) .then(function (r) { if (!r.ok) throw new Error(r.status === 413 ? "Your edits are over the 32 KB a person can keep. Ask the owner to fold them into the sheet." : "Couldn't save (" + r.status + ")."); }) .catch(function (e) { var st = document.getElementById("status"); st.textContent = e.message; st.className = "status err"; }); + render(); select(a); } var settled = false; addEventListener("spacesheep:session", function (e) { settled = true; if (e.detail && e.detail.signed_in) load(0); }); diff --git a/tests/hostile.js b/tests/hostile.js index cfb3f81..9fd70ea 100644 --- a/tests/hostile.js +++ b/tests/hostile.js @@ -216,6 +216,41 @@ module.exports = function ({ E, test, script, within, ROOT }) { const whole = Buffer.from(E.xlsx(new E.Book({ tabs: [{ name: "T", cells: { A1: "=A9999+1", A9999: 99 } }] }))).toString("utf8"); assert.match(whole, /A9999\+1<\/f>/); // a whole workbook keeps its live formulas }); + // --- a value its format can't show --- + const plain = (o) => JSON.parse(JSON.stringify(o)); + test("a number past the dates a Date holds, in a date or month cell, is shown as it is and marked, never thrown", () => { + const GB = { locale: "en-GB", currency: "GBP" }; + assert.throws(() => E.fmtValue(1e9, "date", GB), /not a date/); // the formatter itself still refuses + for (const f of ["date", "month"]) for (const v of [1e9, -1e9, 1e300]) assert.deepStrictEqual(plain(E.show(v, f, GB)), { text: String(v), bad: true }); + assert.deepStrictEqual(plain(E.show(E.serial(2026, 11, 15), "date", GB)), { text: "15 Nov 2026", bad: false }); + assert.deepStrictEqual(plain(E.show(1e8, "month", GB)).bad, false); // the far end of what a Date holds still formats + assert.deepStrictEqual(plain(E.show(5, "money", { locale: "en-GB", currency: "not a code" })), { text: "5", bad: true }); // a currency Intl refuses, the same + const data = { tabs: [{ name: "T", freeze: 1, cols: [{ fmt: "month" }, { fmt: "date" }], cells: { A1: "Month", B1: "Due", A2: 1e9, B2: "=A2", A3: 46000 }, + charts: [{ type: "bar", title: "By month", labels: "A2:A3", series: [{ name: "n", range: "A2:A3" }] }] }], before: { "T!A2": 46000 } }; + const csv = E.makeFile("csv", data, {}, "T"); + assert.ok(csv.ok, "no CSV"); + assert.deepStrictEqual(csv.bytes.split("\r\n")[1], "1000000000,1000000000"); // the number, not NaN-aN-aN + assert.ok(E.makeFile("xlsx", data, {}, "T").ok); // the number with its date format: Excel shows it as #### + const ch = E.calc(data, {}).delta.filter((d) => d.cell === "T!B2")[0]; + assert.deepStrictEqual([ch.was, ch.now], ["9 Dec 2025", "1000000000"]); // what changed in this version, shown + const labels = [1e9, 46000].map((v) => ({ v, fmt: "month", text: E.show(v, "month", GB).text })); + const ax = E.chartAxes({ labels, max: 10, fmt: "int", title: "By month, 2025", width: 358, measure: (s) => s.length * 7, data: GB }); + assert.deepStrictEqual(ax.labels, ["1000000000", "Dec 2025"]); // a chart's labels don't throw either + }); + test("a formatter that throws leaves every value shown: the page shows values only through E.show, and draws each cell and chart under a guard", () => { + const real = E.fmtValue; + E.fmtValue = () => { throw new Error("a formatter that throws"); }; + try { + assert.deepStrictEqual([5, "text", null, true, { e: "#N/A" }].map((v) => plain(E.show(v, "int", {}))), + [{ text: "5", bad: true }, { text: "text", bad: true }, { text: "", bad: true }, { text: "true", bad: true }, { text: "#N/A", bad: true }]); + } finally { E.fmtValue = real; } + const ui = script("sheet-ui"); + assert.doesNotMatch(ui, /E\.fmtValue\(/); // no way round show() + assert.match(ui, /try \{\s*raw = book\.raw\[tname\]\[a\]; v = book\.value\(tab\.name, a\)/); // each cell under its own guard... + assert.match(ui, /\} catch \(e\) \{ \/\/ anything else this cell can't draw[^\n]*\n[^\n]*unshown\.push\(a\)/); // ...shown as it is, and named in the status + assert.match(ui, /try \{ drawChart\(host, tab, ch, idx, W\); \} catch \(e\)/); // each chart too + assert.match(ui, /fetch\(API \+ "\/records\/" \+ COL \+ "\/mine"[\s\S]{0,600}?\n render\(\); select\(a\);/); // an edit is sent before it's drawn + }); test("files are made by makeFile, within the budget: out of budget is a refusal, never a partial file", () => { const ok = E.makeFile("csv", { tabs: [{ name: "T", cells: { A1: 2, A2: "=A1*21" } }] }, {}, "T"); assert.deepStrictEqual([ok.ok, ok.bytes.split("\r\n")[1]], [true, "42"]); From 87c55858ccc1f557538ef01c5403de8fec549953 Mon Sep 17 00:00:00 2001 From: James Briggs <35938317+jamescalam@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:04:46 +0800 Subject: [PATCH 05/10] Sheets: the status line's warning is red on a line of its own, in the person's words; the usual sentence stays grey MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "⚠ C3 isn't a date, so it shows what you typed." ("isn't a month" for a month column; "aren't dates" for several; "its value as it is" where the value isn't the person's own edit; a format other than date or month says "can't be shown in its column's format".) Formula errors and charts that can't be drawn go on the same red line. "Edits save for everyone…" and the other notes stay in the status line's grey, as when nothing is wrong. Before, the whole line turned red. A value shown as it is starts at the cell's left, as typed text does, rather than right-aligned as a number. Co-authored-by: Pointman Co-authored-by: Claude --- sheets/references/sheet-template.html | 32 +++++++++++++++++++-------- tests/hostile.js | 2 +- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/sheets/references/sheet-template.html b/sheets/references/sheet-template.html index 3e76cf3..800a013 100644 --- a/sheets/references/sheet-template.html +++ b/sheets/references/sheet-template.html @@ -25,7 +25,8 @@ .bar button{min-height:40px;padding:0 14px;border:1px solid var(--line);border-radius:8px;background:var(--cell);color:var(--ink);font:inherit;cursor:pointer} .bar button:hover{border-color:var(--accent)} .status{font-size:13px;color:var(--muted)} -.status.err{color:var(--bad-ink);font-weight:600} +.status.err,.status .warn{color:var(--bad-ink);font-weight:600} +.status .warn{display:block} .tabs{display:flex;gap:4px;overflow-x:auto;border-bottom:1px solid var(--line);margin-top:6px} .tabs button{min-height:42px;padding:0 16px;border:1px solid transparent;border-bottom:none;border-radius:8px 8px 0 0;background:none;font:inherit;cursor:pointer;white-space:nowrap;color:var(--muted)} .tabs button[aria-selected=true]{background:var(--cell);border-color:var(--line);color:var(--ink);font-weight:600;margin-bottom:-1px} @@ -956,7 +957,7 @@

SHEET TITLE

} // A value's text, never an exception (E.show). A cell its format can't show is noted for the status line. var unshown = [], unchart = []; // per render: such cells on this tab, and charts that couldn't be drawn - function shown(v, fmt, a) { if (v === PENDING) return "…"; var s = E.show(v, fmt, data); if (s.bad && a) unshown.push(a); return s.text; } + function shown(v, fmt, a) { if (v === PENDING) return "…"; var s = E.show(v, fmt, data); if (s.bad && a) unshown.push({ a: a, fmt: fmt }); return s.text; } function tabObj() { return data.tabs[state.tab]; } function el(tag, attrs, text) { var n = document.createElement(tag); if (attrs) Object.keys(attrs).forEach(function (k) { n.setAttribute(k, attrs[k]); }); if (text !== undefined) n.textContent = text; return n; } // A tab's name in the link, with every character the viewer's # check doesn't take (!'()*~ too) as %XX. @@ -1016,9 +1017,9 @@

SHEET TITLE

(function (a) { sel.onchange = function (ev) { write(a, ev.target.value); }; })(a); td.appendChild(sel); } else if (state.showF && inp && inp.formula !== undefined) td.textContent = "=" + inp.formula; - else { var had = unshown.length; td.textContent = shown(v, fmt, a); if (unshown.length > had) td.classList.add("error"); } // marked as well as named + else { var had = unshown.length; td.textContent = shown(v, fmt, a); if (unshown.length > had) { td.classList.add("error"); td.classList.remove("num"); } } // marked, named, and from the left, as typed } catch (e) { // anything else this cell can't draw: its value as it is, marked, and the grid goes on - td = el("td", { "data-cell": a, class: "error" }, v === undefined || v === null ? "" : E.isErr(v) ? v.e : String(v)); unshown.push(a); + td = el("td", { "data-cell": a, class: "error" }, v === undefined || v === null ? "" : E.isErr(v) ? v.e : String(v)); unshown.push({ a: a, fmt: null }); } (function (a) { td.onclick = function (ev) { if (ev.target.tagName === "INPUT" || ev.target.tagName === "SELECT") return; select(a); }; td.ondblclick = function () { select(a); document.getElementById("fx").focus(); }; })(a); tr.appendChild(td); @@ -1073,11 +1074,24 @@

SHEET TITLE

if (calc.here) who = "This page can't start a worker, so the sheet is worked out here, with a smaller limit. " + who; if (state.cut) who = "Only the first " + state.cut + " rows are drawn and downloaded; " + state.out + " more are left out. " + who; if (state.draft && state.draft.under) who = "The cell you're typing in changed: Enter keeps yours, Esc takes the new value. " + who; - var odd = unshown.length ? "⚠ " + (unshown.length > 1 ? unshown.length + " cells can't be shown in their format, so they show the value as it is: " + unshown.slice(0, 5).join(", ") + ". " : unshown[0] + " can't be shown in its format, so it shows the value as it is. ") : ""; - if (unchart.length) odd += "⚠ " + unchart.map(function (t) { return "“" + t + "”"; }).join(", ") + " can't be drawn. "; - if (odd) who = odd + who; - if (rep.errors.length) { st.textContent = "⚠ " + rep.errors.length + " cell" + (rep.errors.length > 1 ? "s show" : " shows") + " an error: " + rep.errors.slice(0, 5).join(", ") + ". " + who; st.className = "status err"; } - else { st.textContent = odd ? who : "No error cells. " + who; st.className = odd ? "status err" : "status"; } + var warn = []; + if (rep.errors.length) warn.push("⚠ " + rep.errors.length + " cell" + (rep.errors.length > 1 ? "s show" : " shows") + " an error: " + rep.errors.slice(0, 5).join(", ") + "."); + if (unshown.length) warn.push("⚠ " + unshownLine(unshown)); + if (unchart.length) warn.push("⚠ " + unchart.map(function (t) { return "“" + t + "”"; }).join(", ") + " can't be drawn."); + st.textContent = ""; st.className = "status"; // red is for what's wrong, on its own line; the rest stays grey + if (warn.length) st.appendChild(el("span", { class: "warn" }, warn.join(" "))); + st.appendChild(document.createTextNode(warn.length ? who : "No error cells. " + who)); + } + // Cells a format couldn't show, in the person's words: "C3 isn't a date, so it shows what you typed." + function unshownLine(list) { + var KIND = { date: ["a date", "dates"], month: ["a month", "months"] }, mine = state.mine, tn = tabObj().name; + var k = KIND[list[0].fmt], same = !!k && list.every(function (u) { return u.fmt === list[0].fmt; }); + var yours = list.every(function (u) { return mine[tn + "!" + u.a]; }), one = list.length === 1; + var names = list.slice(0, 5).map(function (u) { return u.a; }), more = list.length - names.length; + var who2 = one ? names[0] : names.slice(0, -1).join(", ") + (more ? ", " + names[names.length - 1] + " and " + more + " more" : " and " + names[names.length - 1]); + var what = yours ? "what you typed" : one ? "its value as it is" : "their values as they are"; + if (same) return who2 + (one ? " isn't " + k[0] + ", so it shows " : " aren't " + k[1] + ", so they show ") + what + "."; + return who2 + (one ? " can't be shown in its column's format, so it shows " : " can't be shown in their columns' formats, so they show ") + what + "."; } // --- charts: bar and line, from computed cells --- var PAL = ["#1a5fd0", "#e07b00", "#0f7b55", "#7a4fd1", "#b23a6a", "#5f6b7a"]; diff --git a/tests/hostile.js b/tests/hostile.js index 9fd70ea..dbea861 100644 --- a/tests/hostile.js +++ b/tests/hostile.js @@ -247,7 +247,7 @@ module.exports = function ({ E, test, script, within, ROOT }) { const ui = script("sheet-ui"); assert.doesNotMatch(ui, /E\.fmtValue\(/); // no way round show() assert.match(ui, /try \{\s*raw = book\.raw\[tname\]\[a\]; v = book\.value\(tab\.name, a\)/); // each cell under its own guard... - assert.match(ui, /\} catch \(e\) \{ \/\/ anything else this cell can't draw[^\n]*\n[^\n]*unshown\.push\(a\)/); // ...shown as it is, and named in the status + assert.match(ui, /\} catch \(e\) \{ \/\/ anything else this cell can't draw[^\n]*\n[^\n]*unshown\.push\(\{ a: a/); // ...shown as it is, and named in the status assert.match(ui, /try \{ drawChart\(host, tab, ch, idx, W\); \} catch \(e\)/); // each chart too assert.match(ui, /fetch\(API \+ "\/records\/" \+ COL \+ "\/mine"[\s\S]{0,600}?\n render\(\); select\(a\);/); // an edit is sent before it's drawn }); From 1705f99be2b9cbf08a5ebd6e0ce9841dd8f9a54f Mon Sep 17 00:00:00 2001 From: James Briggs <35938317+jamescalam@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:08:32 +0800 Subject: [PATCH 06/10] Sheets: "More columns" sits at the grid's bottom-right, off the letters' row, and a drop-down's text stops short of its arrow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a phone the chip sat on the column letters' row, which never scrolls away, so it hid the letter of the last column in view for good. It now sits at the grid box's bottom-right. A sheet wider than its box gets 38 px of room under its last row (class "wide", which doesn't change while scrolling across, so nothing jumps), so scrolling down always clears whatever the chip covers. A drop-down drew the browser's own arrow over the end of its text ("Proposal sent" ran into it in a 130 px column). It now draws its own arrow in the theme's grey, and keeps 22 px clear for it; longer text ends in "…" before the arrow. Co-authored-by: Pointman Co-authored-by: Claude --- sheets/references/sheet-template.html | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/sheets/references/sheet-template.html b/sheets/references/sheet-template.html index 800a013..72a59c4 100644 --- a/sheets/references/sheet-template.html +++ b/sheets/references/sheet-template.html @@ -38,7 +38,10 @@ .wrap{overflow:auto;max-height:70vh;border:1px solid var(--line);border-radius:8px;overscroll-behavior-x:contain} .gridbox::after{content:"";position:absolute;top:1px;right:1px;bottom:1px;width:32px;border-radius:0 8px 8px 0;background:linear-gradient(to right,transparent,var(--edge));pointer-events:none;opacity:0;transition:opacity .15s} .gridbox.more-right::after{opacity:1} -.more{position:absolute;right:10px;top:7px;z-index:5;font:600 12px system-ui;color:var(--ink);background:var(--cell);border:1px solid var(--line);border-radius:999px;padding:3px 10px;pointer-events:none;display:none} +/* "More columns" sits at the box's bottom-right, not on the letters' row, which never scrolls away: a sheet wider than + its box gets room under its last row, so scrolling down always clears what the chip covers. */ +.gridbox.wide .wrap{padding-bottom:38px} +.more{position:absolute;right:10px;bottom:9px;z-index:5;font:600 12px system-ui;color:var(--ink);background:var(--cell);border:1px solid var(--line);border-radius:999px;padding:3px 10px;pointer-events:none;display:none} .gridbox.more-right .more{display:block} table.grid{border-collapse:separate;border-spacing:0;font-variant-numeric:tabular-nums} .grid th,.grid td{border-right:1px solid var(--line);border-bottom:1px solid var(--line);padding:0 8px;height:34px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:320px} @@ -61,7 +64,10 @@ .grid td.warn{background:var(--warn);color:var(--warn-ink)} .grid td.good{background:var(--good);color:var(--good-ink)} .grid td.error{color:var(--bad-ink);font-weight:600} -.grid td select{width:100%;min-height:30px;border:none;background:transparent;font:inherit} +/* A drop-down draws its own arrow, and its text stops short of it ("Proposal sent" ran into the browser's own). */ +.grid td select{-webkit-appearance:none;appearance:none;width:100%;min-height:30px;border:none;padding:0 22px 0 0;font:inherit;text-overflow:ellipsis;cursor:pointer; +background:linear-gradient(45deg,transparent 50%,var(--muted) 50%) calc(100% - 10px) 50%/5px 5px no-repeat,linear-gradient(135deg,var(--muted) 50%,transparent 50%) calc(100% - 5px) 50%/5px 5px no-repeat} +.grid td select:disabled{cursor:default} .grid td input[type=checkbox]{width:20px;height:20px;margin:0;vertical-align:middle} .legend[hidden]{display:none} .legend{display:flex;flex-wrap:wrap;gap:14px;font-size:13px;color:var(--muted);margin:8px 0} @@ -1031,7 +1037,7 @@

SHEET TITLE

var sf = document.getElementById("show-f"); sf.setAttribute("aria-pressed", String(state.showF)); sf.textContent = state.showF ? "Show values" : "Show formulas"; } // A shade and "More columns" at the right edge while columns are hidden past it. - function edges() { var w = document.getElementById("wrap"); document.getElementById("gridbox").classList.toggle("more-right", w.scrollLeft + w.clientWidth < w.scrollWidth - 2); } + function edges() { var w = document.getElementById("wrap"), g = document.getElementById("gridbox"); g.classList.toggle("wide", w.scrollWidth > w.clientWidth + 2); g.classList.toggle("more-right", w.scrollLeft + w.clientWidth < w.scrollWidth - 2); } // wide: stays put while scrolling across, so nothing jumps document.getElementById("wrap").addEventListener("scroll", edges, { passive: true }); addEventListener("resize", edges); var deltaRows = null; From 3af71a31d32f0627848f9014d7c70136fbce4f51 Mon Sep 17 00:00:00 2001 From: James Briggs <35938317+jamescalam@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:09:37 +0800 Subject: [PATCH 07/10] =?UTF-8?q?Sheets:=20row=20numbers=20from=20200=20up?= =?UTF-8?q?=20are=20whole,=20not=20"2=E2=80=A6"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The row-number column was 40 px with 8 px of padding a side, so any three-digit number with wide digits (200, 888) and every four-digit one ended in "…". A tab can draw up to 10,000 rows. The column is now 40 px up to row 999 and 8 px wider for each digit after (the page sets --rn from the rows it draws), with 6 px padding and even-width digits. The first column's sticky edge follows it. Co-authored-by: Pointman Co-authored-by: Claude --- sheets/references/sheet-template.html | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/sheets/references/sheet-template.html b/sheets/references/sheet-template.html index 72a59c4..c03deb3 100644 --- a/sheets/references/sheet-template.html +++ b/sheets/references/sheet-template.html @@ -46,10 +46,12 @@ table.grid{border-collapse:separate;border-spacing:0;font-variant-numeric:tabular-nums} .grid th,.grid td{border-right:1px solid var(--line);border-bottom:1px solid var(--line);padding:0 8px;height:34px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:320px} .grid thead th{position:sticky;top:0;background:var(--head);z-index:2;font:600 12px system-ui;color:var(--muted);text-align:center} -.grid th.rn{position:sticky;left:0;background:var(--head);z-index:1;font:600 12px system-ui;color:var(--muted);width:40px;min-width:40px;max-width:40px;text-align:center} +/* Row numbers: 40 px up to row 999, then 8 px a digit more (the page sets --rn), so row 200 isn't "2…". */ +.grid{--rn:40px} +.grid th.rn{position:sticky;left:0;background:var(--head);z-index:1;font:600 12px system-ui;font-variant-numeric:tabular-nums;color:var(--muted);width:var(--rn);min-width:var(--rn);max-width:var(--rn);padding:0 6px;text-align:center} .grid thead th.rn{z-index:3} -.grid thead th:nth-child(2){position:sticky;left:40px;z-index:3} -.grid tbody td:first-of-type{position:sticky;left:40px;z-index:1;border-right-color:var(--muted)} +.grid thead th:nth-child(2){position:sticky;left:var(--rn);z-index:3} +.grid tbody td:first-of-type{position:sticky;left:var(--rn);z-index:1;border-right-color:var(--muted)} .grid tr.frozen td:first-of-type{z-index:2} .grid tr.frozen th.rn{position:sticky;top:34px;left:0;z-index:3} .grid td{background:var(--cell);cursor:cell} @@ -988,6 +990,7 @@

SHEET TITLE

rebuild(); renderTabs(); var tab = tabObj(); lookups = buildLookups(tab); var ds = E.drawSize(book, tab), rows = ds.rows, cols = ds.cols, k = E.kept(book, tab); state.cut = k.out ? k.rows : 0; state.out = k.out; var g = document.getElementById("grid"); g.textContent = ""; unshown = []; unchart = []; + g.style.setProperty("--rn", Math.max(40, 16 + 8 * String(rows).length) + "px"); // room for the last row's number var thead = el("thead"), hr = el("tr"); hr.appendChild(el("th", { class: "rn", scope: "col" }, "")); for (var c = 1; c <= cols; c++) { var th = el("th", { scope: "col" }, E.colName(c)); var w = (tab.cols || [])[c - 1]; if (w && w.w) th.style.minWidth = w.w + "px"; hr.appendChild(th); } thead.appendChild(hr); g.appendChild(thead); From a4f81d0fde1a887e69419994b612a5adb92bd1c8 Mon Sep 17 00:00:00 2001 From: James Briggs <35938317+jamescalam@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:15:37 +0800 Subject: [PATCH 08/10] Sheets: "More columns" sits in the tabs row, right-aligned, over nothing At the grid's bottom-right it no longer hid a column letter, but it hid a cell's words. It now sits at the right end of the tabs row: above the grid, on the first screen, covering nothing. When the tabs leave no room beside it, it takes a line of its own below them (class "below", set when the tabs would scroll with the chip beside them). It shows while the sheet is wider than its box, and hides once scrolled to the last column, keeping its room so nothing moves. The 38 px under the last row goes. Co-authored-by: Pointman Co-authored-by: Claude --- sheets/references/sheet-template.html | 28 ++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/sheets/references/sheet-template.html b/sheets/references/sheet-template.html index c03deb3..e33b56a 100644 --- a/sheets/references/sheet-template.html +++ b/sheets/references/sheet-template.html @@ -27,7 +27,13 @@ .status{font-size:13px;color:var(--muted)} .status.err,.status .warn{color:var(--bad-ink);font-weight:600} .status .warn{display:block} -.tabs{display:flex;gap:4px;overflow-x:auto;border-bottom:1px solid var(--line);margin-top:6px} +/* The tabs row holds the tabs and, at its right end, "More columns": above the grid, over nothing. When the tabs leave + no room for it, it takes a line of its own below them (.below, set by the page). */ +.tabrow{display:flex;align-items:center;gap:8px;margin-top:6px;border-bottom:1px solid var(--line)} +.tabs{display:flex;gap:4px;overflow-x:auto;flex:1 1 auto;min-width:0} +.tabrow.below{flex-wrap:wrap;border-bottom:none} +.tabrow.below .tabs{flex-basis:100%;border-bottom:1px solid var(--line)} +.tabrow.below .more{margin:0 0 0 auto} .tabs button{min-height:42px;padding:0 16px;border:1px solid transparent;border-bottom:none;border-radius:8px 8px 0 0;background:none;font:inherit;cursor:pointer;white-space:nowrap;color:var(--muted)} .tabs button[aria-selected=true]{background:var(--cell);border-color:var(--line);color:var(--ink);font-weight:600;margin-bottom:-1px} .fx{display:flex;gap:8px;align-items:center;margin:8px 0} @@ -38,11 +44,10 @@ .wrap{overflow:auto;max-height:70vh;border:1px solid var(--line);border-radius:8px;overscroll-behavior-x:contain} .gridbox::after{content:"";position:absolute;top:1px;right:1px;bottom:1px;width:32px;border-radius:0 8px 8px 0;background:linear-gradient(to right,transparent,var(--edge));pointer-events:none;opacity:0;transition:opacity .15s} .gridbox.more-right::after{opacity:1} -/* "More columns" sits at the box's bottom-right, not on the letters' row, which never scrolls away: a sheet wider than - its box gets room under its last row, so scrolling down always clears what the chip covers. */ -.gridbox.wide .wrap{padding-bottom:38px} -.more{position:absolute;right:10px;bottom:9px;z-index:5;font:600 12px system-ui;color:var(--ink);background:var(--cell);border:1px solid var(--line);border-radius:999px;padding:3px 10px;pointer-events:none;display:none} -.gridbox.more-right .more{display:block} +/* Shown while the sheet is wider than its box; hidden, keeping its room, once scrolled to the last column. */ +.more{flex:none;font:600 12px system-ui;color:var(--ink);background:var(--cell);border:1px solid var(--line);border-radius:999px;padding:3px 10px;white-space:nowrap;display:none;visibility:hidden} +.tabrow.wide .more{display:block} +.tabrow.more-right .more{visibility:visible} table.grid{border-collapse:separate;border-spacing:0;font-variant-numeric:tabular-nums} .grid th,.grid td{border-right:1px solid var(--line);border-bottom:1px solid var(--line);padding:0 8px;height:34px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:320px} .grid thead th{position:sticky;top:0;background:var(--head);z-index:2;font:600 12px system-ui;color:var(--muted);text-align:center} @@ -123,9 +128,9 @@

SHEET TITLE

Loading…
- +
A1
-
+
@@ -1040,7 +1045,12 @@

SHEET TITLE

var sf = document.getElementById("show-f"); sf.setAttribute("aria-pressed", String(state.showF)); sf.textContent = state.showF ? "Show values" : "Show formulas"; } // A shade and "More columns" at the right edge while columns are hidden past it. - function edges() { var w = document.getElementById("wrap"), g = document.getElementById("gridbox"); g.classList.toggle("wide", w.scrollWidth > w.clientWidth + 2); g.classList.toggle("more-right", w.scrollLeft + w.clientWidth < w.scrollWidth - 2); } // wide: stays put while scrolling across, so nothing jumps + function edges() { + var w = document.getElementById("wrap"), row = document.getElementById("tabrow"), wide = w.scrollWidth > w.clientWidth + 2, right = w.scrollLeft + w.clientWidth < w.scrollWidth - 2; + document.getElementById("gridbox").classList.toggle("more-right", right); // the shade at the right edge + row.classList.toggle("wide", wide); row.classList.toggle("more-right", right); // "wide" doesn't change while scrolling across, so nothing moves + if (wide) { row.classList.remove("below"); var nav = document.getElementById("tabs"); row.classList.toggle("below", nav.scrollWidth > nav.clientWidth + 1); } // beside the chip, the tabs would scroll: the chip goes below + } document.getElementById("wrap").addEventListener("scroll", edges, { passive: true }); addEventListener("resize", edges); var deltaRows = null; From 81e5e7ab7891a4838eb5f23384fa90953ac73487 Mon Sep 17 00:00:00 2001 From: James Briggs <35938317+jamescalam@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:25:05 +0800 Subject: [PATCH 09/10] Sheets: leaving the formula bar sends only the edit the person made, and a tap on another cell keeps the tap After Enter in a date column, the selection moved down and the bar showed the next cell's date as typed (2026-10-13). Its change handler compared the bar with the cell's serial, so the next tap or click anywhere sent that cell as an edit nobody made: marked "Edited by" for others, overriding the agent's later changes to it, and counted toward the 32 KB a person can keep. - barText() gives the text the bar shows for a cell; the bar and the change handler both use it. - Leaving the bar with a typed change still saves it, in the cell and tab it was typed in, but just after the tap or click that left it (a mouse leaves on press, so it waits for the release; a finger leaves after lifting, with the click). Before, the save redrew the grid between press and release, so the tapped cell was never selected. write() takes the tab and can keep the selection. - A test that no two of a script's top-level functions share a name: the first version of this named its helper send(), which replaced the calc's own send() and broke working the sheet out. Co-authored-by: Pointman Co-authored-by: Claude --- sheets/references/sheet-template.html | 26 ++++++++++++++++++++------ tests/hostile.js | 17 ++++++++++++++++- 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/sheets/references/sheet-template.html b/sheets/references/sheet-template.html index e33b56a..75d6399 100644 --- a/sheets/references/sheet-template.html +++ b/sheets/references/sheet-template.html @@ -1072,10 +1072,13 @@

SHEET TITLE

} // What a person is typing is theirs: no redraw writes over it, and it outlasts a rewrite or a reload. function drafting() { var d = state.draft; return d && d.tab === tabObj().name && d.cell === state.sel ? d : null; } + // What the formula bar shows for a cell: its formula, or what was typed (a date as typed, 2026-10-13). The bar's + // change handler compares with the same text, so leaving the bar never sends an edit nobody made. + function barText(tab, a) { var inp = book.input(tab.name, a); return !inp ? "" : inp.formula !== undefined ? "=" + inp.formula : inp.value === null ? "" : (inp.date ? book.raw[tab.name.toLowerCase()][a].v : String(inp.value)); } function renderBar() { - var tab = tabObj(), inp = book.input(tab.name, state.sel), fx = document.getElementById("fx"), d = drafting(); + var tab = tabObj(), fx = document.getElementById("fx"), d = drafting(); document.getElementById("addr").textContent = tab.name + "!" + state.sel; - fx.value = d ? d.text : !inp ? "" : inp.formula !== undefined ? "=" + inp.formula : inp.value === null ? "" : (inp.date ? book.raw[tab.name.toLowerCase()][state.sel].v : String(inp.value)); + fx.value = d ? d.text : barText(tab, state.sel); fx.disabled = !state.loaded || !state.signedIn; if (state.refocus && d && !fx.disabled) { state.refocus = false; fx.focus(); } // back to the half-typed text after a reload } @@ -1161,16 +1164,16 @@

SHEET TITLE

} addEventListener("resize", function () { if (book && chartWidth() !== chartW) { unchart = []; renderCharts(); renderStatus(); } }); // --- people's edits: one shared record each, newest edit to a cell wins --- - function write(a, value) { + function write(a, value, stay, tabName) { // stay: keep the selection where it is (the person has moved on); tabName: the tab it was typed in if (!state.loaded || !state.signedIn) return; - var tab = tabObj(), key = tab.name + "!" + a, v = value; + var key = (tabName || tabObj().name) + "!" + a, v = value; if (typeof v === "string") { var s = v.trim(); if (s !== "" && s.charAt(0) !== "=" && !isNaN(Number(s.replace(/,/g, ""))) && !/^0\d/.test(s)) v = Number(s.replace(/,/g, "")); else if (/^(true|false)$/i.test(s)) v = /^true$/i.test(s); } state.mine[key] = { v: v, at: new Date().toISOString() }; state.ver++; state.draft = null; // Sent before it's drawn: what they typed is kept even if something on the page can't show it. fetch(API + "/records/" + COL + "/mine", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ data: { edits: state.mine } }) }) .then(function (r) { if (!r.ok) throw new Error(r.status === 413 ? "Your edits are over the 32 KB a person can keep. Ask the owner to fold them into the sheet." : "Couldn't save (" + r.status + ")."); }) .catch(function (e) { var st = document.getElementById("status"); st.textContent = e.message; st.className = "status err"; }); - render(); select(a); + render(); select(stay ? state.sel : a); } var settled = false; addEventListener("spacesheep:session", function (e) { settled = true; if (e.detail && e.detail.signed_in) load(0); }); @@ -1218,7 +1221,18 @@

SHEET TITLE

if (e.key === "Escape") { state.draft = null; render(); fx.blur(); keepPlace(); } }); fx.addEventListener("input", function () { var d = drafting(); state.draft = { tab: tabObj().name, cell: state.sel, text: fx.value, under: !!(d && d.under) }; keepPlace(); }); - fx.addEventListener("change", function () { var inp = book.input(tabObj().name, state.sel), cur = !inp ? "" : inp.formula !== undefined ? "=" + inp.formula : inp.value === null ? "" : String(inp.value); if (fx.value !== cur) write(state.sel, fx.value); }); + // Leaving the bar keeps what was typed, in the cell and tab it was typed in. It's sent just after the tap or click + // that left it, so the redraw doesn't take the tapped cell from under the tap, and the tapped cell stays selected. + // A mouse leaves the bar on press: then it waits for the release. A finger leaves it after lifting, with the click. + var down = false, held = null; + function keepTyped(h) { setTimeout(function () { write(h[0], h[1], true, h[2]); }, 0); } + fx.addEventListener("change", function () { + if (fx.value === barText(tabObj(), state.sel)) return; + var h = [state.sel, fx.value, tabObj().name]; + if (down) held = h; else keepTyped(h); + }); + addEventListener("pointerdown", function () { down = true; }, true); + ["pointerup", "pointercancel"].forEach(function (t) { addEventListener(t, function () { down = false; if (held) { keepTyped(held); held = null; } }, true); }); document.addEventListener("keydown", function (e) { if (document.activeElement === fx || /INPUT|SELECT|TEXTAREA/.test((document.activeElement || {}).tagName || "")) return; var mv = E.map({ ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] })[e.key]; diff --git a/tests/hostile.js b/tests/hostile.js index dbea861..75c8fef 100644 --- a/tests/hostile.js +++ b/tests/hostile.js @@ -249,7 +249,22 @@ module.exports = function ({ E, test, script, within, ROOT }) { assert.match(ui, /try \{\s*raw = book\.raw\[tname\]\[a\]; v = book\.value\(tab\.name, a\)/); // each cell under its own guard... assert.match(ui, /\} catch \(e\) \{ \/\/ anything else this cell can't draw[^\n]*\n[^\n]*unshown\.push\(\{ a: a/); // ...shown as it is, and named in the status assert.match(ui, /try \{ drawChart\(host, tab, ch, idx, W\); \} catch \(e\)/); // each chart too - assert.match(ui, /fetch\(API \+ "\/records\/" \+ COL \+ "\/mine"[\s\S]{0,600}?\n render\(\); select\(a\);/); // an edit is sent before it's drawn + assert.match(ui, /fetch\(API \+ "\/records\/" \+ COL \+ "\/mine"[\s\S]{0,600}?\n render\(\); select\(stay \? state\.sel : a\);/); // an edit is sent before it's drawn + }); + test("leaving the formula bar sends an edit only when its text changed: the bar and its check share one text, a date as typed", () => { + const ui = script("sheet-ui"); + assert.match(ui, /function barText\(tab, a\) \{[^\n]*inp\.date \? book\.raw\[tab\.name\.toLowerCase\(\)\]\[a\]\.v/); // 2026-10-13, as typed, not the serial + assert.match(ui, /fx\.value = d \? d\.text : barText\(tab, state\.sel\);/); // what the bar shows... + assert.match(ui, /if \(fx\.value === barText\(tabObj\(\), state\.sel\)\) return;/); // ...is what leaving it compares with + assert.match(ui, /var h = \[state\.sel, fx\.value, tabObj\(\)\.name\];\s*if \(down\) held = h; else keepTyped\(h\);/); // in the cell and tab it was typed in, after the tap + assert.match(ui, /setTimeout\(function \(\) \{ write\(h\[0\], h\[1\], true, h\[2\]\); \}, 0\)/); // ...keeping the tapped cell selected + }); + test("no two of a script's own functions share a name, so a new one can't quietly replace another", () => { + for (const id of ["sheet-engine", "sheet-ui"]) { + const names = [...script(id).matchAll(/^ function (\w+)\(/gm)].map((m) => m[1]); // the script's top level + assert.ok(names.length > 20, id + ": too few functions found to check"); + assert.deepStrictEqual(names.filter((n, i) => names.indexOf(n) !== i), [], id + " declares the same function twice"); + } }); test("files are made by makeFile, within the budget: out of budget is a refusal, never a partial file", () => { const ok = E.makeFile("csv", { tabs: [{ name: "T", cells: { A1: 2, A2: "=A1*21" } }] }, {}, "T"); From f24e254be0e4874baca3bd823ae66521fc06354f Mon Sep 17 00:00:00 2001 From: James Briggs <35938317+jamescalam@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:28:01 +0800 Subject: [PATCH 10/10] Changelog: v2.0.1 Co-authored-by: Pointman Co-authored-by: Claude --- CHANGELOG.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index dcd109e..f4eac8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ Each release is a heading with its tag. The release workflow uses the words under it as the release's notes. +## v2.0.1 + +- On a phone the sheet starts on the first screen. The description folds to two lines with "more", and the two downloads sit under one Download button. +- A chart is drawn at the width it's shown at, so its labels stay 12 px on a phone and don't touch at any width. Its value steps are round (£0, £500, £1,000), month labels drop a year the title names, and one series the title names has no key. +- One value a column's format can't show, like 1000000000 typed into a date column, no longer stops the grid drawing or loses the edit. It shows as typed, marked, and the status line says why: "C3 isn't a date, so it shows what you typed." +- Every cell and chart is drawn on its own, so one that fails can't stop the rest. The status line's warnings are red on a line of their own; the rest stays grey. +- Leaving the formula bar sends only the edit the person made. Before, after Enter in a date column, the next tap saved the cell below as their edit, and could lose the tap. +- A formula whose ranges add up past the limit shows `#CALC!` at once, instead of reading millions of cells first. +- "More columns" sits in the tabs row, over nothing. A drop-down's text stops short of its arrow, and row numbers past 199 show whole. +- Enter on a focused button presses it. +- The folder's hash is `36168641a830`. + ## v2.0.0 - The sheet fills in while it's built. Within about 20 seconds the space shows the title, the named tabs and what the agent is doing. Each tab's rows then arrive in batches, outlined as they land, on every open tab. The last save says it's done, and the "working on this page" card goes away.