diff --git a/sheets/references/sheet-template.html b/sheets/references/sheet-template.html index 81ac251..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…
@@ -394,7 +421,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 +430,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 +441,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 +539,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 = []; @@ -542,6 +588,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; } @@ -750,7 +832,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; @@ -927,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. @@ -980,32 +1062,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; @@ -1068,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 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); 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");