diff --git a/sheets/references/sheet-template.html b/sheets/references/sheet-template.html index 81ac251..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} @@ -73,16 +74,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…
@@ -166,6 +194,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 @@ -394,7 +423,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 +432,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 +443,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 +541,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 = []; @@ -515,6 +563,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 ""; @@ -528,8 +583,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); } } @@ -542,6 +597,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; } @@ -640,7 +731,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); } @@ -723,7 +814,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; @@ -750,7 +841,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, 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; @@ -863,7 +955,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: 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. @@ -887,7 +981,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); @@ -897,8 +991,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"); @@ -920,14 +1016,18 @@

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"); 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: 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); } 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. @@ -974,48 +1074,84 @@

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; - 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"; } + 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"]; 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(); - (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 tab = tabObj(), W = chartW = chartWidth(); + (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; - 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) { 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); }); @@ -1068,13 +1204,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..dbea861 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); @@ -197,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: 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"]); 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");